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/scenario.py | add_resourcegroupitems | def add_resourcegroupitems(scenario_id, items, scenario=None, **kwargs):
"""
Get all the items in a group, in a scenario.
"""
user_id = int(kwargs.get('user_id'))
if scenario is None:
scenario = _get_scenario(scenario_id, user_id)
_check_network_ownership(scenario.network_id, user_id)
newitems = []
for group_item in items:
group_item_i = _add_resourcegroupitem(group_item, scenario.id)
newitems.append(group_item_i)
db.DBSession.flush()
return newitems | python | def add_resourcegroupitems(scenario_id, items, scenario=None, **kwargs):
"""
Get all the items in a group, in a scenario.
"""
user_id = int(kwargs.get('user_id'))
if scenario is None:
scenario = _get_scenario(scenario_id, user_id)
_check_network_ownership(scenario.network_id, user_id)
newitems = []
for group_item in items:
group_item_i = _add_resourcegroupitem(group_item, scenario.id)
newitems.append(group_item_i)
db.DBSession.flush()
return newitems | [
"def",
"add_resourcegroupitems",
"(",
"scenario_id",
",",
"items",
",",
"scenario",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"int",
"(",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
")",
"if",
"scenario",
"is",
"None",
":",
"scen... | Get all the items in a group, in a scenario. | [
"Get",
"all",
"the",
"items",
"in",
"a",
"group",
"in",
"a",
"scenario",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/scenario.py#L1089-L1108 | train | 46,000 |
hydraplatform/hydra-base | hydra_base/lib/plugins.py | get_plugins | def get_plugins(**kwargs):
"""
Get all available plugins
"""
plugins = []
plugin_paths = []
#Look in directory or set of directories for
#plugins
base_plugin_dir = config.get('plugin', 'default_directory')
plugin_xsd_path = config.get('plugin', 'plugin_xsd_path')
base_plugin_dir_contents = os.listdir(base_plugin_dir)
for directory in base_plugin_dir_contents:
#ignore hidden files
if directory[0] == '.' or directory == 'xml':
continue
#Is this a file or a directory? If it's a directory, it's a plugin.
path = os.path.join(base_plugin_dir, directory)
if os.path.isdir(path):
plugin_paths.append(path)
#For each plugin, get its details (an XML string)
#Retrieve the xml schema for validating the XML to make sure
#what is being provided to the IU is correct.
xmlschema_doc = etree.parse(plugin_xsd_path)
xmlschema = etree.XMLSchema(xmlschema_doc)
#Get the xml description file from the plugin directory. If there
#is no xml file, the plugin in unusable.
for plugin_dir in plugin_paths:
full_plugin_path = os.path.join(plugin_dir, 'trunk')
dir_contents = os.listdir(full_plugin_path)
#look for a plugin.xml file in the plugin directory
for file_name in dir_contents:
file_path = os.path.join(full_plugin_path, file_name)
if file_name == 'plugin.xml':
f = open(file_path, 'r')
#validate the xml using the xml schema for defining
#plugin details
try:
y = open(file_path, 'r')
xml_tree = etree.parse(y)
xmlschema.assertValid(xml_tree)
plugins.append(etree.tostring(xml_tree))
except Exception as e:
log.critical("Schema %s did not validate! (error was %s)"%(file_name, e))
break
else:
log.warning("No xml plugin details found for %s. Ignoring", plugin_dir)
return plugins | python | def get_plugins(**kwargs):
"""
Get all available plugins
"""
plugins = []
plugin_paths = []
#Look in directory or set of directories for
#plugins
base_plugin_dir = config.get('plugin', 'default_directory')
plugin_xsd_path = config.get('plugin', 'plugin_xsd_path')
base_plugin_dir_contents = os.listdir(base_plugin_dir)
for directory in base_plugin_dir_contents:
#ignore hidden files
if directory[0] == '.' or directory == 'xml':
continue
#Is this a file or a directory? If it's a directory, it's a plugin.
path = os.path.join(base_plugin_dir, directory)
if os.path.isdir(path):
plugin_paths.append(path)
#For each plugin, get its details (an XML string)
#Retrieve the xml schema for validating the XML to make sure
#what is being provided to the IU is correct.
xmlschema_doc = etree.parse(plugin_xsd_path)
xmlschema = etree.XMLSchema(xmlschema_doc)
#Get the xml description file from the plugin directory. If there
#is no xml file, the plugin in unusable.
for plugin_dir in plugin_paths:
full_plugin_path = os.path.join(plugin_dir, 'trunk')
dir_contents = os.listdir(full_plugin_path)
#look for a plugin.xml file in the plugin directory
for file_name in dir_contents:
file_path = os.path.join(full_plugin_path, file_name)
if file_name == 'plugin.xml':
f = open(file_path, 'r')
#validate the xml using the xml schema for defining
#plugin details
try:
y = open(file_path, 'r')
xml_tree = etree.parse(y)
xmlschema.assertValid(xml_tree)
plugins.append(etree.tostring(xml_tree))
except Exception as e:
log.critical("Schema %s did not validate! (error was %s)"%(file_name, e))
break
else:
log.warning("No xml plugin details found for %s. Ignoring", plugin_dir)
return plugins | [
"def",
"get_plugins",
"(",
"*",
"*",
"kwargs",
")",
":",
"plugins",
"=",
"[",
"]",
"plugin_paths",
"=",
"[",
"]",
"#Look in directory or set of directories for",
"#plugins",
"base_plugin_dir",
"=",
"config",
".",
"get",
"(",
"'plugin'",
",",
"'default_directory'",... | Get all available plugins | [
"Get",
"all",
"available",
"plugins"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/plugins.py#L31-L95 | train | 46,001 |
hydraplatform/hydra-base | hydra_base/lib/plugins.py | run_plugin | def run_plugin(plugin,**kwargs):
"""
Run a plugin
"""
args = [sys.executable]
#Get plugin executable
home = os.path.expanduser('~')
path_to_plugin = os.path.join(home, 'svn/HYDRA/HydraPlugins', plugin.location)
args.append(path_to_plugin)
#Parse plugin arguments into a string
plugin_params = " "
for p in plugin.params:
param = "--%s=%s "%(p.name, p.value)
args.append("--%s"%p.name)
args.append(p.value)
plugin_params = plugin_params + param
log_dir = config.get('plugin', 'result_file')
log_file = os.path.join(home, log_dir, plugin.name)
#this reads all the logs so far. We're not interested in them
#Everything after this is new content to the file
try:
f = open(log_file, 'r')
f.read()
except:
f = open(log_file, 'w')
f.close()
f = open(log_file, 'r')
pid = subprocess.Popen(args).pid
#run plugin
#os.system("%s %s"%(path_to_plugin, plugin_params))
log.info("Process started! PID: %s", pid)
return str(pid) | python | def run_plugin(plugin,**kwargs):
"""
Run a plugin
"""
args = [sys.executable]
#Get plugin executable
home = os.path.expanduser('~')
path_to_plugin = os.path.join(home, 'svn/HYDRA/HydraPlugins', plugin.location)
args.append(path_to_plugin)
#Parse plugin arguments into a string
plugin_params = " "
for p in plugin.params:
param = "--%s=%s "%(p.name, p.value)
args.append("--%s"%p.name)
args.append(p.value)
plugin_params = plugin_params + param
log_dir = config.get('plugin', 'result_file')
log_file = os.path.join(home, log_dir, plugin.name)
#this reads all the logs so far. We're not interested in them
#Everything after this is new content to the file
try:
f = open(log_file, 'r')
f.read()
except:
f = open(log_file, 'w')
f.close()
f = open(log_file, 'r')
pid = subprocess.Popen(args).pid
#run plugin
#os.system("%s %s"%(path_to_plugin, plugin_params))
log.info("Process started! PID: %s", pid)
return str(pid) | [
"def",
"run_plugin",
"(",
"plugin",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"sys",
".",
"executable",
"]",
"#Get plugin executable",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"path_to_plugin",
"=",
"os",
".",
"pat... | Run a plugin | [
"Run",
"a",
"plugin"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/plugins.py#L97-L136 | train | 46,002 |
hydraplatform/hydra-base | hydra_base/db/__init__.py | create_mysql_db | def create_mysql_db(db_url):
"""
To simplify deployment, create the mysql DB if it's not there.
Accepts a URL with or without a DB name stated, and returns a db url
containing the db name for use in the main sqlalchemy engine.
THe formats can take the following form:
mysql+driver://username:password@hostname
mysql+driver://username:password@hostname/dbname
if no DB name is specified, it is retrieved from config
"""
#Remove trailing whitespace and forwardslashes
db_url = db_url.strip().strip('/')
#Check this is a mysql URL
if db_url.find('mysql') >= 0:
#Get the DB name from config and check if it's in the URL
db_name = config.get('mysqld', 'db_name', 'hydradb')
if db_url.find(db_name) >= 0:
no_db_url = db_url.rsplit("/", 1)[0]
else:
#Check that there is a hostname specified, as we'll be using the '@' symbol soon..
if db_url.find('@') == -1:
raise HydraError("No Hostname specified in DB url")
#Check if there's a DB name specified that's different to the one in config.
host_and_db_name = db_url.split('@')[1]
if host_and_db_name.find('/') >= 0:
no_db_url, db_name = db_url.rsplit("/", 1)
else:
no_db_url = db_url
db_url = no_db_url + "/" + db_name
db_url = "{}?charset=utf8&use_unicode=1".format(db_url)
if config.get('mysqld', 'auto_create', 'Y') == 'Y':
tmp_engine = create_engine(no_db_url)
log.warning("Creating database {0} as it does not exist.".format(db_name))
tmp_engine.execute("CREATE DATABASE IF NOT EXISTS {0}".format(db_name))
return db_url | python | def create_mysql_db(db_url):
"""
To simplify deployment, create the mysql DB if it's not there.
Accepts a URL with or without a DB name stated, and returns a db url
containing the db name for use in the main sqlalchemy engine.
THe formats can take the following form:
mysql+driver://username:password@hostname
mysql+driver://username:password@hostname/dbname
if no DB name is specified, it is retrieved from config
"""
#Remove trailing whitespace and forwardslashes
db_url = db_url.strip().strip('/')
#Check this is a mysql URL
if db_url.find('mysql') >= 0:
#Get the DB name from config and check if it's in the URL
db_name = config.get('mysqld', 'db_name', 'hydradb')
if db_url.find(db_name) >= 0:
no_db_url = db_url.rsplit("/", 1)[0]
else:
#Check that there is a hostname specified, as we'll be using the '@' symbol soon..
if db_url.find('@') == -1:
raise HydraError("No Hostname specified in DB url")
#Check if there's a DB name specified that's different to the one in config.
host_and_db_name = db_url.split('@')[1]
if host_and_db_name.find('/') >= 0:
no_db_url, db_name = db_url.rsplit("/", 1)
else:
no_db_url = db_url
db_url = no_db_url + "/" + db_name
db_url = "{}?charset=utf8&use_unicode=1".format(db_url)
if config.get('mysqld', 'auto_create', 'Y') == 'Y':
tmp_engine = create_engine(no_db_url)
log.warning("Creating database {0} as it does not exist.".format(db_name))
tmp_engine.execute("CREATE DATABASE IF NOT EXISTS {0}".format(db_name))
return db_url | [
"def",
"create_mysql_db",
"(",
"db_url",
")",
":",
"#Remove trailing whitespace and forwardslashes",
"db_url",
"=",
"db_url",
".",
"strip",
"(",
")",
".",
"strip",
"(",
"'/'",
")",
"#Check this is a mysql URL",
"if",
"db_url",
".",
"find",
"(",
"'mysql'",
")",
"... | To simplify deployment, create the mysql DB if it's not there.
Accepts a URL with or without a DB name stated, and returns a db url
containing the db name for use in the main sqlalchemy engine.
THe formats can take the following form:
mysql+driver://username:password@hostname
mysql+driver://username:password@hostname/dbname
if no DB name is specified, it is retrieved from config | [
"To",
"simplify",
"deployment",
"create",
"the",
"mysql",
"DB",
"if",
"it",
"s",
"not",
"there",
".",
"Accepts",
"a",
"URL",
"with",
"or",
"without",
"a",
"DB",
"name",
"stated",
"and",
"returns",
"a",
"db",
"url",
"containing",
"the",
"db",
"name",
"f... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/__init__.py#L43-L89 | train | 46,003 |
hydraplatform/hydra-base | hydra_base/lib/project.py | add_project | def add_project(project,**kwargs):
"""
Add a new project
returns a project complexmodel
"""
user_id = kwargs.get('user_id')
existing_proj = get_project_by_name(project.name,user_id=user_id)
if len(existing_proj) > 0:
raise HydraError("A Project with the name \"%s\" already exists"%(project.name,))
#check_perm(user_id, 'add_project')
proj_i = Project()
proj_i.name = project.name
proj_i.description = project.description
proj_i.created_by = user_id
attr_map = hdb.add_resource_attributes(proj_i, project.attributes)
db.DBSession.flush() #Needed to get the resource attr's ID
proj_data = _add_project_attribute_data(proj_i, attr_map, project.attribute_data)
proj_i.attribute_data = proj_data
proj_i.set_owner(user_id)
db.DBSession.add(proj_i)
db.DBSession.flush()
return proj_i | python | def add_project(project,**kwargs):
"""
Add a new project
returns a project complexmodel
"""
user_id = kwargs.get('user_id')
existing_proj = get_project_by_name(project.name,user_id=user_id)
if len(existing_proj) > 0:
raise HydraError("A Project with the name \"%s\" already exists"%(project.name,))
#check_perm(user_id, 'add_project')
proj_i = Project()
proj_i.name = project.name
proj_i.description = project.description
proj_i.created_by = user_id
attr_map = hdb.add_resource_attributes(proj_i, project.attributes)
db.DBSession.flush() #Needed to get the resource attr's ID
proj_data = _add_project_attribute_data(proj_i, attr_map, project.attribute_data)
proj_i.attribute_data = proj_data
proj_i.set_owner(user_id)
db.DBSession.add(proj_i)
db.DBSession.flush()
return proj_i | [
"def",
"add_project",
"(",
"project",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"existing_proj",
"=",
"get_project_by_name",
"(",
"project",
".",
"name",
",",
"user_id",
"=",
"user_id",
")",
"if",
"le... | Add a new project
returns a project complexmodel | [
"Add",
"a",
"new",
"project",
"returns",
"a",
"project",
"complexmodel"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/project.py#L65-L93 | train | 46,004 |
hydraplatform/hydra-base | hydra_base/lib/project.py | update_project | def update_project(project,**kwargs):
"""
Update a project
returns a project complexmodel
"""
user_id = kwargs.get('user_id')
#check_perm(user_id, 'update_project')
proj_i = _get_project(project.id)
proj_i.check_write_permission(user_id)
proj_i.name = project.name
proj_i.description = project.description
attr_map = hdb.add_resource_attributes(proj_i, project.attributes)
proj_data = _add_project_attribute_data(proj_i, attr_map, project.attribute_data)
proj_i.attribute_data = proj_data
db.DBSession.flush()
return proj_i | python | def update_project(project,**kwargs):
"""
Update a project
returns a project complexmodel
"""
user_id = kwargs.get('user_id')
#check_perm(user_id, 'update_project')
proj_i = _get_project(project.id)
proj_i.check_write_permission(user_id)
proj_i.name = project.name
proj_i.description = project.description
attr_map = hdb.add_resource_attributes(proj_i, project.attributes)
proj_data = _add_project_attribute_data(proj_i, attr_map, project.attribute_data)
proj_i.attribute_data = proj_data
db.DBSession.flush()
return proj_i | [
"def",
"update_project",
"(",
"project",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"#check_perm(user_id, 'update_project')",
"proj_i",
"=",
"_get_project",
"(",
"project",
".",
"id",
")",
"proj_i",
".",
"... | Update a project
returns a project complexmodel | [
"Update",
"a",
"project",
"returns",
"a",
"project",
"complexmodel"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/project.py#L95-L115 | train | 46,005 |
hydraplatform/hydra-base | hydra_base/lib/project.py | get_project_by_network_id | def get_project_by_network_id(network_id,**kwargs):
"""
get a project complexmodel by a network_id
"""
user_id = kwargs.get('user_id')
projects_i = db.DBSession.query(Project).join(ProjectOwner).join(Network, Project.id==Network.project_id).filter(
Network.id==network_id,
ProjectOwner.user_id==user_id).order_by('name').all()
ret_project = None
for project_i in projects_i:
try:
project_i.check_read_permission(user_id)
ret_project = project_i
except:
log.info("Can't return project %s. User %s does not have permission to read it.", project_i.id, user_id)
return ret_project | python | def get_project_by_network_id(network_id,**kwargs):
"""
get a project complexmodel by a network_id
"""
user_id = kwargs.get('user_id')
projects_i = db.DBSession.query(Project).join(ProjectOwner).join(Network, Project.id==Network.project_id).filter(
Network.id==network_id,
ProjectOwner.user_id==user_id).order_by('name').all()
ret_project = None
for project_i in projects_i:
try:
project_i.check_read_permission(user_id)
ret_project = project_i
except:
log.info("Can't return project %s. User %s does not have permission to read it.", project_i.id, user_id)
return ret_project | [
"def",
"get_project_by_network_id",
"(",
"network_id",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"projects_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Project",
")",
".",
"join",
"(",
"Projec... | get a project complexmodel by a network_id | [
"get",
"a",
"project",
"complexmodel",
"by",
"a",
"network_id"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/project.py#L149-L166 | train | 46,006 |
hydraplatform/hydra-base | hydra_base/lib/project.py | get_projects | def get_projects(uid, include_shared_projects=True, projects_ids_list_filter=None, **kwargs):
"""
Get all the projects owned by the specified user.
These include projects created by the user, but also ones shared with the user.
For shared projects, only include networks in those projects which are accessible to the user.
the include_shared_projects flag indicates whether to include projects which have been shared
with the user, or to only return projects created directly by this user.
"""
req_user_id = kwargs.get('user_id')
##Don't load the project's networks. Load them separately, as the networks
#must be checked individually for ownership
projects_qry = db.DBSession.query(Project)
log.info("Getting projects for %s", uid)
if include_shared_projects is True:
projects_qry = projects_qry.join(ProjectOwner).filter(Project.status=='A',
or_(ProjectOwner.user_id==uid,
Project.created_by==uid))
else:
projects_qry = projects_qry.join(ProjectOwner).filter(Project.created_by==uid)
if projects_ids_list_filter is not None:
# Filtering the search of project id
if isinstance(projects_ids_list_filter, str):
# Trying to read a csv string
projects_ids_list_filter = eval(projects_ids_list_filter)
if type(projects_ids_list_filter) is int:
projects_qry = projects_qry.filter(Project.id==projects_ids_list_filter)
else:
projects_qry = projects_qry.filter(Project.id.in_(projects_ids_list_filter))
projects_qry = projects_qry.options(noload('networks')).order_by('id')
projects_i = projects_qry.all()
log.info("Project query done for user %s. %s projects found", uid, len(projects_i))
user = db.DBSession.query(User).filter(User.id==req_user_id).one()
isadmin = user.is_admin()
#Load each
projects_j = []
for project_i in projects_i:
#Ensure the requesting user is allowed to see the project
project_i.check_read_permission(req_user_id)
#lazy load owners
project_i.owners
network_qry = db.DBSession.query(Network)\
.filter(Network.project_id==project_i.id,\
Network.status=='A')
if not isadmin:
network_qry.outerjoin(NetworkOwner)\
.filter(or_(
and_(NetworkOwner.user_id != None,
NetworkOwner.view == 'Y'),
Network.created_by == uid
))
networks_i = network_qry.all()
networks_j = []
for network_i in networks_i:
network_i.owners
net_j = JSONObject(network_i)
if net_j.layout is not None:
net_j.layout = JSONObject(net_j.layout)
else:
net_j.layout = JSONObject({})
networks_j.append(net_j)
project_j = JSONObject(project_i)
project_j.networks = networks_j
projects_j.append(project_j)
log.info("Networks loaded projects for user %s", uid)
return projects_j | python | def get_projects(uid, include_shared_projects=True, projects_ids_list_filter=None, **kwargs):
"""
Get all the projects owned by the specified user.
These include projects created by the user, but also ones shared with the user.
For shared projects, only include networks in those projects which are accessible to the user.
the include_shared_projects flag indicates whether to include projects which have been shared
with the user, or to only return projects created directly by this user.
"""
req_user_id = kwargs.get('user_id')
##Don't load the project's networks. Load them separately, as the networks
#must be checked individually for ownership
projects_qry = db.DBSession.query(Project)
log.info("Getting projects for %s", uid)
if include_shared_projects is True:
projects_qry = projects_qry.join(ProjectOwner).filter(Project.status=='A',
or_(ProjectOwner.user_id==uid,
Project.created_by==uid))
else:
projects_qry = projects_qry.join(ProjectOwner).filter(Project.created_by==uid)
if projects_ids_list_filter is not None:
# Filtering the search of project id
if isinstance(projects_ids_list_filter, str):
# Trying to read a csv string
projects_ids_list_filter = eval(projects_ids_list_filter)
if type(projects_ids_list_filter) is int:
projects_qry = projects_qry.filter(Project.id==projects_ids_list_filter)
else:
projects_qry = projects_qry.filter(Project.id.in_(projects_ids_list_filter))
projects_qry = projects_qry.options(noload('networks')).order_by('id')
projects_i = projects_qry.all()
log.info("Project query done for user %s. %s projects found", uid, len(projects_i))
user = db.DBSession.query(User).filter(User.id==req_user_id).one()
isadmin = user.is_admin()
#Load each
projects_j = []
for project_i in projects_i:
#Ensure the requesting user is allowed to see the project
project_i.check_read_permission(req_user_id)
#lazy load owners
project_i.owners
network_qry = db.DBSession.query(Network)\
.filter(Network.project_id==project_i.id,\
Network.status=='A')
if not isadmin:
network_qry.outerjoin(NetworkOwner)\
.filter(or_(
and_(NetworkOwner.user_id != None,
NetworkOwner.view == 'Y'),
Network.created_by == uid
))
networks_i = network_qry.all()
networks_j = []
for network_i in networks_i:
network_i.owners
net_j = JSONObject(network_i)
if net_j.layout is not None:
net_j.layout = JSONObject(net_j.layout)
else:
net_j.layout = JSONObject({})
networks_j.append(net_j)
project_j = JSONObject(project_i)
project_j.networks = networks_j
projects_j.append(project_j)
log.info("Networks loaded projects for user %s", uid)
return projects_j | [
"def",
"get_projects",
"(",
"uid",
",",
"include_shared_projects",
"=",
"True",
",",
"projects_ids_list_filter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"req_user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"##Don't load the project's networks. ... | Get all the projects owned by the specified user.
These include projects created by the user, but also ones shared with the user.
For shared projects, only include networks in those projects which are accessible to the user.
the include_shared_projects flag indicates whether to include projects which have been shared
with the user, or to only return projects created directly by this user. | [
"Get",
"all",
"the",
"projects",
"owned",
"by",
"the",
"specified",
"user",
".",
"These",
"include",
"projects",
"created",
"by",
"the",
"user",
"but",
"also",
"ones",
"shared",
"with",
"the",
"user",
".",
"For",
"shared",
"projects",
"only",
"include",
"n... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/project.py#L255-L337 | train | 46,007 |
hydraplatform/hydra-base | hydra_base/lib/project.py | get_networks | def get_networks(project_id, include_data='N', **kwargs):
"""
Get all networks in a project
Returns an array of network objects.
"""
log.info("Getting networks for project %s", project_id)
user_id = kwargs.get('user_id')
project = _get_project(project_id)
project.check_read_permission(user_id)
rs = db.DBSession.query(Network.id, Network.status).filter(Network.project_id==project_id).all()
networks=[]
for r in rs:
if r.status != 'A':
continue
try:
net = network.get_network(r.id, summary=True, include_data=include_data, **kwargs)
log.info("Network %s retrieved", net.name)
networks.append(net)
except PermissionError:
log.info("Not returning network %s as user %s does not have "
"permission to read it."%(r.id, user_id))
return networks | python | def get_networks(project_id, include_data='N', **kwargs):
"""
Get all networks in a project
Returns an array of network objects.
"""
log.info("Getting networks for project %s", project_id)
user_id = kwargs.get('user_id')
project = _get_project(project_id)
project.check_read_permission(user_id)
rs = db.DBSession.query(Network.id, Network.status).filter(Network.project_id==project_id).all()
networks=[]
for r in rs:
if r.status != 'A':
continue
try:
net = network.get_network(r.id, summary=True, include_data=include_data, **kwargs)
log.info("Network %s retrieved", net.name)
networks.append(net)
except PermissionError:
log.info("Not returning network %s as user %s does not have "
"permission to read it."%(r.id, user_id))
return networks | [
"def",
"get_networks",
"(",
"project_id",
",",
"include_data",
"=",
"'N'",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"info",
"(",
"\"Getting networks for project %s\"",
",",
"project_id",
")",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",... | Get all networks in a project
Returns an array of network objects. | [
"Get",
"all",
"networks",
"in",
"a",
"project",
"Returns",
"an",
"array",
"of",
"network",
"objects",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/project.py#L364-L387 | train | 46,008 |
hydraplatform/hydra-base | hydra_base/lib/project.py | get_network_project | def get_network_project(network_id, **kwargs):
"""
get the project that a network is in
"""
net_proj = db.DBSession.query(Project).join(Network, and_(Project.id==Network.id, Network.id==network_id)).first()
if net_proj is None:
raise HydraError("Network %s not found"% network_id)
return net_proj | python | def get_network_project(network_id, **kwargs):
"""
get the project that a network is in
"""
net_proj = db.DBSession.query(Project).join(Network, and_(Project.id==Network.id, Network.id==network_id)).first()
if net_proj is None:
raise HydraError("Network %s not found"% network_id)
return net_proj | [
"def",
"get_network_project",
"(",
"network_id",
",",
"*",
"*",
"kwargs",
")",
":",
"net_proj",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Project",
")",
".",
"join",
"(",
"Network",
",",
"and_",
"(",
"Project",
".",
"id",
"==",
"Network",
".",
... | get the project that a network is in | [
"get",
"the",
"project",
"that",
"a",
"network",
"is",
"in"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/project.py#L389-L399 | train | 46,009 |
hydraplatform/hydra-base | hydra_base/util/hdb.py | add_resource_types | def add_resource_types(resource_i, types):
"""
Save a reference to the types used for this resource.
@returns a list of type_ids representing the type ids
on the resource.
"""
if types is None:
return []
existing_type_ids = []
if resource_i.types:
for t in resource_i.types:
existing_type_ids.append(t.type_id)
new_type_ids = []
for templatetype in types:
if templatetype.id in existing_type_ids:
continue
rt_i = ResourceType()
rt_i.type_id = templatetype.id
rt_i.ref_key = resource_i.ref_key
if resource_i.ref_key == 'NODE':
rt_i.node_id = resource_i.id
elif resource_i.ref_key == 'LINK':
rt_i.link_id = resource_i.id
elif resource_i.ref_key == 'GROUP':
rt_i.group_id = resource_i.id
resource_i.types.append(rt_i)
new_type_ids.append(templatetype.id)
return new_type_ids | python | def add_resource_types(resource_i, types):
"""
Save a reference to the types used for this resource.
@returns a list of type_ids representing the type ids
on the resource.
"""
if types is None:
return []
existing_type_ids = []
if resource_i.types:
for t in resource_i.types:
existing_type_ids.append(t.type_id)
new_type_ids = []
for templatetype in types:
if templatetype.id in existing_type_ids:
continue
rt_i = ResourceType()
rt_i.type_id = templatetype.id
rt_i.ref_key = resource_i.ref_key
if resource_i.ref_key == 'NODE':
rt_i.node_id = resource_i.id
elif resource_i.ref_key == 'LINK':
rt_i.link_id = resource_i.id
elif resource_i.ref_key == 'GROUP':
rt_i.group_id = resource_i.id
resource_i.types.append(rt_i)
new_type_ids.append(templatetype.id)
return new_type_ids | [
"def",
"add_resource_types",
"(",
"resource_i",
",",
"types",
")",
":",
"if",
"types",
"is",
"None",
":",
"return",
"[",
"]",
"existing_type_ids",
"=",
"[",
"]",
"if",
"resource_i",
".",
"types",
":",
"for",
"t",
"in",
"resource_i",
".",
"types",
":",
... | Save a reference to the types used for this resource.
@returns a list of type_ids representing the type ids
on the resource. | [
"Save",
"a",
"reference",
"to",
"the",
"types",
"used",
"for",
"this",
"resource",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/hdb.py#L37-L71 | train | 46,010 |
hydraplatform/hydra-base | hydra_base/util/hdb.py | create_default_units_and_dimensions | def create_default_units_and_dimensions():
"""
Adds the units and the dimensions reading a json file. It adds only dimensions and units that are not inside the db
It is possible adding new dimensions and units to the DB just modifiyin the json file
"""
default_units_file_location = os.path.realpath(\
os.path.join(os.path.dirname(os.path.realpath(__file__)),
'../',
'static',
'default_units_and_dimensions.json'))
d=None
with open(default_units_file_location) as json_data:
d = json.load(json_data)
json_data.close()
for json_dimension in d["dimension"]:
new_dimension = None
dimension_name = get_utf8_encoded_string(json_dimension["name"])
db_dimensions_by_name = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).all()
if len(db_dimensions_by_name) == 0:
# Adding the dimension
log.debug("Adding Dimension `{}`".format(dimension_name))
new_dimension = Dimension()
if "id" in json_dimension:
# If ID is specified
new_dimension.id = json_dimension["id"]
new_dimension.name = dimension_name
db.DBSession.add(new_dimension)
db.DBSession.flush()
# Get the dimension by name
new_dimension = get_dimension_from_db_by_name(dimension_name)
for json_unit in json_dimension["unit"]:
db_units_by_name = db.DBSession.query(Unit).filter(Unit.abbreviation==get_utf8_encoded_string(json_unit['abbr'])).all()
if len(db_units_by_name) == 0:
# Adding the unit
log.debug("Adding Unit %s in %s",json_unit['abbr'], json_dimension["name"])
new_unit = Unit()
if "id" in json_unit:
new_unit.id = json_unit["id"]
new_unit.dimension_id = new_dimension.id
new_unit.name = get_utf8_encoded_string(json_unit['name'])
new_unit.abbreviation = get_utf8_encoded_string(json_unit['abbr'])
new_unit.lf = get_utf8_encoded_string(json_unit['lf'])
new_unit.cf = get_utf8_encoded_string(json_unit['cf'])
if "description" in json_unit:
# If Description is specified
new_unit.description = get_utf8_encoded_string(json_unit["description"])
# Save on DB
db.DBSession.add(new_unit)
db.DBSession.flush()
else:
#log.critical("UNIT {}.{} EXISTANT".format(dimension_name,json_unit['abbr']))
pass
try:
# Needed for test. on HWI it fails so we need to catch the exception and pass by
db.DBSession.commit()
except Exception as e:
# Needed for HWI
pass
return | python | def create_default_units_and_dimensions():
"""
Adds the units and the dimensions reading a json file. It adds only dimensions and units that are not inside the db
It is possible adding new dimensions and units to the DB just modifiyin the json file
"""
default_units_file_location = os.path.realpath(\
os.path.join(os.path.dirname(os.path.realpath(__file__)),
'../',
'static',
'default_units_and_dimensions.json'))
d=None
with open(default_units_file_location) as json_data:
d = json.load(json_data)
json_data.close()
for json_dimension in d["dimension"]:
new_dimension = None
dimension_name = get_utf8_encoded_string(json_dimension["name"])
db_dimensions_by_name = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).all()
if len(db_dimensions_by_name) == 0:
# Adding the dimension
log.debug("Adding Dimension `{}`".format(dimension_name))
new_dimension = Dimension()
if "id" in json_dimension:
# If ID is specified
new_dimension.id = json_dimension["id"]
new_dimension.name = dimension_name
db.DBSession.add(new_dimension)
db.DBSession.flush()
# Get the dimension by name
new_dimension = get_dimension_from_db_by_name(dimension_name)
for json_unit in json_dimension["unit"]:
db_units_by_name = db.DBSession.query(Unit).filter(Unit.abbreviation==get_utf8_encoded_string(json_unit['abbr'])).all()
if len(db_units_by_name) == 0:
# Adding the unit
log.debug("Adding Unit %s in %s",json_unit['abbr'], json_dimension["name"])
new_unit = Unit()
if "id" in json_unit:
new_unit.id = json_unit["id"]
new_unit.dimension_id = new_dimension.id
new_unit.name = get_utf8_encoded_string(json_unit['name'])
new_unit.abbreviation = get_utf8_encoded_string(json_unit['abbr'])
new_unit.lf = get_utf8_encoded_string(json_unit['lf'])
new_unit.cf = get_utf8_encoded_string(json_unit['cf'])
if "description" in json_unit:
# If Description is specified
new_unit.description = get_utf8_encoded_string(json_unit["description"])
# Save on DB
db.DBSession.add(new_unit)
db.DBSession.flush()
else:
#log.critical("UNIT {}.{} EXISTANT".format(dimension_name,json_unit['abbr']))
pass
try:
# Needed for test. on HWI it fails so we need to catch the exception and pass by
db.DBSession.commit()
except Exception as e:
# Needed for HWI
pass
return | [
"def",
"create_default_units_and_dimensions",
"(",
")",
":",
"default_units_file_location",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
... | Adds the units and the dimensions reading a json file. It adds only dimensions and units that are not inside the db
It is possible adding new dimensions and units to the DB just modifiyin the json file | [
"Adds",
"the",
"units",
"and",
"the",
"dimensions",
"reading",
"a",
"json",
"file",
".",
"It",
"adds",
"only",
"dimensions",
"and",
"units",
"that",
"are",
"not",
"inside",
"the",
"db",
"It",
"is",
"possible",
"adding",
"new",
"dimensions",
"and",
"units",... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/hdb.py#L348-L416 | train | 46,011 |
hydraplatform/hydra-base | hydra_base/util/hdb.py | get_dimension_from_db_by_name | def get_dimension_from_db_by_name(dimension_name):
"""
Gets a dimension from the DB table.
"""
try:
dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one()
return JSONObject(dimension)
except NoResultFound:
raise ResourceNotFoundError("Dimension %s not found"%(dimension_name)) | python | def get_dimension_from_db_by_name(dimension_name):
"""
Gets a dimension from the DB table.
"""
try:
dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one()
return JSONObject(dimension)
except NoResultFound:
raise ResourceNotFoundError("Dimension %s not found"%(dimension_name)) | [
"def",
"get_dimension_from_db_by_name",
"(",
"dimension_name",
")",
":",
"try",
":",
"dimension",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dimension",
")",
".",
"filter",
"(",
"Dimension",
".",
"name",
"==",
"dimension_name",
")",
".",
"one",
"(",
... | Gets a dimension from the DB table. | [
"Gets",
"a",
"dimension",
"from",
"the",
"DB",
"table",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/hdb.py#L425-L433 | train | 46,012 |
hydraplatform/hydra-base | hydra_base/lib/rules.py | get_rules | def get_rules(scenario_id, **kwargs):
"""
Get all the rules for a given scenario.
"""
rules = db.DBSession.query(Rule).filter(Rule.scenario_id==scenario_id, Rule.status=='A').all()
return rules | python | def get_rules(scenario_id, **kwargs):
"""
Get all the rules for a given scenario.
"""
rules = db.DBSession.query(Rule).filter(Rule.scenario_id==scenario_id, Rule.status=='A').all()
return rules | [
"def",
"get_rules",
"(",
"scenario_id",
",",
"*",
"*",
"kwargs",
")",
":",
"rules",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Rule",
")",
".",
"filter",
"(",
"Rule",
".",
"scenario_id",
"==",
"scenario_id",
",",
"Rule",
".",
"status",
"==",
"'... | Get all the rules for a given scenario. | [
"Get",
"all",
"the",
"rules",
"for",
"a",
"given",
"scenario",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/rules.py#L32-L38 | train | 46,013 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_attribute_by_name_and_dimension | def get_attribute_by_name_and_dimension(name, dimension_id=None,**kwargs):
"""
Get a specific attribute by its name.
dimension_id can be None, because in attribute the dimension_id is not anymore mandatory
"""
try:
attr_i = db.DBSession.query(Attr).filter(and_(Attr.name==name, Attr.dimension_id==dimension_id)).one()
log.debug("Attribute retrieved")
return attr_i
except NoResultFound:
return None | python | def get_attribute_by_name_and_dimension(name, dimension_id=None,**kwargs):
"""
Get a specific attribute by its name.
dimension_id can be None, because in attribute the dimension_id is not anymore mandatory
"""
try:
attr_i = db.DBSession.query(Attr).filter(and_(Attr.name==name, Attr.dimension_id==dimension_id)).one()
log.debug("Attribute retrieved")
return attr_i
except NoResultFound:
return None | [
"def",
"get_attribute_by_name_and_dimension",
"(",
"name",
",",
"dimension_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"attr_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Attr",
")",
".",
"filter",
"(",
"and_",
"(",
"Attr",
... | Get a specific attribute by its name.
dimension_id can be None, because in attribute the dimension_id is not anymore mandatory | [
"Get",
"a",
"specific",
"attribute",
"by",
"its",
"name",
".",
"dimension_id",
"can",
"be",
"None",
"because",
"in",
"attribute",
"the",
"dimension_id",
"is",
"not",
"anymore",
"mandatory"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L108-L118 | train | 46,014 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | add_attributes | def add_attributes(attrs,**kwargs):
"""
Add a list of generic attributes, which can then be used in creating
a resource attribute, and put into a type.
.. code-block:: python
(Attr){
id = 1020
name = "Test Attr"
dimen = "very big"
}
"""
#Check to see if any of the attributs being added are already there.
#If they are there already, don't add a new one. If an attribute
#with the same name is there already but with a different dimension,
#add a new attribute.
# All existing attributes
all_attrs = db.DBSession.query(Attr).all()
attr_dict = {}
for attr in all_attrs:
attr_dict[(attr.name.lower(), attr.dimension_id)] = JSONObject(attr)
attrs_to_add = []
existing_attrs = []
for potential_new_attr in attrs:
if potential_new_attr is not None:
# If the attrinute is None we cannot manage it
log.debug("Adding attribute: %s", potential_new_attr)
if attr_dict.get((potential_new_attr.name.lower(), potential_new_attr.dimension_id)) is None:
attrs_to_add.append(JSONObject(potential_new_attr))
else:
existing_attrs.append(attr_dict.get((potential_new_attr.name.lower(), potential_new_attr.dimension_id)))
new_attrs = []
for attr in attrs_to_add:
attr_i = Attr()
attr_i.name = attr.name
attr_i.dimension_id = attr.dimension_id
attr_i.description = attr.description
db.DBSession.add(attr_i)
new_attrs.append(attr_i)
db.DBSession.flush()
new_attrs = new_attrs + existing_attrs
return [JSONObject(a) for a in new_attrs] | python | def add_attributes(attrs,**kwargs):
"""
Add a list of generic attributes, which can then be used in creating
a resource attribute, and put into a type.
.. code-block:: python
(Attr){
id = 1020
name = "Test Attr"
dimen = "very big"
}
"""
#Check to see if any of the attributs being added are already there.
#If they are there already, don't add a new one. If an attribute
#with the same name is there already but with a different dimension,
#add a new attribute.
# All existing attributes
all_attrs = db.DBSession.query(Attr).all()
attr_dict = {}
for attr in all_attrs:
attr_dict[(attr.name.lower(), attr.dimension_id)] = JSONObject(attr)
attrs_to_add = []
existing_attrs = []
for potential_new_attr in attrs:
if potential_new_attr is not None:
# If the attrinute is None we cannot manage it
log.debug("Adding attribute: %s", potential_new_attr)
if attr_dict.get((potential_new_attr.name.lower(), potential_new_attr.dimension_id)) is None:
attrs_to_add.append(JSONObject(potential_new_attr))
else:
existing_attrs.append(attr_dict.get((potential_new_attr.name.lower(), potential_new_attr.dimension_id)))
new_attrs = []
for attr in attrs_to_add:
attr_i = Attr()
attr_i.name = attr.name
attr_i.dimension_id = attr.dimension_id
attr_i.description = attr.description
db.DBSession.add(attr_i)
new_attrs.append(attr_i)
db.DBSession.flush()
new_attrs = new_attrs + existing_attrs
return [JSONObject(a) for a in new_attrs] | [
"def",
"add_attributes",
"(",
"attrs",
",",
"*",
"*",
"kwargs",
")",
":",
"#Check to see if any of the attributs being added are already there.",
"#If they are there already, don't add a new one. If an attribute",
"#with the same name is there already but with a different dimension,",
"#ad... | Add a list of generic attributes, which can then be used in creating
a resource attribute, and put into a type.
.. code-block:: python
(Attr){
id = 1020
name = "Test Attr"
dimen = "very big"
} | [
"Add",
"a",
"list",
"of",
"generic",
"attributes",
"which",
"can",
"then",
"be",
"used",
"in",
"creating",
"a",
"resource",
"attribute",
"and",
"put",
"into",
"a",
"type",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L186-L238 | train | 46,015 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_attributes | def get_attributes(**kwargs):
"""
Get all attributes
"""
attrs = db.DBSession.query(Attr).order_by(Attr.name).all()
return attrs | python | def get_attributes(**kwargs):
"""
Get all attributes
"""
attrs = db.DBSession.query(Attr).order_by(Attr.name).all()
return attrs | [
"def",
"get_attributes",
"(",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Attr",
")",
".",
"order_by",
"(",
"Attr",
".",
"name",
")",
".",
"all",
"(",
")",
"return",
"attrs"
] | Get all attributes | [
"Get",
"all",
"attributes"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L240-L247 | train | 46,016 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | add_resource_attribute | def add_resource_attribute(resource_type, resource_id, attr_id, is_var, error_on_duplicate=True, **kwargs):
"""
Add a resource attribute attribute to a resource.
attr_is_var indicates whether the attribute is a variable or not --
this is used in simulation to indicate that this value is expected
to be filled in by the simulator.
"""
attr = db.DBSession.query(Attr).filter(Attr.id==attr_id).first()
if attr is None:
raise ResourceNotFoundError("Attribute with ID %s does not exist."%attr_id)
resource_i = _get_resource(resource_type, resource_id)
resourceattr_qry = db.DBSession.query(ResourceAttr).filter(ResourceAttr.ref_key==resource_type)
if resource_type == 'NETWORK':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.network_id==resource_id)
elif resource_type == 'NODE':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.node_id==resource_id)
elif resource_type == 'LINK':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.link_id==resource_id)
elif resource_type == 'GROUP':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.group_id==resource_id)
elif resource_type == 'PROJECT':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.project_id==resource_id)
else:
raise HydraError('Resource type "{}" not recognised.'.format(resource_type))
resource_attrs = resourceattr_qry.all()
for ra in resource_attrs:
if ra.attr_id == attr_id:
if not error_on_duplicate:
return ra
raise HydraError("Duplicate attribute. %s %s already has attribute %s"
%(resource_type, resource_i.get_name(), attr.name))
attr_is_var = 'Y' if is_var == 'Y' else 'N'
new_ra = resource_i.add_attribute(attr_id, attr_is_var)
db.DBSession.flush()
return new_ra | python | def add_resource_attribute(resource_type, resource_id, attr_id, is_var, error_on_duplicate=True, **kwargs):
"""
Add a resource attribute attribute to a resource.
attr_is_var indicates whether the attribute is a variable or not --
this is used in simulation to indicate that this value is expected
to be filled in by the simulator.
"""
attr = db.DBSession.query(Attr).filter(Attr.id==attr_id).first()
if attr is None:
raise ResourceNotFoundError("Attribute with ID %s does not exist."%attr_id)
resource_i = _get_resource(resource_type, resource_id)
resourceattr_qry = db.DBSession.query(ResourceAttr).filter(ResourceAttr.ref_key==resource_type)
if resource_type == 'NETWORK':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.network_id==resource_id)
elif resource_type == 'NODE':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.node_id==resource_id)
elif resource_type == 'LINK':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.link_id==resource_id)
elif resource_type == 'GROUP':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.group_id==resource_id)
elif resource_type == 'PROJECT':
resourceattr_qry = resourceattr_qry.filter(ResourceAttr.project_id==resource_id)
else:
raise HydraError('Resource type "{}" not recognised.'.format(resource_type))
resource_attrs = resourceattr_qry.all()
for ra in resource_attrs:
if ra.attr_id == attr_id:
if not error_on_duplicate:
return ra
raise HydraError("Duplicate attribute. %s %s already has attribute %s"
%(resource_type, resource_i.get_name(), attr.name))
attr_is_var = 'Y' if is_var == 'Y' else 'N'
new_ra = resource_i.add_attribute(attr_id, attr_is_var)
db.DBSession.flush()
return new_ra | [
"def",
"add_resource_attribute",
"(",
"resource_type",
",",
"resource_id",
",",
"attr_id",
",",
"is_var",
",",
"error_on_duplicate",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"attr",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Attr",
")",
".",
... | Add a resource attribute attribute to a resource.
attr_is_var indicates whether the attribute is a variable or not --
this is used in simulation to indicate that this value is expected
to be filled in by the simulator. | [
"Add",
"a",
"resource",
"attribute",
"attribute",
"to",
"a",
"resource",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L295-L340 | train | 46,017 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | add_resource_attrs_from_type | def add_resource_attrs_from_type(type_id, resource_type, resource_id,**kwargs):
"""
adds all the attributes defined by a type to a node.
"""
type_i = _get_templatetype(type_id)
resource_i = _get_resource(resource_type, resource_id)
resourceattr_qry = db.DBSession.query(ResourceAttr).filter(ResourceAttr.ref_key==resource_type)
if resource_type == 'NETWORK':
resourceattr_qry.filter(ResourceAttr.network_id==resource_id)
elif resource_type == 'NODE':
resourceattr_qry.filter(ResourceAttr.node_id==resource_id)
elif resource_type == 'LINK':
resourceattr_qry.filter(ResourceAttr.link_id==resource_id)
elif resource_type == 'GROUP':
resourceattr_qry.filter(ResourceAttr.group_id==resource_id)
elif resource_type == 'PROJECT':
resourceattr_qry.filter(ResourceAttr.project_id==resource_id)
resource_attrs = resourceattr_qry.all()
attrs = {}
for res_attr in resource_attrs:
attrs[res_attr.attr_id] = res_attr
new_resource_attrs = []
for item in type_i.typeattrs:
if attrs.get(item.attr_id) is None:
ra = resource_i.add_attribute(item.attr_id)
new_resource_attrs.append(ra)
db.DBSession.flush()
return new_resource_attrs | python | def add_resource_attrs_from_type(type_id, resource_type, resource_id,**kwargs):
"""
adds all the attributes defined by a type to a node.
"""
type_i = _get_templatetype(type_id)
resource_i = _get_resource(resource_type, resource_id)
resourceattr_qry = db.DBSession.query(ResourceAttr).filter(ResourceAttr.ref_key==resource_type)
if resource_type == 'NETWORK':
resourceattr_qry.filter(ResourceAttr.network_id==resource_id)
elif resource_type == 'NODE':
resourceattr_qry.filter(ResourceAttr.node_id==resource_id)
elif resource_type == 'LINK':
resourceattr_qry.filter(ResourceAttr.link_id==resource_id)
elif resource_type == 'GROUP':
resourceattr_qry.filter(ResourceAttr.group_id==resource_id)
elif resource_type == 'PROJECT':
resourceattr_qry.filter(ResourceAttr.project_id==resource_id)
resource_attrs = resourceattr_qry.all()
attrs = {}
for res_attr in resource_attrs:
attrs[res_attr.attr_id] = res_attr
new_resource_attrs = []
for item in type_i.typeattrs:
if attrs.get(item.attr_id) is None:
ra = resource_i.add_attribute(item.attr_id)
new_resource_attrs.append(ra)
db.DBSession.flush()
return new_resource_attrs | [
"def",
"add_resource_attrs_from_type",
"(",
"type_id",
",",
"resource_type",
",",
"resource_id",
",",
"*",
"*",
"kwargs",
")",
":",
"type_i",
"=",
"_get_templatetype",
"(",
"type_id",
")",
"resource_i",
"=",
"_get_resource",
"(",
"resource_type",
",",
"resource_id... | adds all the attributes defined by a type to a node. | [
"adds",
"all",
"the",
"attributes",
"defined",
"by",
"a",
"type",
"to",
"a",
"node",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L342-L377 | train | 46,018 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_all_resource_attributes | def get_all_resource_attributes(ref_key, network_id, template_id=None, **kwargs):
"""
Get all the resource attributes for a given resource type in the network.
That includes all the resource attributes for a given type within the network.
For example, if the ref_key is 'NODE', then it will return all the attirbutes
of all nodes in the network. This function allows a front end to pre-load an entire
network's resource attribute information to reduce on function calls.
If type_id is specified, only
return the resource attributes within the type.
"""
user_id = kwargs.get('user_id')
resource_attr_qry = db.DBSession.query(ResourceAttr).\
outerjoin(Node, Node.id==ResourceAttr.node_id).\
outerjoin(Link, Link.id==ResourceAttr.link_id).\
outerjoin(ResourceGroup, ResourceGroup.id==ResourceAttr.group_id).filter(
ResourceAttr.ref_key == ref_key,
or_(
and_(ResourceAttr.node_id != None,
ResourceAttr.node_id == Node.id,
Node.network_id==network_id),
and_(ResourceAttr.link_id != None,
ResourceAttr.link_id == Link.id,
Link.network_id==network_id),
and_(ResourceAttr.group_id != None,
ResourceAttr.group_id == ResourceGroup.id,
ResourceGroup.network_id==network_id)
))
if template_id is not None:
attr_ids = []
rs = db.DBSession.query(TypeAttr).join(TemplateType,
TemplateType.id==TypeAttr.type_id).filter(
TemplateType.template_id==template_id).all()
for r in rs:
attr_ids.append(r.attr_id)
resource_attr_qry = resource_attr_qry.filter(ResourceAttr.attr_id.in_(attr_ids))
resource_attrs = resource_attr_qry.all()
return resource_attrs | python | def get_all_resource_attributes(ref_key, network_id, template_id=None, **kwargs):
"""
Get all the resource attributes for a given resource type in the network.
That includes all the resource attributes for a given type within the network.
For example, if the ref_key is 'NODE', then it will return all the attirbutes
of all nodes in the network. This function allows a front end to pre-load an entire
network's resource attribute information to reduce on function calls.
If type_id is specified, only
return the resource attributes within the type.
"""
user_id = kwargs.get('user_id')
resource_attr_qry = db.DBSession.query(ResourceAttr).\
outerjoin(Node, Node.id==ResourceAttr.node_id).\
outerjoin(Link, Link.id==ResourceAttr.link_id).\
outerjoin(ResourceGroup, ResourceGroup.id==ResourceAttr.group_id).filter(
ResourceAttr.ref_key == ref_key,
or_(
and_(ResourceAttr.node_id != None,
ResourceAttr.node_id == Node.id,
Node.network_id==network_id),
and_(ResourceAttr.link_id != None,
ResourceAttr.link_id == Link.id,
Link.network_id==network_id),
and_(ResourceAttr.group_id != None,
ResourceAttr.group_id == ResourceGroup.id,
ResourceGroup.network_id==network_id)
))
if template_id is not None:
attr_ids = []
rs = db.DBSession.query(TypeAttr).join(TemplateType,
TemplateType.id==TypeAttr.type_id).filter(
TemplateType.template_id==template_id).all()
for r in rs:
attr_ids.append(r.attr_id)
resource_attr_qry = resource_attr_qry.filter(ResourceAttr.attr_id.in_(attr_ids))
resource_attrs = resource_attr_qry.all()
return resource_attrs | [
"def",
"get_all_resource_attributes",
"(",
"ref_key",
",",
"network_id",
",",
"template_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"resource_attr_qry",
"=",
"db",
".",
"DBSession",
".",
... | Get all the resource attributes for a given resource type in the network.
That includes all the resource attributes for a given type within the network.
For example, if the ref_key is 'NODE', then it will return all the attirbutes
of all nodes in the network. This function allows a front end to pre-load an entire
network's resource attribute information to reduce on function calls.
If type_id is specified, only
return the resource attributes within the type. | [
"Get",
"all",
"the",
"resource",
"attributes",
"for",
"a",
"given",
"resource",
"type",
"in",
"the",
"network",
".",
"That",
"includes",
"all",
"the",
"resource",
"attributes",
"for",
"a",
"given",
"type",
"within",
"the",
"network",
".",
"For",
"example",
... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L379-L423 | train | 46,019 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_resource_attributes | def get_resource_attributes(ref_key, ref_id, type_id=None, **kwargs):
"""
Get all the resource attributes for a given resource.
If type_id is specified, only
return the resource attributes within the type.
"""
user_id = kwargs.get('user_id')
resource_attr_qry = db.DBSession.query(ResourceAttr).filter(
ResourceAttr.ref_key == ref_key,
or_(
ResourceAttr.network_id==ref_id,
ResourceAttr.node_id==ref_id,
ResourceAttr.link_id==ref_id,
ResourceAttr.group_id==ref_id
))
if type_id is not None:
attr_ids = []
rs = db.DBSession.query(TypeAttr).filter(TypeAttr.type_id==type_id).all()
for r in rs:
attr_ids.append(r.attr_id)
resource_attr_qry = resource_attr_qry.filter(ResourceAttr.attr_id.in_(attr_ids))
resource_attrs = resource_attr_qry.all()
return resource_attrs | python | def get_resource_attributes(ref_key, ref_id, type_id=None, **kwargs):
"""
Get all the resource attributes for a given resource.
If type_id is specified, only
return the resource attributes within the type.
"""
user_id = kwargs.get('user_id')
resource_attr_qry = db.DBSession.query(ResourceAttr).filter(
ResourceAttr.ref_key == ref_key,
or_(
ResourceAttr.network_id==ref_id,
ResourceAttr.node_id==ref_id,
ResourceAttr.link_id==ref_id,
ResourceAttr.group_id==ref_id
))
if type_id is not None:
attr_ids = []
rs = db.DBSession.query(TypeAttr).filter(TypeAttr.type_id==type_id).all()
for r in rs:
attr_ids.append(r.attr_id)
resource_attr_qry = resource_attr_qry.filter(ResourceAttr.attr_id.in_(attr_ids))
resource_attrs = resource_attr_qry.all()
return resource_attrs | [
"def",
"get_resource_attributes",
"(",
"ref_key",
",",
"ref_id",
",",
"type_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"resource_attr_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
... | Get all the resource attributes for a given resource.
If type_id is specified, only
return the resource attributes within the type. | [
"Get",
"all",
"the",
"resource",
"attributes",
"for",
"a",
"given",
"resource",
".",
"If",
"type_id",
"is",
"specified",
"only",
"return",
"the",
"resource",
"attributes",
"within",
"the",
"type",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L425-L453 | train | 46,020 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | check_attr_dimension | def check_attr_dimension(attr_id, **kwargs):
"""
Check that the dimension of the resource attribute data is consistent
with the definition of the attribute.
If the attribute says 'volume', make sure every dataset connected
with this attribute via a resource attribute also has a dimension
of 'volume'.
"""
attr_i = _get_attr(attr_id)
datasets = db.DBSession.query(Dataset).filter(Dataset.id == ResourceScenario.dataset_id,
ResourceScenario.resource_attr_id == ResourceAttr.id,
ResourceAttr.attr_id == attr_id).all()
bad_datasets = []
for d in datasets:
if attr_i.dimension_id is None and d.unit is not None or \
attr_i.dimension_id is not None and d.unit is None or \
units.get_dimension_by_unit_id(d.unit_id) != attr_i.dimension_id:
# If there is an inconsistency
bad_datasets.append(d.id)
if len(bad_datasets) > 0:
raise HydraError("Datasets %s have a different dimension_id to attribute %s"%(bad_datasets, attr_id))
return 'OK' | python | def check_attr_dimension(attr_id, **kwargs):
"""
Check that the dimension of the resource attribute data is consistent
with the definition of the attribute.
If the attribute says 'volume', make sure every dataset connected
with this attribute via a resource attribute also has a dimension
of 'volume'.
"""
attr_i = _get_attr(attr_id)
datasets = db.DBSession.query(Dataset).filter(Dataset.id == ResourceScenario.dataset_id,
ResourceScenario.resource_attr_id == ResourceAttr.id,
ResourceAttr.attr_id == attr_id).all()
bad_datasets = []
for d in datasets:
if attr_i.dimension_id is None and d.unit is not None or \
attr_i.dimension_id is not None and d.unit is None or \
units.get_dimension_by_unit_id(d.unit_id) != attr_i.dimension_id:
# If there is an inconsistency
bad_datasets.append(d.id)
if len(bad_datasets) > 0:
raise HydraError("Datasets %s have a different dimension_id to attribute %s"%(bad_datasets, attr_id))
return 'OK' | [
"def",
"check_attr_dimension",
"(",
"attr_id",
",",
"*",
"*",
"kwargs",
")",
":",
"attr_i",
"=",
"_get_attr",
"(",
"attr_id",
")",
"datasets",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dataset",
")",
".",
"filter",
"(",
"Dataset",
".",
"id",
"==... | Check that the dimension of the resource attribute data is consistent
with the definition of the attribute.
If the attribute says 'volume', make sure every dataset connected
with this attribute via a resource attribute also has a dimension
of 'volume'. | [
"Check",
"that",
"the",
"dimension",
"of",
"the",
"resource",
"attribute",
"data",
"is",
"consistent",
"with",
"the",
"definition",
"of",
"the",
"attribute",
".",
"If",
"the",
"attribute",
"says",
"volume",
"make",
"sure",
"every",
"dataset",
"connected",
"wit... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L455-L479 | train | 46,021 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_resource_attribute | def get_resource_attribute(resource_attr_id, **kwargs):
"""
Get a specific resource attribte, by ID
If type_id is Gspecified, only
return the resource attributes within the type.
"""
resource_attr_qry = db.DBSession.query(ResourceAttr).filter(
ResourceAttr.id == resource_attr_id,
)
resource_attr = resource_attr_qry.first()
if resource_attr is None:
raise ResourceNotFoundError("Resource attribute %s does not exist", resource_attr_id)
return resource_attr | python | def get_resource_attribute(resource_attr_id, **kwargs):
"""
Get a specific resource attribte, by ID
If type_id is Gspecified, only
return the resource attributes within the type.
"""
resource_attr_qry = db.DBSession.query(ResourceAttr).filter(
ResourceAttr.id == resource_attr_id,
)
resource_attr = resource_attr_qry.first()
if resource_attr is None:
raise ResourceNotFoundError("Resource attribute %s does not exist", resource_attr_id)
return resource_attr | [
"def",
"get_resource_attribute",
"(",
"resource_attr_id",
",",
"*",
"*",
"kwargs",
")",
":",
"resource_attr_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceAttr",
")",
".",
"filter",
"(",
"ResourceAttr",
".",
"id",
"==",
"resource_attr_id",
",",... | Get a specific resource attribte, by ID
If type_id is Gspecified, only
return the resource attributes within the type. | [
"Get",
"a",
"specific",
"resource",
"attribte",
"by",
"ID",
"If",
"type_id",
"is",
"Gspecified",
"only",
"return",
"the",
"resource",
"attributes",
"within",
"the",
"type",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L481-L497 | train | 46,022 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | delete_mappings_in_network | def delete_mappings_in_network(network_id, network_2_id=None, **kwargs):
"""
Delete all the resource attribute mappings in a network. If another network
is specified, only delete the mappings between the two networks.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(or_(ResourceAttrMap.network_a_id == network_id, ResourceAttrMap.network_b_id == network_id))
if network_2_id is not None:
qry = qry.filter(or_(ResourceAttrMap.network_a_id==network_2_id, ResourceAttrMap.network_b_id==network_2_id))
mappings = qry.all()
for m in mappings:
db.DBSession.delete(m)
db.DBSession.flush()
return 'OK' | python | def delete_mappings_in_network(network_id, network_2_id=None, **kwargs):
"""
Delete all the resource attribute mappings in a network. If another network
is specified, only delete the mappings between the two networks.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(or_(ResourceAttrMap.network_a_id == network_id, ResourceAttrMap.network_b_id == network_id))
if network_2_id is not None:
qry = qry.filter(or_(ResourceAttrMap.network_a_id==network_2_id, ResourceAttrMap.network_b_id==network_2_id))
mappings = qry.all()
for m in mappings:
db.DBSession.delete(m)
db.DBSession.flush()
return 'OK' | [
"def",
"delete_mappings_in_network",
"(",
"network_id",
",",
"network_2_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceAttrMap",
")",
".",
"filter",
"(",
"or_",
"(",
"ResourceAttrMap",
"... | Delete all the resource attribute mappings in a network. If another network
is specified, only delete the mappings between the two networks. | [
"Delete",
"all",
"the",
"resource",
"attribute",
"mappings",
"in",
"a",
"network",
".",
"If",
"another",
"network",
"is",
"specified",
"only",
"delete",
"the",
"mappings",
"between",
"the",
"two",
"networks",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L540-L556 | train | 46,023 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_network_mappings | def get_network_mappings(network_id, network_2_id=None, **kwargs):
"""
Get all the mappings of network resource attributes, NOT ALL THE MAPPINGS
WITHIN A NETWORK. For that, ``use get_mappings_in_network``. If another network
is specified, only return the mappings between the two networks.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(
or_(
and_(
ResourceAttrMap.resource_attr_id_a == ResourceAttr.id,
ResourceAttr.network_id == network_id),
and_(
ResourceAttrMap.resource_attr_id_b == ResourceAttr.id,
ResourceAttr.network_id == network_id)))
if network_2_id is not None:
aliased_ra = aliased(ResourceAttr, name="ra2")
qry = qry.filter(or_(
and_(
ResourceAttrMap.resource_attr_id_a == aliased_ra.id,
aliased_ra.network_id == network_2_id),
and_(
ResourceAttrMap.resource_attr_id_b == aliased_ra.id,
aliased_ra.network_id == network_2_id)))
return qry.all() | python | def get_network_mappings(network_id, network_2_id=None, **kwargs):
"""
Get all the mappings of network resource attributes, NOT ALL THE MAPPINGS
WITHIN A NETWORK. For that, ``use get_mappings_in_network``. If another network
is specified, only return the mappings between the two networks.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(
or_(
and_(
ResourceAttrMap.resource_attr_id_a == ResourceAttr.id,
ResourceAttr.network_id == network_id),
and_(
ResourceAttrMap.resource_attr_id_b == ResourceAttr.id,
ResourceAttr.network_id == network_id)))
if network_2_id is not None:
aliased_ra = aliased(ResourceAttr, name="ra2")
qry = qry.filter(or_(
and_(
ResourceAttrMap.resource_attr_id_a == aliased_ra.id,
aliased_ra.network_id == network_2_id),
and_(
ResourceAttrMap.resource_attr_id_b == aliased_ra.id,
aliased_ra.network_id == network_2_id)))
return qry.all() | [
"def",
"get_network_mappings",
"(",
"network_id",
",",
"network_2_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceAttrMap",
")",
".",
"filter",
"(",
"or_",
"(",
"and_",
"(",
"ResourceAt... | Get all the mappings of network resource attributes, NOT ALL THE MAPPINGS
WITHIN A NETWORK. For that, ``use get_mappings_in_network``. If another network
is specified, only return the mappings between the two networks. | [
"Get",
"all",
"the",
"mappings",
"of",
"network",
"resource",
"attributes",
"NOT",
"ALL",
"THE",
"MAPPINGS",
"WITHIN",
"A",
"NETWORK",
".",
"For",
"that",
"use",
"get_mappings_in_network",
".",
"If",
"another",
"network",
"is",
"specified",
"only",
"return",
"... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L623-L648 | train | 46,024 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | check_attribute_mapping_exists | def check_attribute_mapping_exists(resource_attr_id_source, resource_attr_id_target, **kwargs):
"""
Check whether an attribute mapping exists between a source and target resource attribute.
returns 'Y' if a mapping exists. Returns 'N' in all other cases.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(
ResourceAttrMap.resource_attr_id_a == resource_attr_id_source,
ResourceAttrMap.resource_attr_id_b == resource_attr_id_target).all()
if len(qry) > 0:
return 'Y'
else:
return 'N' | python | def check_attribute_mapping_exists(resource_attr_id_source, resource_attr_id_target, **kwargs):
"""
Check whether an attribute mapping exists between a source and target resource attribute.
returns 'Y' if a mapping exists. Returns 'N' in all other cases.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(
ResourceAttrMap.resource_attr_id_a == resource_attr_id_source,
ResourceAttrMap.resource_attr_id_b == resource_attr_id_target).all()
if len(qry) > 0:
return 'Y'
else:
return 'N' | [
"def",
"check_attribute_mapping_exists",
"(",
"resource_attr_id_source",
",",
"resource_attr_id_target",
",",
"*",
"*",
"kwargs",
")",
":",
"qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceAttrMap",
")",
".",
"filter",
"(",
"ResourceAttrMap",
".",
... | Check whether an attribute mapping exists between a source and target resource attribute.
returns 'Y' if a mapping exists. Returns 'N' in all other cases. | [
"Check",
"whether",
"an",
"attribute",
"mapping",
"exists",
"between",
"a",
"source",
"and",
"target",
"resource",
"attribute",
".",
"returns",
"Y",
"if",
"a",
"mapping",
"exists",
".",
"Returns",
"N",
"in",
"all",
"other",
"cases",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L650-L662 | train | 46,025 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_attribute_group | def get_attribute_group(group_id, **kwargs):
"""
Get a specific attribute group
"""
user_id=kwargs.get('user_id')
try:
group_i = db.DBSession.query(AttrGroup).filter(
AttrGroup.id==group_id).one()
group_i.project.check_read_permission(user_id)
except NoResultFound:
raise HydraError("Group %s not found" % (group_id,))
return group_i | python | def get_attribute_group(group_id, **kwargs):
"""
Get a specific attribute group
"""
user_id=kwargs.get('user_id')
try:
group_i = db.DBSession.query(AttrGroup).filter(
AttrGroup.id==group_id).one()
group_i.project.check_read_permission(user_id)
except NoResultFound:
raise HydraError("Group %s not found" % (group_id,))
return group_i | [
"def",
"get_attribute_group",
"(",
"group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"try",
":",
"group_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"AttrGroup",
")",
".",
"filter",
"(",
... | Get a specific attribute group | [
"Get",
"a",
"specific",
"attribute",
"group"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L665-L679 | train | 46,026 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | delete_attribute_group | def delete_attribute_group(group_id, **kwargs):
"""
Delete an attribute group.
"""
user_id = kwargs['user_id']
try:
group_i = db.DBSession.query(AttrGroup).filter(AttrGroup.id==group_id).one()
group_i.project.check_write_permission(user_id)
db.DBSession.delete(group_i)
db.DBSession.flush()
log.info("Group %s in project %s deleted", group_i.id, group_i.project_id)
except NoResultFound:
raise HydraError('No Attribute Group %s was found', group_id)
return 'OK' | python | def delete_attribute_group(group_id, **kwargs):
"""
Delete an attribute group.
"""
user_id = kwargs['user_id']
try:
group_i = db.DBSession.query(AttrGroup).filter(AttrGroup.id==group_id).one()
group_i.project.check_write_permission(user_id)
db.DBSession.delete(group_i)
db.DBSession.flush()
log.info("Group %s in project %s deleted", group_i.id, group_i.project_id)
except NoResultFound:
raise HydraError('No Attribute Group %s was found', group_id)
return 'OK' | [
"def",
"delete_attribute_group",
"(",
"group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
"[",
"'user_id'",
"]",
"try",
":",
"group_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"AttrGroup",
")",
".",
"filter",
"(",
"AttrGroup"... | Delete an attribute group. | [
"Delete",
"an",
"attribute",
"group",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L768-L789 | train | 46,027 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_network_attributegroup_items | def get_network_attributegroup_items(network_id, **kwargs):
"""
Get all the group items in a network
"""
user_id=kwargs.get('user_id')
net_i = _get_network(network_id)
net_i.check_read_permission(user_id)
group_items_i = db.DBSession.query(AttrGroupItem).filter(
AttrGroupItem.network_id==network_id).all()
return group_items_i | python | def get_network_attributegroup_items(network_id, **kwargs):
"""
Get all the group items in a network
"""
user_id=kwargs.get('user_id')
net_i = _get_network(network_id)
net_i.check_read_permission(user_id)
group_items_i = db.DBSession.query(AttrGroupItem).filter(
AttrGroupItem.network_id==network_id).all()
return group_items_i | [
"def",
"get_network_attributegroup_items",
"(",
"network_id",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"net_i",
"=",
"_get_network",
"(",
"network_id",
")",
"net_i",
".",
"check_read_permission",
"(",
"use... | Get all the group items in a network | [
"Get",
"all",
"the",
"group",
"items",
"in",
"a",
"network"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L791-L806 | train | 46,028 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_group_attributegroup_items | def get_group_attributegroup_items(network_id, group_id, **kwargs):
"""
Get all the items in a specified group, within a network
"""
user_id=kwargs.get('user_id')
network_i = _get_network(network_id)
network_i.check_read_permission(user_id)
group_items_i = db.DBSession.query(AttrGroupItem).filter(
AttrGroupItem.network_id==network_id,
AttrGroupItem.group_id==group_id).all()
return group_items_i | python | def get_group_attributegroup_items(network_id, group_id, **kwargs):
"""
Get all the items in a specified group, within a network
"""
user_id=kwargs.get('user_id')
network_i = _get_network(network_id)
network_i.check_read_permission(user_id)
group_items_i = db.DBSession.query(AttrGroupItem).filter(
AttrGroupItem.network_id==network_id,
AttrGroupItem.group_id==group_id).all()
return group_items_i | [
"def",
"get_group_attributegroup_items",
"(",
"network_id",
",",
"group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"network_i",
"=",
"_get_network",
"(",
"network_id",
")",
"network_i",
".",
"check_read... | Get all the items in a specified group, within a network | [
"Get",
"all",
"the",
"items",
"in",
"a",
"specified",
"group",
"within",
"a",
"network"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L808-L822 | train | 46,029 |
hydraplatform/hydra-base | hydra_base/lib/attributes.py | get_attribute_item_groups | def get_attribute_item_groups(network_id, attr_id, **kwargs):
"""
Get all the group items in a network with a given attribute_id
"""
user_id=kwargs.get('user_id')
network_i = _get_network(network_id)
network_i.check_read_permission(user_id)
group_items_i = db.DBSession.query(AttrGroupItem).filter(
AttrGroupItem.network_id==network_id,
AttrGroupItem.attr_id==attr_id).all()
return group_items_i | python | def get_attribute_item_groups(network_id, attr_id, **kwargs):
"""
Get all the group items in a network with a given attribute_id
"""
user_id=kwargs.get('user_id')
network_i = _get_network(network_id)
network_i.check_read_permission(user_id)
group_items_i = db.DBSession.query(AttrGroupItem).filter(
AttrGroupItem.network_id==network_id,
AttrGroupItem.attr_id==attr_id).all()
return group_items_i | [
"def",
"get_attribute_item_groups",
"(",
"network_id",
",",
"attr_id",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"network_i",
"=",
"_get_network",
"(",
"network_id",
")",
"network_i",
".",
"check_read_permi... | Get all the group items in a network with a given attribute_id | [
"Get",
"all",
"the",
"group",
"items",
"in",
"a",
"network",
"with",
"a",
"given",
"attribute_id"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/attributes.py#L825-L839 | train | 46,030 |
hydraplatform/hydra-base | hydra_base/lib/sharing.py | share_network | def share_network(network_id, usernames, read_only, share,**kwargs):
"""
Share a network with a list of users, identified by their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users
"""
user_id = kwargs.get('user_id')
net_i = _get_network(network_id)
net_i.check_share_permission(user_id)
if read_only == 'Y':
write = 'N'
share = 'N'
else:
write = 'Y'
if net_i.created_by != int(user_id) and share == 'Y':
raise HydraError("Cannot share the 'sharing' ability as user %s is not"
" the owner of network %s"%
(user_id, network_id))
for username in usernames:
user_i = _get_user(username)
#Set the owner ship on the network itself
net_i.set_owner(user_i.id, write=write, share=share)
for o in net_i.project.owners:
if o.user_id == user_i.id:
break
else:
#Give the user read access to the containing project
net_i.project.set_owner(user_i.id, write='N', share='N')
db.DBSession.flush() | python | def share_network(network_id, usernames, read_only, share,**kwargs):
"""
Share a network with a list of users, identified by their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users
"""
user_id = kwargs.get('user_id')
net_i = _get_network(network_id)
net_i.check_share_permission(user_id)
if read_only == 'Y':
write = 'N'
share = 'N'
else:
write = 'Y'
if net_i.created_by != int(user_id) and share == 'Y':
raise HydraError("Cannot share the 'sharing' ability as user %s is not"
" the owner of network %s"%
(user_id, network_id))
for username in usernames:
user_i = _get_user(username)
#Set the owner ship on the network itself
net_i.set_owner(user_i.id, write=write, share=share)
for o in net_i.project.owners:
if o.user_id == user_i.id:
break
else:
#Give the user read access to the containing project
net_i.project.set_owner(user_i.id, write='N', share='N')
db.DBSession.flush() | [
"def",
"share_network",
"(",
"network_id",
",",
"usernames",
",",
"read_only",
",",
"share",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"net_i",
"=",
"_get_network",
"(",
"network_id",
")",
"net_i",
".... | Share a network with a list of users, identified by their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users | [
"Share",
"a",
"network",
"with",
"a",
"list",
"of",
"users",
"identified",
"by",
"their",
"usernames",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/sharing.py#L57-L93 | train | 46,031 |
hydraplatform/hydra-base | hydra_base/lib/sharing.py | unshare_network | def unshare_network(network_id, usernames,**kwargs):
"""
Un-Share a network with a list of users, identified by their usernames.
"""
user_id = kwargs.get('user_id')
net_i = _get_network(network_id)
net_i.check_share_permission(user_id)
for username in usernames:
user_i = _get_user(username)
#Set the owner ship on the network itself
net_i.unset_owner(user_i.id, write=write, share=share)
db.DBSession.flush() | python | def unshare_network(network_id, usernames,**kwargs):
"""
Un-Share a network with a list of users, identified by their usernames.
"""
user_id = kwargs.get('user_id')
net_i = _get_network(network_id)
net_i.check_share_permission(user_id)
for username in usernames:
user_i = _get_user(username)
#Set the owner ship on the network itself
net_i.unset_owner(user_i.id, write=write, share=share)
db.DBSession.flush() | [
"def",
"unshare_network",
"(",
"network_id",
",",
"usernames",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"net_i",
"=",
"_get_network",
"(",
"network_id",
")",
"net_i",
".",
"check_share_permission",
"(",
... | Un-Share a network with a list of users, identified by their usernames. | [
"Un",
"-",
"Share",
"a",
"network",
"with",
"a",
"list",
"of",
"users",
"identified",
"by",
"their",
"usernames",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/sharing.py#L95-L109 | train | 46,032 |
hydraplatform/hydra-base | hydra_base/lib/sharing.py | share_project | def share_project(project_id, usernames, read_only, share,**kwargs):
"""
Share an entire project with a list of users, identifed by
their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users
"""
user_id = kwargs.get('user_id')
proj_i = _get_project(project_id)
#Is the sharing user allowed to share this project?
proj_i.check_share_permission(int(user_id))
user_id = int(user_id)
for owner in proj_i.owners:
if user_id == owner.user_id:
break
else:
raise HydraError("Permission Denied. Cannot share project.")
if read_only == 'Y':
write = 'N'
share = 'N'
else:
write = 'Y'
if proj_i.created_by != user_id and share == 'Y':
raise HydraError("Cannot share the 'sharing' ability as user %s is not"
" the owner of project %s"%
(user_id, project_id))
for username in usernames:
user_i = _get_user(username)
proj_i.set_owner(user_i.id, write=write, share=share)
for net_i in proj_i.networks:
net_i.set_owner(user_i.id, write=write, share=share)
db.DBSession.flush() | python | def share_project(project_id, usernames, read_only, share,**kwargs):
"""
Share an entire project with a list of users, identifed by
their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users
"""
user_id = kwargs.get('user_id')
proj_i = _get_project(project_id)
#Is the sharing user allowed to share this project?
proj_i.check_share_permission(int(user_id))
user_id = int(user_id)
for owner in proj_i.owners:
if user_id == owner.user_id:
break
else:
raise HydraError("Permission Denied. Cannot share project.")
if read_only == 'Y':
write = 'N'
share = 'N'
else:
write = 'Y'
if proj_i.created_by != user_id and share == 'Y':
raise HydraError("Cannot share the 'sharing' ability as user %s is not"
" the owner of project %s"%
(user_id, project_id))
for username in usernames:
user_i = _get_user(username)
proj_i.set_owner(user_i.id, write=write, share=share)
for net_i in proj_i.networks:
net_i.set_owner(user_i.id, write=write, share=share)
db.DBSession.flush() | [
"def",
"share_project",
"(",
"project_id",
",",
"usernames",
",",
"read_only",
",",
"share",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"proj_i",
"=",
"_get_project",
"(",
"project_id",
")",
"#Is the sha... | Share an entire project with a list of users, identifed by
their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users | [
"Share",
"an",
"entire",
"project",
"with",
"a",
"list",
"of",
"users",
"identifed",
"by",
"their",
"usernames",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/sharing.py#L111-L155 | train | 46,033 |
hydraplatform/hydra-base | hydra_base/lib/sharing.py | unshare_project | def unshare_project(project_id, usernames,**kwargs):
"""
Un-share a project with a list of users, identified by their usernames.
"""
user_id = kwargs.get('user_id')
proj_i = _get_project(project_id)
proj_i.check_share_permission(user_id)
for username in usernames:
user_i = _get_user(username)
#Set the owner ship on the network itself
proj_i.unset_owner(user_i.id, write=write, share=share)
db.DBSession.flush() | python | def unshare_project(project_id, usernames,**kwargs):
"""
Un-share a project with a list of users, identified by their usernames.
"""
user_id = kwargs.get('user_id')
proj_i = _get_project(project_id)
proj_i.check_share_permission(user_id)
for username in usernames:
user_i = _get_user(username)
#Set the owner ship on the network itself
proj_i.unset_owner(user_i.id, write=write, share=share)
db.DBSession.flush() | [
"def",
"unshare_project",
"(",
"project_id",
",",
"usernames",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"proj_i",
"=",
"_get_project",
"(",
"project_id",
")",
"proj_i",
".",
"check_share_permission",
"("... | Un-share a project with a list of users, identified by their usernames. | [
"Un",
"-",
"share",
"a",
"project",
"with",
"a",
"list",
"of",
"users",
"identified",
"by",
"their",
"usernames",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/sharing.py#L157-L170 | train | 46,034 |
hydraplatform/hydra-base | hydra_base/lib/sharing.py | set_project_permission | def set_project_permission(project_id, usernames, read, write, share,**kwargs):
"""
Set permissions on a project to a list of users, identifed by
their usernames.
The read flag ('Y' or 'N') sets read access, the write
flag sets write access. If the read flag is 'N', then there is
automatically no write access or share access.
"""
user_id = kwargs.get('user_id')
proj_i = _get_project(project_id)
#Is the sharing user allowed to share this project?
proj_i.check_share_permission(user_id)
#You cannot edit something you cannot see.
if read == 'N':
write = 'N'
share = 'N'
for username in usernames:
user_i = _get_user(username)
#The creator of a project must always have read and write access
#to their project
if proj_i.created_by == user_i.id:
raise HydraError("Cannot set permissions on project %s"
" for user %s as this user is the creator." %
(project_id, username))
proj_i.set_owner(user_i.id, read=read, write=write)
for net_i in proj_i.networks:
net_i.set_owner(user_i.id, read=read, write=write, share=share)
db.DBSession.flush() | python | def set_project_permission(project_id, usernames, read, write, share,**kwargs):
"""
Set permissions on a project to a list of users, identifed by
their usernames.
The read flag ('Y' or 'N') sets read access, the write
flag sets write access. If the read flag is 'N', then there is
automatically no write access or share access.
"""
user_id = kwargs.get('user_id')
proj_i = _get_project(project_id)
#Is the sharing user allowed to share this project?
proj_i.check_share_permission(user_id)
#You cannot edit something you cannot see.
if read == 'N':
write = 'N'
share = 'N'
for username in usernames:
user_i = _get_user(username)
#The creator of a project must always have read and write access
#to their project
if proj_i.created_by == user_i.id:
raise HydraError("Cannot set permissions on project %s"
" for user %s as this user is the creator." %
(project_id, username))
proj_i.set_owner(user_i.id, read=read, write=write)
for net_i in proj_i.networks:
net_i.set_owner(user_i.id, read=read, write=write, share=share)
db.DBSession.flush() | [
"def",
"set_project_permission",
"(",
"project_id",
",",
"usernames",
",",
"read",
",",
"write",
",",
"share",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"proj_i",
"=",
"_get_project",
"(",
"project_id",... | Set permissions on a project to a list of users, identifed by
their usernames.
The read flag ('Y' or 'N') sets read access, the write
flag sets write access. If the read flag is 'N', then there is
automatically no write access or share access. | [
"Set",
"permissions",
"on",
"a",
"project",
"to",
"a",
"list",
"of",
"users",
"identifed",
"by",
"their",
"usernames",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/sharing.py#L172-L207 | train | 46,035 |
hydraplatform/hydra-base | hydra_base/lib/sharing.py | get_all_project_owners | def get_all_project_owners(project_ids=None, **kwargs):
"""
Get the project owner entries for all the requested projects.
If the project_ids argument is None, return all the owner entries
for ALL projects
"""
projowner_qry = db.DBSession.query(ProjectOwner)
if project_ids is not None:
projowner_qry = projowner_qry.filter(ProjectOwner.project_id.in_(project_ids))
project_owners_i = projowner_qry.all()
return [JSONObject(project_owner_i) for project_owner_i in project_owners_i] | python | def get_all_project_owners(project_ids=None, **kwargs):
"""
Get the project owner entries for all the requested projects.
If the project_ids argument is None, return all the owner entries
for ALL projects
"""
projowner_qry = db.DBSession.query(ProjectOwner)
if project_ids is not None:
projowner_qry = projowner_qry.filter(ProjectOwner.project_id.in_(project_ids))
project_owners_i = projowner_qry.all()
return [JSONObject(project_owner_i) for project_owner_i in project_owners_i] | [
"def",
"get_all_project_owners",
"(",
"project_ids",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"projowner_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ProjectOwner",
")",
"if",
"project_ids",
"is",
"not",
"None",
":",
"projowner_qry",
"=",
... | Get the project owner entries for all the requested projects.
If the project_ids argument is None, return all the owner entries
for ALL projects | [
"Get",
"the",
"project",
"owner",
"entries",
"for",
"all",
"the",
"requested",
"projects",
".",
"If",
"the",
"project_ids",
"argument",
"is",
"None",
"return",
"all",
"the",
"owner",
"entries",
"for",
"ALL",
"projects"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/sharing.py#L290-L305 | train | 46,036 |
hydraplatform/hydra-base | hydra_base/lib/sharing.py | get_all_network_owners | def get_all_network_owners(network_ids=None, **kwargs):
"""
Get the network owner entries for all the requested networks.
If the network_ids argument is None, return all the owner entries
for ALL networks
"""
networkowner_qry = db.DBSession.query(NetworkOwner)
if network_ids is not None:
networkowner_qry = networkowner_qry.filter(NetworkOwner.network_id.in_(network_ids))
network_owners_i = networkowner_qry.all()
return [JSONObject(network_owner_i) for network_owner_i in network_owners_i] | python | def get_all_network_owners(network_ids=None, **kwargs):
"""
Get the network owner entries for all the requested networks.
If the network_ids argument is None, return all the owner entries
for ALL networks
"""
networkowner_qry = db.DBSession.query(NetworkOwner)
if network_ids is not None:
networkowner_qry = networkowner_qry.filter(NetworkOwner.network_id.in_(network_ids))
network_owners_i = networkowner_qry.all()
return [JSONObject(network_owner_i) for network_owner_i in network_owners_i] | [
"def",
"get_all_network_owners",
"(",
"network_ids",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"networkowner_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"NetworkOwner",
")",
"if",
"network_ids",
"is",
"not",
"None",
":",
"networkowner_qry",
"... | Get the network owner entries for all the requested networks.
If the network_ids argument is None, return all the owner entries
for ALL networks | [
"Get",
"the",
"network",
"owner",
"entries",
"for",
"all",
"the",
"requested",
"networks",
".",
"If",
"the",
"network_ids",
"argument",
"is",
"None",
"return",
"all",
"the",
"owner",
"entries",
"for",
"ALL",
"networks"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/sharing.py#L308-L323 | train | 46,037 |
hydraplatform/hydra-base | hydra_base/lib/data.py | add_dataset | def add_dataset(data_type, val, unit_id=None, metadata={}, name="", user_id=None, flush=False):
"""
Data can exist without scenarios. This is the mechanism whereby
single pieces of data can be added without doing it through a scenario.
A typical use of this would be for setting default values on types.
"""
d = Dataset()
d.type = data_type
d.value = val
d.set_metadata(metadata)
d.unit_id = unit_id
d.name = name
d.created_by = user_id
d.hash = d.set_hash()
try:
existing_dataset = db.DBSession.query(Dataset).filter(Dataset.hash==d.hash).one()
if existing_dataset.check_user(user_id):
d = existing_dataset
else:
d.set_metadata({'created_at': datetime.datetime.now()})
d.set_hash()
db.DBSession.add(d)
except NoResultFound:
db.DBSession.add(d)
if flush == True:
db.DBSession.flush()
return d | python | def add_dataset(data_type, val, unit_id=None, metadata={}, name="", user_id=None, flush=False):
"""
Data can exist without scenarios. This is the mechanism whereby
single pieces of data can be added without doing it through a scenario.
A typical use of this would be for setting default values on types.
"""
d = Dataset()
d.type = data_type
d.value = val
d.set_metadata(metadata)
d.unit_id = unit_id
d.name = name
d.created_by = user_id
d.hash = d.set_hash()
try:
existing_dataset = db.DBSession.query(Dataset).filter(Dataset.hash==d.hash).one()
if existing_dataset.check_user(user_id):
d = existing_dataset
else:
d.set_metadata({'created_at': datetime.datetime.now()})
d.set_hash()
db.DBSession.add(d)
except NoResultFound:
db.DBSession.add(d)
if flush == True:
db.DBSession.flush()
return d | [
"def",
"add_dataset",
"(",
"data_type",
",",
"val",
",",
"unit_id",
"=",
"None",
",",
"metadata",
"=",
"{",
"}",
",",
"name",
"=",
"\"\"",
",",
"user_id",
"=",
"None",
",",
"flush",
"=",
"False",
")",
":",
"d",
"=",
"Dataset",
"(",
")",
"d",
".",... | Data can exist without scenarios. This is the mechanism whereby
single pieces of data can be added without doing it through a scenario.
A typical use of this would be for setting default values on types. | [
"Data",
"can",
"exist",
"without",
"scenarios",
".",
"This",
"is",
"the",
"mechanism",
"whereby",
"single",
"pieces",
"of",
"data",
"can",
"be",
"added",
"without",
"doing",
"it",
"through",
"a",
"scenario",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/data.py#L465-L497 | train | 46,038 |
hydraplatform/hydra-base | hydra_base/lib/data.py | _bulk_insert_data | def _bulk_insert_data(bulk_data, user_id=None, source=None):
"""
Insert lots of datasets at once to reduce the number of DB interactions.
user_id indicates the user adding the data
source indicates the name of the app adding the data
both user_id and source are added as metadata
"""
get_timing = lambda x: datetime.datetime.now() - x
start_time=datetime.datetime.now()
new_data = _process_incoming_data(bulk_data, user_id, source)
log.info("Incoming data processed in %s", (get_timing(start_time)))
existing_data = _get_existing_data(new_data.keys())
log.info("Existing data retrieved.")
#The list of dataset IDS to be returned.
hash_id_map = {}
new_datasets = []
metadata = {}
#This is what gets returned.
for d in bulk_data:
dataset_dict = new_data[d.hash]
current_hash = d.hash
#if this piece of data is already in the DB, then
#there is no need to insert it!
if existing_data.get(current_hash) is not None:
dataset = existing_data.get(current_hash)
#Is this user allowed to use this dataset?
if dataset.check_user(user_id) == False:
new_dataset = _make_new_dataset(dataset_dict)
new_datasets.append(new_dataset)
metadata[new_dataset['hash']] = dataset_dict['metadata']
else:
hash_id_map[current_hash] = dataset#existing_data[current_hash]
elif current_hash in hash_id_map:
new_datasets.append(dataset_dict)
else:
#set a placeholder for a dataset_id we don't know yet.
#The placeholder is the hash, which is unique to this object and
#therefore easily identifiable.
new_datasets.append(dataset_dict)
hash_id_map[current_hash] = dataset_dict
metadata[current_hash] = dataset_dict['metadata']
log.debug("Isolating new data %s", get_timing(start_time))
#Isolate only the new datasets and insert them
new_data_for_insert = []
#keep track of the datasets that are to be inserted to avoid duplicate
#inserts
new_data_hashes = []
for d in new_datasets:
if d['hash'] not in new_data_hashes:
new_data_for_insert.append(d)
new_data_hashes.append(d['hash'])
if len(new_data_for_insert) > 0:
#If we're working with mysql, we have to lock the table..
#For sqlite, this is not possible. Hence the try: except
#try:
# db.DBSession.execute("LOCK TABLES tDataset WRITE, tMetadata WRITE")
#except OperationalError:
# pass
log.debug("Inserting new data %s", get_timing(start_time))
db.DBSession.bulk_insert_mappings(Dataset, new_data_for_insert)
log.debug("New data Inserted %s", get_timing(start_time))
#try:
# db.DBSession.execute("UNLOCK TABLES")
#except OperationalError:
# pass
new_data = _get_existing_data(new_data_hashes)
log.debug("New data retrieved %s", get_timing(start_time))
for k, v in new_data.items():
hash_id_map[k] = v
_insert_metadata(metadata, hash_id_map)
log.debug("Metadata inserted %s", get_timing(start_time))
returned_ids = []
for d in bulk_data:
returned_ids.append(hash_id_map[d.hash])
log.info("Done bulk inserting data. %s datasets", len(returned_ids))
return returned_ids | python | def _bulk_insert_data(bulk_data, user_id=None, source=None):
"""
Insert lots of datasets at once to reduce the number of DB interactions.
user_id indicates the user adding the data
source indicates the name of the app adding the data
both user_id and source are added as metadata
"""
get_timing = lambda x: datetime.datetime.now() - x
start_time=datetime.datetime.now()
new_data = _process_incoming_data(bulk_data, user_id, source)
log.info("Incoming data processed in %s", (get_timing(start_time)))
existing_data = _get_existing_data(new_data.keys())
log.info("Existing data retrieved.")
#The list of dataset IDS to be returned.
hash_id_map = {}
new_datasets = []
metadata = {}
#This is what gets returned.
for d in bulk_data:
dataset_dict = new_data[d.hash]
current_hash = d.hash
#if this piece of data is already in the DB, then
#there is no need to insert it!
if existing_data.get(current_hash) is not None:
dataset = existing_data.get(current_hash)
#Is this user allowed to use this dataset?
if dataset.check_user(user_id) == False:
new_dataset = _make_new_dataset(dataset_dict)
new_datasets.append(new_dataset)
metadata[new_dataset['hash']] = dataset_dict['metadata']
else:
hash_id_map[current_hash] = dataset#existing_data[current_hash]
elif current_hash in hash_id_map:
new_datasets.append(dataset_dict)
else:
#set a placeholder for a dataset_id we don't know yet.
#The placeholder is the hash, which is unique to this object and
#therefore easily identifiable.
new_datasets.append(dataset_dict)
hash_id_map[current_hash] = dataset_dict
metadata[current_hash] = dataset_dict['metadata']
log.debug("Isolating new data %s", get_timing(start_time))
#Isolate only the new datasets and insert them
new_data_for_insert = []
#keep track of the datasets that are to be inserted to avoid duplicate
#inserts
new_data_hashes = []
for d in new_datasets:
if d['hash'] not in new_data_hashes:
new_data_for_insert.append(d)
new_data_hashes.append(d['hash'])
if len(new_data_for_insert) > 0:
#If we're working with mysql, we have to lock the table..
#For sqlite, this is not possible. Hence the try: except
#try:
# db.DBSession.execute("LOCK TABLES tDataset WRITE, tMetadata WRITE")
#except OperationalError:
# pass
log.debug("Inserting new data %s", get_timing(start_time))
db.DBSession.bulk_insert_mappings(Dataset, new_data_for_insert)
log.debug("New data Inserted %s", get_timing(start_time))
#try:
# db.DBSession.execute("UNLOCK TABLES")
#except OperationalError:
# pass
new_data = _get_existing_data(new_data_hashes)
log.debug("New data retrieved %s", get_timing(start_time))
for k, v in new_data.items():
hash_id_map[k] = v
_insert_metadata(metadata, hash_id_map)
log.debug("Metadata inserted %s", get_timing(start_time))
returned_ids = []
for d in bulk_data:
returned_ids.append(hash_id_map[d.hash])
log.info("Done bulk inserting data. %s datasets", len(returned_ids))
return returned_ids | [
"def",
"_bulk_insert_data",
"(",
"bulk_data",
",",
"user_id",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"get_timing",
"=",
"lambda",
"x",
":",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"x",
"start_time",
"=",
"datetime",
".",
"da... | Insert lots of datasets at once to reduce the number of DB interactions.
user_id indicates the user adding the data
source indicates the name of the app adding the data
both user_id and source are added as metadata | [
"Insert",
"lots",
"of",
"datasets",
"at",
"once",
"to",
"reduce",
"the",
"number",
"of",
"DB",
"interactions",
".",
"user_id",
"indicates",
"the",
"user",
"adding",
"the",
"data",
"source",
"indicates",
"the",
"name",
"of",
"the",
"app",
"adding",
"the",
"... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/data.py#L520-L612 | train | 46,039 |
hydraplatform/hydra-base | hydra_base/lib/data.py | _get_metadata | def _get_metadata(dataset_ids):
"""
Get all the metadata for a given list of datasets
"""
metadata = []
if len(dataset_ids) == 0:
return []
if len(dataset_ids) > qry_in_threshold:
idx = 0
extent = qry_in_threshold
while idx < len(dataset_ids):
log.info("Querying %s metadatas", len(dataset_ids[idx:extent]))
rs = db.DBSession.query(Metadata).filter(Metadata.dataset_id.in_(dataset_ids[idx:extent])).all()
metadata.extend(rs)
idx = idx + qry_in_threshold
if idx + qry_in_threshold > len(dataset_ids):
extent = len(dataset_ids)
else:
extent = extent +qry_in_threshold
else:
metadata_qry = db.DBSession.query(Metadata).filter(Metadata.dataset_id.in_(dataset_ids))
for m in metadata_qry:
metadata.append(m)
return metadata | python | def _get_metadata(dataset_ids):
"""
Get all the metadata for a given list of datasets
"""
metadata = []
if len(dataset_ids) == 0:
return []
if len(dataset_ids) > qry_in_threshold:
idx = 0
extent = qry_in_threshold
while idx < len(dataset_ids):
log.info("Querying %s metadatas", len(dataset_ids[idx:extent]))
rs = db.DBSession.query(Metadata).filter(Metadata.dataset_id.in_(dataset_ids[idx:extent])).all()
metadata.extend(rs)
idx = idx + qry_in_threshold
if idx + qry_in_threshold > len(dataset_ids):
extent = len(dataset_ids)
else:
extent = extent +qry_in_threshold
else:
metadata_qry = db.DBSession.query(Metadata).filter(Metadata.dataset_id.in_(dataset_ids))
for m in metadata_qry:
metadata.append(m)
return metadata | [
"def",
"_get_metadata",
"(",
"dataset_ids",
")",
":",
"metadata",
"=",
"[",
"]",
"if",
"len",
"(",
"dataset_ids",
")",
"==",
"0",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"dataset_ids",
")",
">",
"qry_in_threshold",
":",
"idx",
"=",
"0",
"extent",
... | Get all the metadata for a given list of datasets | [
"Get",
"all",
"the",
"metadata",
"for",
"a",
"given",
"list",
"of",
"datasets"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/data.py#L677-L702 | train | 46,040 |
hydraplatform/hydra-base | hydra_base/lib/data.py | _get_datasets | def _get_datasets(dataset_ids):
"""
Get all the datasets in a list of dataset IDS. This must be done in chunks of 999,
as sqlite can only handle 'in' with < 1000 elements.
"""
dataset_dict = {}
datasets = []
if len(dataset_ids) > qry_in_threshold:
idx = 0
extent =qry_in_threshold
while idx < len(dataset_ids):
log.info("Querying %s datasets", len(dataset_ids[idx:extent]))
rs = db.DBSession.query(Dataset).filter(Dataset.id.in_(dataset_ids[idx:extent])).all()
datasets.extend(rs)
idx = idx + qry_in_threshold
if idx + qry_in_threshold > len(dataset_ids):
extent = len(dataset_ids)
else:
extent = extent + qry_in_threshold
else:
datasets = db.DBSession.query(Dataset).filter(Dataset.id.in_(dataset_ids))
for r in datasets:
dataset_dict[r.id] = r
log.info("Retrieved %s datasets", len(dataset_dict))
return dataset_dict | python | def _get_datasets(dataset_ids):
"""
Get all the datasets in a list of dataset IDS. This must be done in chunks of 999,
as sqlite can only handle 'in' with < 1000 elements.
"""
dataset_dict = {}
datasets = []
if len(dataset_ids) > qry_in_threshold:
idx = 0
extent =qry_in_threshold
while idx < len(dataset_ids):
log.info("Querying %s datasets", len(dataset_ids[idx:extent]))
rs = db.DBSession.query(Dataset).filter(Dataset.id.in_(dataset_ids[idx:extent])).all()
datasets.extend(rs)
idx = idx + qry_in_threshold
if idx + qry_in_threshold > len(dataset_ids):
extent = len(dataset_ids)
else:
extent = extent + qry_in_threshold
else:
datasets = db.DBSession.query(Dataset).filter(Dataset.id.in_(dataset_ids))
for r in datasets:
dataset_dict[r.id] = r
log.info("Retrieved %s datasets", len(dataset_dict))
return dataset_dict | [
"def",
"_get_datasets",
"(",
"dataset_ids",
")",
":",
"dataset_dict",
"=",
"{",
"}",
"datasets",
"=",
"[",
"]",
"if",
"len",
"(",
"dataset_ids",
")",
">",
"qry_in_threshold",
":",
"idx",
"=",
"0",
"extent",
"=",
"qry_in_threshold",
"while",
"idx",
"<",
"... | Get all the datasets in a list of dataset IDS. This must be done in chunks of 999,
as sqlite can only handle 'in' with < 1000 elements. | [
"Get",
"all",
"the",
"datasets",
"in",
"a",
"list",
"of",
"dataset",
"IDS",
".",
"This",
"must",
"be",
"done",
"in",
"chunks",
"of",
"999",
"as",
"sqlite",
"can",
"only",
"handle",
"in",
"with",
"<",
"1000",
"elements",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/data.py#L735-L766 | train | 46,041 |
hydraplatform/hydra-base | hydra_base/lib/data.py | get_vals_between_times | def get_vals_between_times(dataset_id, start_time, end_time, timestep,increment,**kwargs):
"""
Retrive data between two specified times within a timeseries. The times
need not be specified in the timeseries. This function will 'fill in the blanks'.
Two types of data retrieval can be done.
If the timeseries is timestamp-based, then start_time and end_time
must be datetimes and timestep must be specified (minutes, seconds etc).
'increment' reflects the size of the timestep -- timestep = 'minutes' and increment = 2
means 'every 2 minutes'.
If the timeseries is float-based (relative), then start_time and end_time
must be decimal values. timestep is ignored and 'increment' represents the increment
to be used between the start and end.
Ex: start_time = 1, end_time = 5, increment = 1 will get times at 1, 2, 3, 4, 5
"""
try:
server_start_time = get_datetime(start_time)
server_end_time = get_datetime(end_time)
times = [server_start_time]
next_time = server_start_time
while next_time < server_end_time:
if int(increment) == 0:
raise HydraError("%s is not a valid increment for this search."%increment)
next_time = next_time + datetime.timedelta(**{timestep:int(increment)})
times.append(next_time)
except ValueError:
try:
server_start_time = Decimal(start_time)
server_end_time = Decimal(end_time)
times = [float(server_start_time)]
next_time = server_start_time
while next_time < server_end_time:
next_time = float(next_time) + increment
times.append(next_time)
except:
raise HydraError("Unable to get times. Please check to and from times.")
td = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one()
log.debug("Number of times to fetch: %s", len(times))
data = td.get_val(timestamp=times)
data_to_return = []
if type(data) is list:
for d in data:
if d is not None:
data_to_return.append(list(d))
elif data is None:
data_to_return = []
else:
data_to_return.append(data)
dataset = JSONObject({'data' : json.dumps(data_to_return)})
return dataset | python | def get_vals_between_times(dataset_id, start_time, end_time, timestep,increment,**kwargs):
"""
Retrive data between two specified times within a timeseries. The times
need not be specified in the timeseries. This function will 'fill in the blanks'.
Two types of data retrieval can be done.
If the timeseries is timestamp-based, then start_time and end_time
must be datetimes and timestep must be specified (minutes, seconds etc).
'increment' reflects the size of the timestep -- timestep = 'minutes' and increment = 2
means 'every 2 minutes'.
If the timeseries is float-based (relative), then start_time and end_time
must be decimal values. timestep is ignored and 'increment' represents the increment
to be used between the start and end.
Ex: start_time = 1, end_time = 5, increment = 1 will get times at 1, 2, 3, 4, 5
"""
try:
server_start_time = get_datetime(start_time)
server_end_time = get_datetime(end_time)
times = [server_start_time]
next_time = server_start_time
while next_time < server_end_time:
if int(increment) == 0:
raise HydraError("%s is not a valid increment for this search."%increment)
next_time = next_time + datetime.timedelta(**{timestep:int(increment)})
times.append(next_time)
except ValueError:
try:
server_start_time = Decimal(start_time)
server_end_time = Decimal(end_time)
times = [float(server_start_time)]
next_time = server_start_time
while next_time < server_end_time:
next_time = float(next_time) + increment
times.append(next_time)
except:
raise HydraError("Unable to get times. Please check to and from times.")
td = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one()
log.debug("Number of times to fetch: %s", len(times))
data = td.get_val(timestamp=times)
data_to_return = []
if type(data) is list:
for d in data:
if d is not None:
data_to_return.append(list(d))
elif data is None:
data_to_return = []
else:
data_to_return.append(data)
dataset = JSONObject({'data' : json.dumps(data_to_return)})
return dataset | [
"def",
"get_vals_between_times",
"(",
"dataset_id",
",",
"start_time",
",",
"end_time",
",",
"timestep",
",",
"increment",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"server_start_time",
"=",
"get_datetime",
"(",
"start_time",
")",
"server_end_time",
"=",
... | Retrive data between two specified times within a timeseries. The times
need not be specified in the timeseries. This function will 'fill in the blanks'.
Two types of data retrieval can be done.
If the timeseries is timestamp-based, then start_time and end_time
must be datetimes and timestep must be specified (minutes, seconds etc).
'increment' reflects the size of the timestep -- timestep = 'minutes' and increment = 2
means 'every 2 minutes'.
If the timeseries is float-based (relative), then start_time and end_time
must be decimal values. timestep is ignored and 'increment' represents the increment
to be used between the start and end.
Ex: start_time = 1, end_time = 5, increment = 1 will get times at 1, 2, 3, 4, 5 | [
"Retrive",
"data",
"between",
"two",
"specified",
"times",
"within",
"a",
"timeseries",
".",
"The",
"times",
"need",
"not",
"be",
"specified",
"in",
"the",
"timeseries",
".",
"This",
"function",
"will",
"fill",
"in",
"the",
"blanks",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/data.py#L974-L1032 | train | 46,042 |
hydraplatform/hydra-base | hydra_base/lib/data.py | delete_dataset | def delete_dataset(dataset_id,**kwargs):
"""
Removes a piece of data from the DB.
CAUTION! Use with care, as this cannot be undone easily.
"""
try:
d = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one()
except NoResultFound:
raise HydraError("Dataset %s does not exist."%dataset_id)
dataset_rs = db.DBSession.query(ResourceScenario).filter(ResourceScenario.dataset_id==dataset_id).all()
if len(dataset_rs) > 0:
raise HydraError("Cannot delete %s. Dataset is used by one or more resource scenarios."%dataset_id)
db.DBSession.delete(d)
db.DBSession.flush()
#Remove ORM references to children of this dataset (metadata, collection items)
db.DBSession.expunge_all() | python | def delete_dataset(dataset_id,**kwargs):
"""
Removes a piece of data from the DB.
CAUTION! Use with care, as this cannot be undone easily.
"""
try:
d = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one()
except NoResultFound:
raise HydraError("Dataset %s does not exist."%dataset_id)
dataset_rs = db.DBSession.query(ResourceScenario).filter(ResourceScenario.dataset_id==dataset_id).all()
if len(dataset_rs) > 0:
raise HydraError("Cannot delete %s. Dataset is used by one or more resource scenarios."%dataset_id)
db.DBSession.delete(d)
db.DBSession.flush()
#Remove ORM references to children of this dataset (metadata, collection items)
db.DBSession.expunge_all() | [
"def",
"delete_dataset",
"(",
"dataset_id",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"d",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dataset",
")",
".",
"filter",
"(",
"Dataset",
".",
"id",
"==",
"dataset_id",
")",
".",
"one",
"(",
")",... | Removes a piece of data from the DB.
CAUTION! Use with care, as this cannot be undone easily. | [
"Removes",
"a",
"piece",
"of",
"data",
"from",
"the",
"DB",
".",
"CAUTION!",
"Use",
"with",
"care",
"as",
"this",
"cannot",
"be",
"undone",
"easily",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/data.py#L1034-L1053 | train | 46,043 |
hydraplatform/hydra-base | hydra_base/lib/notes.py | add_note | def add_note(note, **kwargs):
"""
Add a new note
"""
note_i = Note()
note_i.ref_key = note.ref_key
note_i.set_ref(note.ref_key, note.ref_id)
note_i.value = note.value
note_i.created_by = kwargs.get('user_id')
db.DBSession.add(note_i)
db.DBSession.flush()
return note_i | python | def add_note(note, **kwargs):
"""
Add a new note
"""
note_i = Note()
note_i.ref_key = note.ref_key
note_i.set_ref(note.ref_key, note.ref_id)
note_i.value = note.value
note_i.created_by = kwargs.get('user_id')
db.DBSession.add(note_i)
db.DBSession.flush()
return note_i | [
"def",
"add_note",
"(",
"note",
",",
"*",
"*",
"kwargs",
")",
":",
"note_i",
"=",
"Note",
"(",
")",
"note_i",
".",
"ref_key",
"=",
"note",
".",
"ref_key",
"note_i",
".",
"set_ref",
"(",
"note",
".",
"ref_key",
",",
"note",
".",
"ref_id",
")",
"note... | Add a new note | [
"Add",
"a",
"new",
"note"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/notes.py#L64-L80 | train | 46,044 |
hydraplatform/hydra-base | hydra_base/lib/notes.py | update_note | def update_note(note, **kwargs):
"""
Update a note
"""
note_i = _get_note(note.id)
if note.ref_key != note_i.ref_key:
raise HydraError("Cannot convert a %s note to a %s note. Please create a new note instead."%(note_i.ref_key, note.ref_key))
note_i.set_ref(note.ref_key, note.ref_id)
note_i.value = note.value
db.DBSession.flush()
return note_i | python | def update_note(note, **kwargs):
"""
Update a note
"""
note_i = _get_note(note.id)
if note.ref_key != note_i.ref_key:
raise HydraError("Cannot convert a %s note to a %s note. Please create a new note instead."%(note_i.ref_key, note.ref_key))
note_i.set_ref(note.ref_key, note.ref_id)
note_i.value = note.value
db.DBSession.flush()
return note_i | [
"def",
"update_note",
"(",
"note",
",",
"*",
"*",
"kwargs",
")",
":",
"note_i",
"=",
"_get_note",
"(",
"note",
".",
"id",
")",
"if",
"note",
".",
"ref_key",
"!=",
"note_i",
".",
"ref_key",
":",
"raise",
"HydraError",
"(",
"\"Cannot convert a %s note to a %... | Update a note | [
"Update",
"a",
"note"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/notes.py#L82-L97 | train | 46,045 |
hydraplatform/hydra-base | hydra_base/lib/notes.py | purge_note | def purge_note(note_id, **kwargs):
"""
Remove a note from the DB permenantly
"""
note_i = _get_note(note_id)
db.DBSession.delete(note_i)
db.DBSession.flush() | python | def purge_note(note_id, **kwargs):
"""
Remove a note from the DB permenantly
"""
note_i = _get_note(note_id)
db.DBSession.delete(note_i)
db.DBSession.flush() | [
"def",
"purge_note",
"(",
"note_id",
",",
"*",
"*",
"kwargs",
")",
":",
"note_i",
"=",
"_get_note",
"(",
"note_id",
")",
"db",
".",
"DBSession",
".",
"delete",
"(",
"note_i",
")",
"db",
".",
"DBSession",
".",
"flush",
"(",
")"
] | Remove a note from the DB permenantly | [
"Remove",
"a",
"note",
"from",
"the",
"DB",
"permenantly"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/notes.py#L99-L107 | train | 46,046 |
hydraplatform/hydra-base | hydra_base/lib/service.py | login | def login(username, password, **kwargs):
"""
Login a user, returning a dict containing their user_id and session_id
This does the DB login to check the credentials, and then creates a session
so that requests from apps do not need to perform a login
args:
username (string): The user's username
password(string): The user's password (unencrypted)
returns:
A dict containing the user_id and session_id
raises:
HydraError if the login fails
"""
user_id = util.hdb.login_user(username, password)
hydra_session = session.Session({}, #This is normally a request object, but in this case is empty
validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),
type='file',
cookie_expires=True,
data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'),
file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth'))
hydra_session['user_id'] = user_id
hydra_session['username'] = username
hydra_session.save()
return (user_id, hydra_session.id) | python | def login(username, password, **kwargs):
"""
Login a user, returning a dict containing their user_id and session_id
This does the DB login to check the credentials, and then creates a session
so that requests from apps do not need to perform a login
args:
username (string): The user's username
password(string): The user's password (unencrypted)
returns:
A dict containing the user_id and session_id
raises:
HydraError if the login fails
"""
user_id = util.hdb.login_user(username, password)
hydra_session = session.Session({}, #This is normally a request object, but in this case is empty
validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),
type='file',
cookie_expires=True,
data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'),
file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth'))
hydra_session['user_id'] = user_id
hydra_session['username'] = username
hydra_session.save()
return (user_id, hydra_session.id) | [
"def",
"login",
"(",
"username",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"util",
".",
"hdb",
".",
"login_user",
"(",
"username",
",",
"password",
")",
"hydra_session",
"=",
"session",
".",
"Session",
"(",
"{",
"}",
",",
"#... | Login a user, returning a dict containing their user_id and session_id
This does the DB login to check the credentials, and then creates a session
so that requests from apps do not need to perform a login
args:
username (string): The user's username
password(string): The user's password (unencrypted)
returns:
A dict containing the user_id and session_id
raises:
HydraError if the login fails | [
"Login",
"a",
"user",
"returning",
"a",
"dict",
"containing",
"their",
"user_id",
"and",
"session_id"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/service.py#L25-L54 | train | 46,047 |
hydraplatform/hydra-base | hydra_base/lib/service.py | logout | def logout(session_id, **kwargs):
"""
Logout a user, removing their cookie if it exists and returning 'OK'
args:
session_id (string): The session ID to identify the cookie to remove
returns:
'OK'
raises:
HydraError if the logout fails
"""
hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty
validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),
type='file',
cookie_expires=True,
data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'),
file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth'))
hydra_session = hydra_session_object.get_by_id(session_id)
if hydra_session is not None:
hydra_session.delete()
hydra_session.save()
return 'OK' | python | def logout(session_id, **kwargs):
"""
Logout a user, removing their cookie if it exists and returning 'OK'
args:
session_id (string): The session ID to identify the cookie to remove
returns:
'OK'
raises:
HydraError if the logout fails
"""
hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty
validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),
type='file',
cookie_expires=True,
data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'),
file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth'))
hydra_session = hydra_session_object.get_by_id(session_id)
if hydra_session is not None:
hydra_session.delete()
hydra_session.save()
return 'OK' | [
"def",
"logout",
"(",
"session_id",
",",
"*",
"*",
"kwargs",
")",
":",
"hydra_session_object",
"=",
"session",
".",
"SessionObject",
"(",
"{",
"}",
",",
"#This is normally a request object, but in this case is empty",
"validate_key",
"=",
"config",
".",
"get",
"(",
... | Logout a user, removing their cookie if it exists and returning 'OK'
args:
session_id (string): The session ID to identify the cookie to remove
returns:
'OK'
raises:
HydraError if the logout fails | [
"Logout",
"a",
"user",
"removing",
"their",
"cookie",
"if",
"it",
"exists",
"and",
"returning",
"OK"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/service.py#L56-L82 | train | 46,048 |
hydraplatform/hydra-base | hydra_base/lib/service.py | get_session_user | def get_session_user(session_id, **kwargs):
"""
Given a session ID, get the user ID that it is associated with
args:
session_id (string): The user's ID to identify the cookie to remove
returns:
user_id (string) or None if the session does not exist
"""
hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty
validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),
type='file',
cookie_expires=True,
data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'),
file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth'))
hydra_session = hydra_session_object.get_by_id(session_id)
if hydra_session is not None:
return hydra_session['user_id']
return None | python | def get_session_user(session_id, **kwargs):
"""
Given a session ID, get the user ID that it is associated with
args:
session_id (string): The user's ID to identify the cookie to remove
returns:
user_id (string) or None if the session does not exist
"""
hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty
validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),
type='file',
cookie_expires=True,
data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'),
file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth'))
hydra_session = hydra_session_object.get_by_id(session_id)
if hydra_session is not None:
return hydra_session['user_id']
return None | [
"def",
"get_session_user",
"(",
"session_id",
",",
"*",
"*",
"kwargs",
")",
":",
"hydra_session_object",
"=",
"session",
".",
"SessionObject",
"(",
"{",
"}",
",",
"#This is normally a request object, but in this case is empty",
"validate_key",
"=",
"config",
".",
"get... | Given a session ID, get the user ID that it is associated with
args:
session_id (string): The user's ID to identify the cookie to remove
returns:
user_id (string) or None if the session does not exist | [
"Given",
"a",
"session",
"ID",
"get",
"the",
"user",
"ID",
"that",
"it",
"is",
"associated",
"with"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/service.py#L84-L107 | train | 46,049 |
hydraplatform/hydra-base | hydra_base/util/dataset_util.py | array_dim | def array_dim(arr):
"""Return the size of a multidimansional array.
"""
dim = []
while True:
try:
dim.append(len(arr))
arr = arr[0]
except TypeError:
return dim | python | def array_dim(arr):
"""Return the size of a multidimansional array.
"""
dim = []
while True:
try:
dim.append(len(arr))
arr = arr[0]
except TypeError:
return dim | [
"def",
"array_dim",
"(",
"arr",
")",
":",
"dim",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"dim",
".",
"append",
"(",
"len",
"(",
"arr",
")",
")",
"arr",
"=",
"arr",
"[",
"0",
"]",
"except",
"TypeError",
":",
"return",
"dim"
] | Return the size of a multidimansional array. | [
"Return",
"the",
"size",
"of",
"a",
"multidimansional",
"array",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/dataset_util.py#L33-L42 | train | 46,050 |
hydraplatform/hydra-base | hydra_base/util/dataset_util.py | arr_to_vector | def arr_to_vector(arr):
"""Reshape a multidimensional array to a vector.
"""
dim = array_dim(arr)
tmp_arr = []
for n in range(len(dim) - 1):
for inner in arr:
for i in inner:
tmp_arr.append(i)
arr = tmp_arr
tmp_arr = []
return arr | python | def arr_to_vector(arr):
"""Reshape a multidimensional array to a vector.
"""
dim = array_dim(arr)
tmp_arr = []
for n in range(len(dim) - 1):
for inner in arr:
for i in inner:
tmp_arr.append(i)
arr = tmp_arr
tmp_arr = []
return arr | [
"def",
"arr_to_vector",
"(",
"arr",
")",
":",
"dim",
"=",
"array_dim",
"(",
"arr",
")",
"tmp_arr",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"dim",
")",
"-",
"1",
")",
":",
"for",
"inner",
"in",
"arr",
":",
"for",
"i",
"in",
... | Reshape a multidimensional array to a vector. | [
"Reshape",
"a",
"multidimensional",
"array",
"to",
"a",
"vector",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/dataset_util.py#L61-L72 | train | 46,051 |
hydraplatform/hydra-base | hydra_base/util/dataset_util.py | vector_to_arr | def vector_to_arr(vec, dim):
"""Reshape a vector to a multidimensional array with dimensions 'dim'.
"""
if len(dim) <= 1:
return vec
array = vec
while len(dim) > 1:
i = 0
outer_array = []
for m in range(reduce(mul, dim[0:-1])):
inner_array = []
for n in range(dim[-1]):
inner_array.append(array[i])
i += 1
outer_array.append(inner_array)
array = outer_array
dim = dim[0:-1]
return array | python | def vector_to_arr(vec, dim):
"""Reshape a vector to a multidimensional array with dimensions 'dim'.
"""
if len(dim) <= 1:
return vec
array = vec
while len(dim) > 1:
i = 0
outer_array = []
for m in range(reduce(mul, dim[0:-1])):
inner_array = []
for n in range(dim[-1]):
inner_array.append(array[i])
i += 1
outer_array.append(inner_array)
array = outer_array
dim = dim[0:-1]
return array | [
"def",
"vector_to_arr",
"(",
"vec",
",",
"dim",
")",
":",
"if",
"len",
"(",
"dim",
")",
"<=",
"1",
":",
"return",
"vec",
"array",
"=",
"vec",
"while",
"len",
"(",
"dim",
")",
">",
"1",
":",
"i",
"=",
"0",
"outer_array",
"=",
"[",
"]",
"for",
... | Reshape a vector to a multidimensional array with dimensions 'dim'. | [
"Reshape",
"a",
"vector",
"to",
"a",
"multidimensional",
"array",
"with",
"dimensions",
"dim",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/dataset_util.py#L75-L93 | train | 46,052 |
hydraplatform/hydra-base | hydra_base/util/dataset_util.py | validate_ENUM | def validate_ENUM(in_value, restriction):
"""
Test to ensure that the given value is contained in the provided list.
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the ENUM
"""
value = _get_val(in_value)
if type(value) is list:
for subval in value:
if type(subval) is tuple:
subval = subval[1]
validate_ENUM(subval, restriction)
else:
if value not in restriction:
raise ValidationError("ENUM : %s"%(restriction)) | python | def validate_ENUM(in_value, restriction):
"""
Test to ensure that the given value is contained in the provided list.
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the ENUM
"""
value = _get_val(in_value)
if type(value) is list:
for subval in value:
if type(subval) is tuple:
subval = subval[1]
validate_ENUM(subval, restriction)
else:
if value not in restriction:
raise ValidationError("ENUM : %s"%(restriction)) | [
"def",
"validate_ENUM",
"(",
"in_value",
",",
"restriction",
")",
":",
"value",
"=",
"_get_val",
"(",
"in_value",
")",
"if",
"type",
"(",
"value",
")",
"is",
"list",
":",
"for",
"subval",
"in",
"value",
":",
"if",
"type",
"(",
"subval",
")",
"is",
"t... | Test to ensure that the given value is contained in the provided list.
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the ENUM | [
"Test",
"to",
"ensure",
"that",
"the",
"given",
"value",
"is",
"contained",
"in",
"the",
"provided",
"list",
".",
"the",
"value",
"parameter",
"must",
"be",
"either",
"a",
"single",
"value",
"or",
"a",
"1",
"-",
"dimensional",
"list",
".",
"All",
"the",
... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/dataset_util.py#L214-L228 | train | 46,053 |
hydraplatform/hydra-base | hydra_base/util/dataset_util.py | validate_NUMPLACES | def validate_NUMPLACES(in_value, restriction):
"""
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the condition
"""
#Sometimes restriction values can accidentally be put in the template <item>100</items>,
#Making them a list, not a number. Rather than blowing up, just get value 1 from the list.
if type(restriction) is list:
restriction = restriction[0]
value = _get_val(in_value)
if type(value) is list:
for subval in value:
if type(subval) is tuple:
subval = subval[1]
validate_NUMPLACES(subval, restriction)
else:
restriction = int(restriction) # Just in case..
dec_val = Decimal(str(value))
num_places = dec_val.as_tuple().exponent * -1 #exponent returns a negative num
if restriction != num_places:
raise ValidationError("NUMPLACES: %s"%(restriction)) | python | def validate_NUMPLACES(in_value, restriction):
"""
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the condition
"""
#Sometimes restriction values can accidentally be put in the template <item>100</items>,
#Making them a list, not a number. Rather than blowing up, just get value 1 from the list.
if type(restriction) is list:
restriction = restriction[0]
value = _get_val(in_value)
if type(value) is list:
for subval in value:
if type(subval) is tuple:
subval = subval[1]
validate_NUMPLACES(subval, restriction)
else:
restriction = int(restriction) # Just in case..
dec_val = Decimal(str(value))
num_places = dec_val.as_tuple().exponent * -1 #exponent returns a negative num
if restriction != num_places:
raise ValidationError("NUMPLACES: %s"%(restriction)) | [
"def",
"validate_NUMPLACES",
"(",
"in_value",
",",
"restriction",
")",
":",
"#Sometimes restriction values can accidentally be put in the template <item>100</items>,",
"#Making them a list, not a number. Rather than blowing up, just get value 1 from the list.",
"if",
"type",
"(",
"restrict... | the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the condition | [
"the",
"value",
"parameter",
"must",
"be",
"either",
"a",
"single",
"value",
"or",
"a",
"1",
"-",
"dimensional",
"list",
".",
"All",
"the",
"values",
"in",
"this",
"list",
"must",
"satisfy",
"the",
"condition"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/dataset_util.py#L275-L296 | train | 46,054 |
hydraplatform/hydra-base | hydra_base/util/dataset_util.py | validate_EQUALTIMESTEPS | def validate_EQUALTIMESTEPS(value, restriction):
"""
Ensure that the timesteps in a timeseries are equal. If a restriction
is provided, they must be equal to the specified restriction.
Value is a pandas dataframe.
"""
if len(value) == 0:
return
if type(value) == pd.DataFrame:
if str(value.index[0]).startswith('9999'):
tmp_val = value.to_json().replace('9999', '1900')
value = pd.read_json(tmp_val)
#If the timeseries is not datetime-based, check for a consistent timestep
if type(value.index) == pd.Int64Index:
timesteps = list(value.index)
timestep = timesteps[1] - timesteps[0]
for i, t in enumerate(timesteps[1:]):
if timesteps[i] - timesteps[i-1] != timestep:
raise ValidationError("Timesteps not equal: %s"%(list(value.index)))
if not hasattr(value.index, 'inferred_freq'):
raise ValidationError("Timesteps not equal: %s"%(list(value.index),))
if restriction is None:
if value.index.inferred_freq is None:
raise ValidationError("Timesteps not equal: %s"%(list(value.index),))
else:
if value.index.inferred_freq != restriction:
raise ValidationError("Timesteps not equal: %s"%(list(value.index),)) | python | def validate_EQUALTIMESTEPS(value, restriction):
"""
Ensure that the timesteps in a timeseries are equal. If a restriction
is provided, they must be equal to the specified restriction.
Value is a pandas dataframe.
"""
if len(value) == 0:
return
if type(value) == pd.DataFrame:
if str(value.index[0]).startswith('9999'):
tmp_val = value.to_json().replace('9999', '1900')
value = pd.read_json(tmp_val)
#If the timeseries is not datetime-based, check for a consistent timestep
if type(value.index) == pd.Int64Index:
timesteps = list(value.index)
timestep = timesteps[1] - timesteps[0]
for i, t in enumerate(timesteps[1:]):
if timesteps[i] - timesteps[i-1] != timestep:
raise ValidationError("Timesteps not equal: %s"%(list(value.index)))
if not hasattr(value.index, 'inferred_freq'):
raise ValidationError("Timesteps not equal: %s"%(list(value.index),))
if restriction is None:
if value.index.inferred_freq is None:
raise ValidationError("Timesteps not equal: %s"%(list(value.index),))
else:
if value.index.inferred_freq != restriction:
raise ValidationError("Timesteps not equal: %s"%(list(value.index),)) | [
"def",
"validate_EQUALTIMESTEPS",
"(",
"value",
",",
"restriction",
")",
":",
"if",
"len",
"(",
"value",
")",
"==",
"0",
":",
"return",
"if",
"type",
"(",
"value",
")",
"==",
"pd",
".",
"DataFrame",
":",
"if",
"str",
"(",
"value",
".",
"index",
"[",
... | Ensure that the timesteps in a timeseries are equal. If a restriction
is provided, they must be equal to the specified restriction.
Value is a pandas dataframe. | [
"Ensure",
"that",
"the",
"timesteps",
"in",
"a",
"timeseries",
"are",
"equal",
".",
"If",
"a",
"restriction",
"is",
"provided",
"they",
"must",
"be",
"equal",
"to",
"the",
"specified",
"restriction",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/dataset_util.py#L608-L641 | train | 46,055 |
hydraplatform/hydra-base | hydra_base/util/__init__.py | flatten_dict | def flatten_dict(value, target_depth=1, depth=None):
"""
Take a hashtable with multiple nested dicts and return a
dict where the keys are a concatenation of each sub-key.
The depth of the returned array is dictated by target_depth, defaulting to 1
ex: {'a' : {'b':1, 'c': 2}} ==> {'a_b': 1, 'a_c': 2}
Assumes a constant structure actoss all sub-dicts. i.e. there isn't
one sub-dict with values that are both numbers and sub-dicts.
"""
#failsafe in case someone specified null
if target_depth is None:
target_depth = 1
values = list(value.values())
if len(values) == 0:
return {}
else:
if depth is None:
depth = count_levels(value)
if isinstance(values[0], dict) and len(values[0]) > 0:
subval = list(values[0].values())[0]
if not isinstance(subval, dict) != 'object':
return value
if target_depth >= depth:
return value
flatval = {}
for k in value.keys():
subval = flatten_dict(value[k], target_depth, depth-1)
for k1 in subval.keys():
flatval[str(k)+"_"+str(k1)] = subval[k1];
return flatval
else:
return value | python | def flatten_dict(value, target_depth=1, depth=None):
"""
Take a hashtable with multiple nested dicts and return a
dict where the keys are a concatenation of each sub-key.
The depth of the returned array is dictated by target_depth, defaulting to 1
ex: {'a' : {'b':1, 'c': 2}} ==> {'a_b': 1, 'a_c': 2}
Assumes a constant structure actoss all sub-dicts. i.e. there isn't
one sub-dict with values that are both numbers and sub-dicts.
"""
#failsafe in case someone specified null
if target_depth is None:
target_depth = 1
values = list(value.values())
if len(values) == 0:
return {}
else:
if depth is None:
depth = count_levels(value)
if isinstance(values[0], dict) and len(values[0]) > 0:
subval = list(values[0].values())[0]
if not isinstance(subval, dict) != 'object':
return value
if target_depth >= depth:
return value
flatval = {}
for k in value.keys():
subval = flatten_dict(value[k], target_depth, depth-1)
for k1 in subval.keys():
flatval[str(k)+"_"+str(k1)] = subval[k1];
return flatval
else:
return value | [
"def",
"flatten_dict",
"(",
"value",
",",
"target_depth",
"=",
"1",
",",
"depth",
"=",
"None",
")",
":",
"#failsafe in case someone specified null",
"if",
"target_depth",
"is",
"None",
":",
"target_depth",
"=",
"1",
"values",
"=",
"list",
"(",
"value",
".",
... | Take a hashtable with multiple nested dicts and return a
dict where the keys are a concatenation of each sub-key.
The depth of the returned array is dictated by target_depth, defaulting to 1
ex: {'a' : {'b':1, 'c': 2}} ==> {'a_b': 1, 'a_c': 2}
Assumes a constant structure actoss all sub-dicts. i.e. there isn't
one sub-dict with values that are both numbers and sub-dicts. | [
"Take",
"a",
"hashtable",
"with",
"multiple",
"nested",
"dicts",
"and",
"return",
"a",
"dict",
"where",
"the",
"keys",
"are",
"a",
"concatenation",
"of",
"each",
"sub",
"-",
"key",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/__init__.py#L55-L94 | train | 46,056 |
hydraplatform/hydra-base | hydra_base/util/__init__.py | to_named_tuple | def to_named_tuple(keys, values):
"""
Convert a sqlalchemy object into a named tuple
"""
values = [dbobject.__dict__[key] for key in dbobject.keys()]
tuple_object = namedtuple('DBObject', dbobject.keys())
tuple_instance = tuple_object._make(values)
return tuple_instance | python | def to_named_tuple(keys, values):
"""
Convert a sqlalchemy object into a named tuple
"""
values = [dbobject.__dict__[key] for key in dbobject.keys()]
tuple_object = namedtuple('DBObject', dbobject.keys())
tuple_instance = tuple_object._make(values)
return tuple_instance | [
"def",
"to_named_tuple",
"(",
"keys",
",",
"values",
")",
":",
"values",
"=",
"[",
"dbobject",
".",
"__dict__",
"[",
"key",
"]",
"for",
"key",
"in",
"dbobject",
".",
"keys",
"(",
")",
"]",
"tuple_object",
"=",
"namedtuple",
"(",
"'DBObject'",
",",
"dbo... | Convert a sqlalchemy object into a named tuple | [
"Convert",
"a",
"sqlalchemy",
"object",
"into",
"a",
"named",
"tuple"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/__init__.py#L96-L107 | train | 46,057 |
hydraplatform/hydra-base | hydra_base/util/__init__.py | get_val | def get_val(dataset, timestamp=None):
"""
Turn the string value of a dataset into an appropriate
value, be it a decimal value, array or time series.
If a timestamp is passed to this function,
return the values appropriate to the requested times.
If the timestamp is *before* the start of the timeseries data, return None
If the timestamp is *after* the end of the timeseries data, return the last
value.
The raw flag indicates whether timeseries should be returned raw -- exactly
as they are in the DB (a timeseries being a list of timeseries data objects,
for example) or as a single python dictionary
"""
if dataset.type == 'array':
#TODO: design a mechansim to retrieve this data if it's stored externally
return json.loads(dataset.value)
elif dataset.type == 'descriptor':
return str(dataset.value)
elif dataset.type == 'scalar':
return Decimal(str(dataset.value))
elif dataset.type == 'timeseries':
#TODO: design a mechansim to retrieve this data if it's stored externally
val = dataset.value
seasonal_year = config.get('DEFAULT','seasonal_year', '1678')
seasonal_key = config.get('DEFAULT', 'seasonal_key', '9999')
val = dataset.value.replace(seasonal_key, seasonal_year)
timeseries = pd.read_json(val, convert_axes=True)
if timestamp is None:
return timeseries
else:
try:
idx = timeseries.index
#Seasonal timeseries are stored in the year
#1678 (the lowest year pandas allows for valid times).
#Therefore if the timeseries is seasonal,
#the request must be a seasonal request, not a
#standard request
if type(idx) == pd.DatetimeIndex:
if set(idx.year) == set([int(seasonal_year)]):
if isinstance(timestamp, list):
seasonal_timestamp = []
for t in timestamp:
t_1900 = t.replace(year=int(seasonal_year))
seasonal_timestamp.append(t_1900)
timestamp = seasonal_timestamp
else:
timestamp = [timestamp.replace(year=int(seasonal_year))]
pandas_ts = timeseries.reindex(timestamp, method='ffill')
#If there are no values at all, just return None
if len(pandas_ts.dropna()) == 0:
return None
#Replace all numpy NAN values with None
pandas_ts = pandas_ts.where(pandas_ts.notnull(), None)
val_is_array = False
if len(pandas_ts.columns) > 1:
val_is_array = True
if val_is_array:
if type(timestamp) is list and len(timestamp) == 1:
ret_val = pandas_ts.loc[timestamp[0]].values.tolist()
else:
ret_val = pandas_ts.loc[timestamp].values.tolist()
else:
col_name = pandas_ts.loc[timestamp].columns[0]
if type(timestamp) is list and len(timestamp) == 1:
ret_val = pandas_ts.loc[timestamp[0]].loc[col_name]
else:
ret_val = pandas_ts.loc[timestamp][col_name].values.tolist()
return ret_val
except Exception as e:
log.critical("Unable to retrive data. Check timestamps.")
log.critical(e) | python | def get_val(dataset, timestamp=None):
"""
Turn the string value of a dataset into an appropriate
value, be it a decimal value, array or time series.
If a timestamp is passed to this function,
return the values appropriate to the requested times.
If the timestamp is *before* the start of the timeseries data, return None
If the timestamp is *after* the end of the timeseries data, return the last
value.
The raw flag indicates whether timeseries should be returned raw -- exactly
as they are in the DB (a timeseries being a list of timeseries data objects,
for example) or as a single python dictionary
"""
if dataset.type == 'array':
#TODO: design a mechansim to retrieve this data if it's stored externally
return json.loads(dataset.value)
elif dataset.type == 'descriptor':
return str(dataset.value)
elif dataset.type == 'scalar':
return Decimal(str(dataset.value))
elif dataset.type == 'timeseries':
#TODO: design a mechansim to retrieve this data if it's stored externally
val = dataset.value
seasonal_year = config.get('DEFAULT','seasonal_year', '1678')
seasonal_key = config.get('DEFAULT', 'seasonal_key', '9999')
val = dataset.value.replace(seasonal_key, seasonal_year)
timeseries = pd.read_json(val, convert_axes=True)
if timestamp is None:
return timeseries
else:
try:
idx = timeseries.index
#Seasonal timeseries are stored in the year
#1678 (the lowest year pandas allows for valid times).
#Therefore if the timeseries is seasonal,
#the request must be a seasonal request, not a
#standard request
if type(idx) == pd.DatetimeIndex:
if set(idx.year) == set([int(seasonal_year)]):
if isinstance(timestamp, list):
seasonal_timestamp = []
for t in timestamp:
t_1900 = t.replace(year=int(seasonal_year))
seasonal_timestamp.append(t_1900)
timestamp = seasonal_timestamp
else:
timestamp = [timestamp.replace(year=int(seasonal_year))]
pandas_ts = timeseries.reindex(timestamp, method='ffill')
#If there are no values at all, just return None
if len(pandas_ts.dropna()) == 0:
return None
#Replace all numpy NAN values with None
pandas_ts = pandas_ts.where(pandas_ts.notnull(), None)
val_is_array = False
if len(pandas_ts.columns) > 1:
val_is_array = True
if val_is_array:
if type(timestamp) is list and len(timestamp) == 1:
ret_val = pandas_ts.loc[timestamp[0]].values.tolist()
else:
ret_val = pandas_ts.loc[timestamp].values.tolist()
else:
col_name = pandas_ts.loc[timestamp].columns[0]
if type(timestamp) is list and len(timestamp) == 1:
ret_val = pandas_ts.loc[timestamp[0]].loc[col_name]
else:
ret_val = pandas_ts.loc[timestamp][col_name].values.tolist()
return ret_val
except Exception as e:
log.critical("Unable to retrive data. Check timestamps.")
log.critical(e) | [
"def",
"get_val",
"(",
"dataset",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"dataset",
".",
"type",
"==",
"'array'",
":",
"#TODO: design a mechansim to retrieve this data if it's stored externally",
"return",
"json",
".",
"loads",
"(",
"dataset",
".",
"value",
... | Turn the string value of a dataset into an appropriate
value, be it a decimal value, array or time series.
If a timestamp is passed to this function,
return the values appropriate to the requested times.
If the timestamp is *before* the start of the timeseries data, return None
If the timestamp is *after* the end of the timeseries data, return the last
value.
The raw flag indicates whether timeseries should be returned raw -- exactly
as they are in the DB (a timeseries being a list of timeseries data objects,
for example) or as a single python dictionary | [
"Turn",
"the",
"string",
"value",
"of",
"a",
"dataset",
"into",
"an",
"appropriate",
"value",
"be",
"it",
"a",
"decimal",
"value",
"array",
"or",
"time",
"series",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/__init__.py#L132-L218 | train | 46,058 |
hydraplatform/hydra-base | hydra_base/util/__init__.py | get_layout_as_string | def get_layout_as_string(layout):
"""
Take a dict or string and return a string.
The dict will be json dumped.
The string will json parsed to check for json validity. In order to deal
with strings which have been json encoded multiple times, keep json decoding
until a dict is retrieved or until a non-json structure is identified.
"""
if isinstance(layout, dict):
return json.dumps(layout)
if(isinstance(layout, six.string_types)):
try:
return get_layout_as_string(json.loads(layout))
except:
return layout | python | def get_layout_as_string(layout):
"""
Take a dict or string and return a string.
The dict will be json dumped.
The string will json parsed to check for json validity. In order to deal
with strings which have been json encoded multiple times, keep json decoding
until a dict is retrieved or until a non-json structure is identified.
"""
if isinstance(layout, dict):
return json.dumps(layout)
if(isinstance(layout, six.string_types)):
try:
return get_layout_as_string(json.loads(layout))
except:
return layout | [
"def",
"get_layout_as_string",
"(",
"layout",
")",
":",
"if",
"isinstance",
"(",
"layout",
",",
"dict",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"layout",
")",
"if",
"(",
"isinstance",
"(",
"layout",
",",
"six",
".",
"string_types",
")",
")",
":"... | Take a dict or string and return a string.
The dict will be json dumped.
The string will json parsed to check for json validity. In order to deal
with strings which have been json encoded multiple times, keep json decoding
until a dict is retrieved or until a non-json structure is identified. | [
"Take",
"a",
"dict",
"or",
"string",
"and",
"return",
"a",
"string",
".",
"The",
"dict",
"will",
"be",
"json",
"dumped",
".",
"The",
"string",
"will",
"json",
"parsed",
"to",
"check",
"for",
"json",
"validity",
".",
"In",
"order",
"to",
"deal",
"with",... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/__init__.py#L220-L236 | train | 46,059 |
hydraplatform/hydra-base | hydra_base/util/__init__.py | get_layout_as_dict | def get_layout_as_dict(layout):
"""
Take a dict or string and return a dict if the data is json-encoded.
The string will json parsed to check for json validity. In order to deal
with strings which have been json encoded multiple times, keep json decoding
until a dict is retrieved or until a non-json structure is identified.
"""
if isinstance(layout, dict):
return layout
if(isinstance(layout, six.string_types)):
try:
return get_layout_as_dict(json.loads(layout))
except:
return layout | python | def get_layout_as_dict(layout):
"""
Take a dict or string and return a dict if the data is json-encoded.
The string will json parsed to check for json validity. In order to deal
with strings which have been json encoded multiple times, keep json decoding
until a dict is retrieved or until a non-json structure is identified.
"""
if isinstance(layout, dict):
return layout
if(isinstance(layout, six.string_types)):
try:
return get_layout_as_dict(json.loads(layout))
except:
return layout | [
"def",
"get_layout_as_dict",
"(",
"layout",
")",
":",
"if",
"isinstance",
"(",
"layout",
",",
"dict",
")",
":",
"return",
"layout",
"if",
"(",
"isinstance",
"(",
"layout",
",",
"six",
".",
"string_types",
")",
")",
":",
"try",
":",
"return",
"get_layout_... | Take a dict or string and return a dict if the data is json-encoded.
The string will json parsed to check for json validity. In order to deal
with strings which have been json encoded multiple times, keep json decoding
until a dict is retrieved or until a non-json structure is identified. | [
"Take",
"a",
"dict",
"or",
"string",
"and",
"return",
"a",
"dict",
"if",
"the",
"data",
"is",
"json",
"-",
"encoded",
".",
"The",
"string",
"will",
"json",
"parsed",
"to",
"check",
"for",
"json",
"validity",
".",
"In",
"order",
"to",
"deal",
"with",
... | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/__init__.py#L238-L253 | train | 46,060 |
hydraplatform/hydra-base | hydra_base/lib/users.py | get_username | def get_username(uid,**kwargs):
"""
Return the username of a given user_id
"""
rs = db.DBSession.query(User.username).filter(User.id==uid).one()
if rs is None:
raise ResourceNotFoundError("User with ID %s not found"%uid)
return rs.username | python | def get_username(uid,**kwargs):
"""
Return the username of a given user_id
"""
rs = db.DBSession.query(User.username).filter(User.id==uid).one()
if rs is None:
raise ResourceNotFoundError("User with ID %s not found"%uid)
return rs.username | [
"def",
"get_username",
"(",
"uid",
",",
"*",
"*",
"kwargs",
")",
":",
"rs",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"User",
".",
"username",
")",
".",
"filter",
"(",
"User",
".",
"id",
"==",
"uid",
")",
".",
"one",
"(",
")",
"if",
"rs",... | Return the username of a given user_id | [
"Return",
"the",
"username",
"of",
"a",
"given",
"user_id"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L64-L73 | train | 46,061 |
hydraplatform/hydra-base | hydra_base/lib/users.py | get_usernames_like | def get_usernames_like(username,**kwargs):
"""
Return a list of usernames like the given string.
"""
checkname = "%%%s%%"%username
rs = db.DBSession.query(User.username).filter(User.username.like(checkname)).all()
return [r.username for r in rs] | python | def get_usernames_like(username,**kwargs):
"""
Return a list of usernames like the given string.
"""
checkname = "%%%s%%"%username
rs = db.DBSession.query(User.username).filter(User.username.like(checkname)).all()
return [r.username for r in rs] | [
"def",
"get_usernames_like",
"(",
"username",
",",
"*",
"*",
"kwargs",
")",
":",
"checkname",
"=",
"\"%%%s%%\"",
"%",
"username",
"rs",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"User",
".",
"username",
")",
".",
"filter",
"(",
"User",
".",
"user... | Return a list of usernames like the given string. | [
"Return",
"a",
"list",
"of",
"usernames",
"like",
"the",
"given",
"string",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L75-L81 | train | 46,062 |
hydraplatform/hydra-base | hydra_base/lib/users.py | update_user_display_name | def update_user_display_name(user,**kwargs):
"""
Update a user's display name
"""
#check_perm(kwargs.get('user_id'), 'edit_user')
try:
user_i = db.DBSession.query(User).filter(User.id==user.id).one()
user_i.display_name = user.display_name
return user_i
except NoResultFound:
raise ResourceNotFoundError("User (id=%s) not found"%(user.id)) | python | def update_user_display_name(user,**kwargs):
"""
Update a user's display name
"""
#check_perm(kwargs.get('user_id'), 'edit_user')
try:
user_i = db.DBSession.query(User).filter(User.id==user.id).one()
user_i.display_name = user.display_name
return user_i
except NoResultFound:
raise ResourceNotFoundError("User (id=%s) not found"%(user.id)) | [
"def",
"update_user_display_name",
"(",
"user",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_user')",
"try",
":",
"user_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"User",
")",
".",
"filter",
"(",
"User",
".",
"id",
"=... | Update a user's display name | [
"Update",
"a",
"user",
"s",
"display",
"name"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L108-L118 | train | 46,063 |
hydraplatform/hydra-base | hydra_base/lib/users.py | update_user_password | def update_user_password(new_pwd_user_id, new_password,**kwargs):
"""
Update a user's password
"""
#check_perm(kwargs.get('user_id'), 'edit_user')
try:
user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one()
user_i.password = bcrypt.hashpw(str(new_password).encode('utf-8'), bcrypt.gensalt())
return user_i
except NoResultFound:
raise ResourceNotFoundError("User (id=%s) not found"%(new_pwd_user_id)) | python | def update_user_password(new_pwd_user_id, new_password,**kwargs):
"""
Update a user's password
"""
#check_perm(kwargs.get('user_id'), 'edit_user')
try:
user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one()
user_i.password = bcrypt.hashpw(str(new_password).encode('utf-8'), bcrypt.gensalt())
return user_i
except NoResultFound:
raise ResourceNotFoundError("User (id=%s) not found"%(new_pwd_user_id)) | [
"def",
"update_user_password",
"(",
"new_pwd_user_id",
",",
"new_password",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_user')",
"try",
":",
"user_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"User",
")",
".",
"filter",
"(... | Update a user's password | [
"Update",
"a",
"user",
"s",
"password"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L120-L130 | train | 46,064 |
hydraplatform/hydra-base | hydra_base/lib/users.py | get_user | def get_user(uid, **kwargs):
"""
Get a user by ID
"""
user_id=kwargs.get('user_id')
if uid is None:
uid = user_id
user_i = _get_user(uid)
return user_i | python | def get_user(uid, **kwargs):
"""
Get a user by ID
"""
user_id=kwargs.get('user_id')
if uid is None:
uid = user_id
user_i = _get_user(uid)
return user_i | [
"def",
"get_user",
"(",
"uid",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"if",
"uid",
"is",
"None",
":",
"uid",
"=",
"user_id",
"user_i",
"=",
"_get_user",
"(",
"uid",
")",
"return",
"user_i"
] | Get a user by ID | [
"Get",
"a",
"user",
"by",
"ID"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L132-L140 | train | 46,065 |
hydraplatform/hydra-base | hydra_base/lib/users.py | add_role | def add_role(role,**kwargs):
"""
Add a new role
"""
#check_perm(kwargs.get('user_id'), 'add_role')
role_i = Role(name=role.name, code=role.code)
db.DBSession.add(role_i)
db.DBSession.flush()
return role_i | python | def add_role(role,**kwargs):
"""
Add a new role
"""
#check_perm(kwargs.get('user_id'), 'add_role')
role_i = Role(name=role.name, code=role.code)
db.DBSession.add(role_i)
db.DBSession.flush()
return role_i | [
"def",
"add_role",
"(",
"role",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'add_role')",
"role_i",
"=",
"Role",
"(",
"name",
"=",
"role",
".",
"name",
",",
"code",
"=",
"role",
".",
"code",
")",
"db",
".",
"DBSession",
".",
"a... | Add a new role | [
"Add",
"a",
"new",
"role"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L178-L187 | train | 46,066 |
hydraplatform/hydra-base | hydra_base/lib/users.py | add_perm | def add_perm(perm,**kwargs):
"""
Add a permission
"""
#check_perm(kwargs.get('user_id'), 'add_perm')
perm_i = Perm(name=perm.name, code=perm.code)
db.DBSession.add(perm_i)
db.DBSession.flush()
return perm_i | python | def add_perm(perm,**kwargs):
"""
Add a permission
"""
#check_perm(kwargs.get('user_id'), 'add_perm')
perm_i = Perm(name=perm.name, code=perm.code)
db.DBSession.add(perm_i)
db.DBSession.flush()
return perm_i | [
"def",
"add_perm",
"(",
"perm",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'add_perm')",
"perm_i",
"=",
"Perm",
"(",
"name",
"=",
"perm",
".",
"name",
",",
"code",
"=",
"perm",
".",
"code",
")",
"db",
".",
"DBSession",
".",
"a... | Add a permission | [
"Add",
"a",
"permission"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L202-L211 | train | 46,067 |
hydraplatform/hydra-base | hydra_base/lib/users.py | delete_perm | def delete_perm(perm_id,**kwargs):
"""
Delete a permission
"""
#check_perm(kwargs.get('user_id'), 'edit_perm')
try:
perm_i = db.DBSession.query(Perm).filter(Perm.id==perm_id).one()
db.DBSession.delete(perm_i)
except InvalidRequestError:
raise ResourceNotFoundError("Permission (id=%s) does not exist"%(perm_id))
return 'OK' | python | def delete_perm(perm_id,**kwargs):
"""
Delete a permission
"""
#check_perm(kwargs.get('user_id'), 'edit_perm')
try:
perm_i = db.DBSession.query(Perm).filter(Perm.id==perm_id).one()
db.DBSession.delete(perm_i)
except InvalidRequestError:
raise ResourceNotFoundError("Permission (id=%s) does not exist"%(perm_id))
return 'OK' | [
"def",
"delete_perm",
"(",
"perm_id",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_perm')",
"try",
":",
"perm_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Perm",
")",
".",
"filter",
"(",
"Perm",
".",
"id",
"==",
"per... | Delete a permission | [
"Delete",
"a",
"permission"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L213-L225 | train | 46,068 |
hydraplatform/hydra-base | hydra_base/lib/users.py | set_user_role | def set_user_role(new_user_id, role_id, **kwargs):
"""
Apply `role_id` to `new_user_id`
Note this function returns the `Role` instance associated with `role_id`
"""
#check_perm(kwargs.get('user_id'), 'edit_role')
try:
_get_user(new_user_id)
role_i = _get_role(role_id)
roleuser_i = RoleUser(user_id=new_user_id, role_id=role_id)
role_i.roleusers.append(roleuser_i)
db.DBSession.flush()
except Exception as e: # Will occur if the foreign keys do not exist
log.exception(e)
raise ResourceNotFoundError("User or Role does not exist")
return role_i | python | def set_user_role(new_user_id, role_id, **kwargs):
"""
Apply `role_id` to `new_user_id`
Note this function returns the `Role` instance associated with `role_id`
"""
#check_perm(kwargs.get('user_id'), 'edit_role')
try:
_get_user(new_user_id)
role_i = _get_role(role_id)
roleuser_i = RoleUser(user_id=new_user_id, role_id=role_id)
role_i.roleusers.append(roleuser_i)
db.DBSession.flush()
except Exception as e: # Will occur if the foreign keys do not exist
log.exception(e)
raise ResourceNotFoundError("User or Role does not exist")
return role_i | [
"def",
"set_user_role",
"(",
"new_user_id",
",",
"role_id",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_role')",
"try",
":",
"_get_user",
"(",
"new_user_id",
")",
"role_i",
"=",
"_get_role",
"(",
"role_id",
")",
"roleuser_i",
"=",
... | Apply `role_id` to `new_user_id`
Note this function returns the `Role` instance associated with `role_id` | [
"Apply",
"role_id",
"to",
"new_user_id"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L228-L245 | train | 46,069 |
hydraplatform/hydra-base | hydra_base/lib/users.py | delete_user_role | def delete_user_role(deleted_user_id, role_id,**kwargs):
"""
Remove a user from a role
"""
#check_perm(kwargs.get('user_id'), 'edit_role')
try:
_get_user(deleted_user_id)
_get_role(role_id)
roleuser_i = db.DBSession.query(RoleUser).filter(RoleUser.user_id==deleted_user_id, RoleUser.role_id==role_id).one()
db.DBSession.delete(roleuser_i)
except NoResultFound:
raise ResourceNotFoundError("User Role does not exist")
return 'OK' | python | def delete_user_role(deleted_user_id, role_id,**kwargs):
"""
Remove a user from a role
"""
#check_perm(kwargs.get('user_id'), 'edit_role')
try:
_get_user(deleted_user_id)
_get_role(role_id)
roleuser_i = db.DBSession.query(RoleUser).filter(RoleUser.user_id==deleted_user_id, RoleUser.role_id==role_id).one()
db.DBSession.delete(roleuser_i)
except NoResultFound:
raise ResourceNotFoundError("User Role does not exist")
return 'OK' | [
"def",
"delete_user_role",
"(",
"deleted_user_id",
",",
"role_id",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_role')",
"try",
":",
"_get_user",
"(",
"deleted_user_id",
")",
"_get_role",
"(",
"role_id",
")",
"roleuser_i",
"=",
"db",
... | Remove a user from a role | [
"Remove",
"a",
"user",
"from",
"a",
"role"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L247-L260 | train | 46,070 |
hydraplatform/hydra-base | hydra_base/lib/users.py | set_role_perm | def set_role_perm(role_id, perm_id,**kwargs):
"""
Insert a permission into a role
"""
#check_perm(kwargs.get('user_id'), 'edit_perm')
_get_perm(perm_id)
role_i = _get_role(role_id)
roleperm_i = RolePerm(role_id=role_id, perm_id=perm_id)
role_i.roleperms.append(roleperm_i)
db.DBSession.flush()
return role_i | python | def set_role_perm(role_id, perm_id,**kwargs):
"""
Insert a permission into a role
"""
#check_perm(kwargs.get('user_id'), 'edit_perm')
_get_perm(perm_id)
role_i = _get_role(role_id)
roleperm_i = RolePerm(role_id=role_id, perm_id=perm_id)
role_i.roleperms.append(roleperm_i)
db.DBSession.flush()
return role_i | [
"def",
"set_role_perm",
"(",
"role_id",
",",
"perm_id",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_perm')",
"_get_perm",
"(",
"perm_id",
")",
"role_i",
"=",
"_get_role",
"(",
"role_id",
")",
"roleperm_i",
"=",
"RolePerm",
"(",
"... | Insert a permission into a role | [
"Insert",
"a",
"permission",
"into",
"a",
"role"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L262-L276 | train | 46,071 |
hydraplatform/hydra-base | hydra_base/lib/users.py | delete_role_perm | def delete_role_perm(role_id, perm_id,**kwargs):
"""
Remove a permission from a role
"""
#check_perm(kwargs.get('user_id'), 'edit_perm')
_get_perm(perm_id)
_get_role(role_id)
try:
roleperm_i = db.DBSession.query(RolePerm).filter(RolePerm.role_id==role_id, RolePerm.perm_id==perm_id).one()
db.DBSession.delete(roleperm_i)
except NoResultFound:
raise ResourceNotFoundError("Role Perm does not exist")
return 'OK' | python | def delete_role_perm(role_id, perm_id,**kwargs):
"""
Remove a permission from a role
"""
#check_perm(kwargs.get('user_id'), 'edit_perm')
_get_perm(perm_id)
_get_role(role_id)
try:
roleperm_i = db.DBSession.query(RolePerm).filter(RolePerm.role_id==role_id, RolePerm.perm_id==perm_id).one()
db.DBSession.delete(roleperm_i)
except NoResultFound:
raise ResourceNotFoundError("Role Perm does not exist")
return 'OK' | [
"def",
"delete_role_perm",
"(",
"role_id",
",",
"perm_id",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_perm')",
"_get_perm",
"(",
"perm_id",
")",
"_get_role",
"(",
"role_id",
")",
"try",
":",
"roleperm_i",
"=",
"db",
".",
"DBSess... | Remove a permission from a role | [
"Remove",
"a",
"permission",
"from",
"a",
"role"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L278-L292 | train | 46,072 |
hydraplatform/hydra-base | hydra_base/lib/users.py | update_role | def update_role(role,**kwargs):
"""
Update the role.
Used to add permissions and users to a role.
"""
#check_perm(kwargs.get('user_id'), 'edit_role')
try:
role_i = db.DBSession.query(Role).filter(Role.id==role.id).one()
role_i.name = role.name
role_i.code = role.code
except NoResultFound:
raise ResourceNotFoundError("Role (role_id=%s) does not exist"%(role.id))
for perm in role.permissions:
_get_perm(perm.id)
roleperm_i = RolePerm(role_id=role.id,
perm_id=perm.id
)
db.DBSession.add(roleperm_i)
for user in role.users:
_get_user(user.id)
roleuser_i = RoleUser(user_id=user.id,
perm_id=perm.id
)
db.DBSession.add(roleuser_i)
db.DBSession.flush()
return role_i | python | def update_role(role,**kwargs):
"""
Update the role.
Used to add permissions and users to a role.
"""
#check_perm(kwargs.get('user_id'), 'edit_role')
try:
role_i = db.DBSession.query(Role).filter(Role.id==role.id).one()
role_i.name = role.name
role_i.code = role.code
except NoResultFound:
raise ResourceNotFoundError("Role (role_id=%s) does not exist"%(role.id))
for perm in role.permissions:
_get_perm(perm.id)
roleperm_i = RolePerm(role_id=role.id,
perm_id=perm.id
)
db.DBSession.add(roleperm_i)
for user in role.users:
_get_user(user.id)
roleuser_i = RoleUser(user_id=user.id,
perm_id=perm.id
)
db.DBSession.add(roleuser_i)
db.DBSession.flush()
return role_i | [
"def",
"update_role",
"(",
"role",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_role')",
"try",
":",
"role_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Role",
")",
".",
"filter",
"(",
"Role",
".",
"id",
"==",
"role",... | Update the role.
Used to add permissions and users to a role. | [
"Update",
"the",
"role",
".",
"Used",
"to",
"add",
"permissions",
"and",
"users",
"to",
"a",
"role",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L294-L324 | train | 46,073 |
hydraplatform/hydra-base | hydra_base/lib/users.py | get_all_users | def get_all_users(**kwargs):
"""
Get the username & ID of all users.
Use the the filter if it has been provided
The filter has to be a list of values
"""
users_qry = db.DBSession.query(User)
filter_type = kwargs.get('filter_type')
filter_value = kwargs.get('filter_value')
if filter_type is not None:
# Filtering the search of users
if filter_type == "id":
if isinstance(filter_value, str):
# Trying to read a csv string
log.info("[HB.users] Getting user by Filter ID : %s", filter_value)
filter_value = eval(filter_value)
if type(filter_value) is int:
users_qry = users_qry.filter(User.id==filter_value)
else:
users_qry = users_qry.filter(User.id.in_(filter_value))
elif filter_type == "username":
if isinstance(filter_value, str):
# Trying to read a csv string
log.info("[HB.users] Getting user by Filter Username : %s", filter_value)
filter_value = filter_value.split(",")
for i, em in enumerate(filter_value):
log.info("[HB.users] >>> Getting user by single Username : %s", em)
filter_value[i] = em.strip()
if isinstance(filter_value, str):
users_qry = users_qry.filter(User.username==filter_value)
else:
users_qry = users_qry.filter(User.username.in_(filter_value))
else:
raise Exception("Filter type '{}' not allowed".format(filter_type))
else:
log.info('[HB.users] Getting All Users')
rs = users_qry.all()
return rs | python | def get_all_users(**kwargs):
"""
Get the username & ID of all users.
Use the the filter if it has been provided
The filter has to be a list of values
"""
users_qry = db.DBSession.query(User)
filter_type = kwargs.get('filter_type')
filter_value = kwargs.get('filter_value')
if filter_type is not None:
# Filtering the search of users
if filter_type == "id":
if isinstance(filter_value, str):
# Trying to read a csv string
log.info("[HB.users] Getting user by Filter ID : %s", filter_value)
filter_value = eval(filter_value)
if type(filter_value) is int:
users_qry = users_qry.filter(User.id==filter_value)
else:
users_qry = users_qry.filter(User.id.in_(filter_value))
elif filter_type == "username":
if isinstance(filter_value, str):
# Trying to read a csv string
log.info("[HB.users] Getting user by Filter Username : %s", filter_value)
filter_value = filter_value.split(",")
for i, em in enumerate(filter_value):
log.info("[HB.users] >>> Getting user by single Username : %s", em)
filter_value[i] = em.strip()
if isinstance(filter_value, str):
users_qry = users_qry.filter(User.username==filter_value)
else:
users_qry = users_qry.filter(User.username.in_(filter_value))
else:
raise Exception("Filter type '{}' not allowed".format(filter_type))
else:
log.info('[HB.users] Getting All Users')
rs = users_qry.all()
return rs | [
"def",
"get_all_users",
"(",
"*",
"*",
"kwargs",
")",
":",
"users_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"User",
")",
"filter_type",
"=",
"kwargs",
".",
"get",
"(",
"'filter_type'",
")",
"filter_value",
"=",
"kwargs",
".",
"get",
"(",
"'... | Get the username & ID of all users.
Use the the filter if it has been provided
The filter has to be a list of values | [
"Get",
"the",
"username",
"&",
"ID",
"of",
"all",
"users",
".",
"Use",
"the",
"the",
"filter",
"if",
"it",
"has",
"been",
"provided",
"The",
"filter",
"has",
"to",
"be",
"a",
"list",
"of",
"values"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L327-L369 | train | 46,074 |
hydraplatform/hydra-base | hydra_base/lib/users.py | get_role | def get_role(role_id,**kwargs):
"""
Get a role by its ID.
"""
try:
role = db.DBSession.query(Role).filter(Role.id==role_id).one()
return role
except NoResultFound:
raise HydraError("Role not found (role_id={})".format(role_id)) | python | def get_role(role_id,**kwargs):
"""
Get a role by its ID.
"""
try:
role = db.DBSession.query(Role).filter(Role.id==role_id).one()
return role
except NoResultFound:
raise HydraError("Role not found (role_id={})".format(role_id)) | [
"def",
"get_role",
"(",
"role_id",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"role",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Role",
")",
".",
"filter",
"(",
"Role",
".",
"id",
"==",
"role_id",
")",
".",
"one",
"(",
")",
"return",
... | Get a role by its ID. | [
"Get",
"a",
"role",
"by",
"its",
"ID",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L385-L393 | train | 46,075 |
hydraplatform/hydra-base | hydra_base/lib/users.py | get_role_by_code | def get_role_by_code(role_code,**kwargs):
"""
Get a role by its code
"""
try:
role = db.DBSession.query(Role).filter(Role.code==role_code).one()
return role
except NoResultFound:
raise ResourceNotFoundError("Role not found (role_code={})".format(role_code)) | python | def get_role_by_code(role_code,**kwargs):
"""
Get a role by its code
"""
try:
role = db.DBSession.query(Role).filter(Role.code==role_code).one()
return role
except NoResultFound:
raise ResourceNotFoundError("Role not found (role_code={})".format(role_code)) | [
"def",
"get_role_by_code",
"(",
"role_code",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"role",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Role",
")",
".",
"filter",
"(",
"Role",
".",
"code",
"==",
"role_code",
")",
".",
"one",
"(",
")",
... | Get a role by its code | [
"Get",
"a",
"role",
"by",
"its",
"code"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L425-L433 | train | 46,076 |
hydraplatform/hydra-base | hydra_base/lib/users.py | get_perm | def get_perm(perm_id,**kwargs):
"""
Get all permissions
"""
try:
perm = db.DBSession.query(Perm).filter(Perm.id==perm_id).one()
return perm
except NoResultFound:
raise ResourceNotFoundError("Permission not found (perm_id={})".format(perm_id)) | python | def get_perm(perm_id,**kwargs):
"""
Get all permissions
"""
try:
perm = db.DBSession.query(Perm).filter(Perm.id==perm_id).one()
return perm
except NoResultFound:
raise ResourceNotFoundError("Permission not found (perm_id={})".format(perm_id)) | [
"def",
"get_perm",
"(",
"perm_id",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"perm",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Perm",
")",
".",
"filter",
"(",
"Perm",
".",
"id",
"==",
"perm_id",
")",
".",
"one",
"(",
")",
"return",
... | Get all permissions | [
"Get",
"all",
"permissions"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L436-L445 | train | 46,077 |
hydraplatform/hydra-base | hydra_base/lib/users.py | get_perm_by_code | def get_perm_by_code(perm_code,**kwargs):
"""
Get a permission by its code
"""
try:
perm = db.DBSession.query(Perm).filter(Perm.code==perm_code).one()
return perm
except NoResultFound:
raise ResourceNotFoundError("Permission not found (perm_code={})".format(perm_code)) | python | def get_perm_by_code(perm_code,**kwargs):
"""
Get a permission by its code
"""
try:
perm = db.DBSession.query(Perm).filter(Perm.code==perm_code).one()
return perm
except NoResultFound:
raise ResourceNotFoundError("Permission not found (perm_code={})".format(perm_code)) | [
"def",
"get_perm_by_code",
"(",
"perm_code",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"perm",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Perm",
")",
".",
"filter",
"(",
"Perm",
".",
"code",
"==",
"perm_code",
")",
".",
"one",
"(",
")",
... | Get a permission by its code | [
"Get",
"a",
"permission",
"by",
"its",
"code"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L447-L456 | train | 46,078 |
hydraplatform/hydra-base | hydra_base/lib/HydraTypes/Types.py | Dataframe._create_dataframe | def _create_dataframe(cls, value):
"""
Builds a dataframe from the value
"""
try:
ordered_jo = json.loads(six.text_type(value), object_pairs_hook=collections.OrderedDict)
#Pandas does not maintain the order of dicts, so we must break the dict
#up and put it into the dataframe manually to maintain the order.
cols = list(ordered_jo.keys())
if len(cols) == 0:
raise ValueError("Dataframe has no columns")
#Assume all sub-dicts have the same set of keys
if isinstance(ordered_jo[cols[0]], list):
index = range(len(ordered_jo[cols[0]]))
else:
index = list(ordered_jo[cols[0]].keys())
data = []
for c in cols:
if isinstance(ordered_jo[c], list):
data.append(ordered_jo[c])
else:
data.append(list(ordered_jo[c].values()))
# This goes in 'sideways' (cols=index, index=cols), so it needs to be transposed after to keep
# the correct structure
# We also try to coerce the data to a regular numpy array first. If the shape is correct
# this is a much faster way of creating the DataFrame instance.
try:
np_data = np.array(data)
except ValueError:
np_data = None
if np_data is not None and np_data.shape == (len(cols), len(index)):
df = pd.DataFrame(np_data, columns=index, index=cols).transpose()
else:
# TODO should these heterogenous structure be supported?
# See https://github.com/hydraplatform/hydra-base/issues/72
df = pd.DataFrame(data, columns=index, index=cols).transpose()
except ValueError as e:
""" Raised on scalar types used as pd.DataFrame values
in absence of index arg
"""
raise HydraError(str(e))
except AssertionError as e:
log.warning("An error occurred creating the new data frame: %s. Defaulting to a simple read_json"%(e))
df = pd.read_json(value).fillna(0)
return df | python | def _create_dataframe(cls, value):
"""
Builds a dataframe from the value
"""
try:
ordered_jo = json.loads(six.text_type(value), object_pairs_hook=collections.OrderedDict)
#Pandas does not maintain the order of dicts, so we must break the dict
#up and put it into the dataframe manually to maintain the order.
cols = list(ordered_jo.keys())
if len(cols) == 0:
raise ValueError("Dataframe has no columns")
#Assume all sub-dicts have the same set of keys
if isinstance(ordered_jo[cols[0]], list):
index = range(len(ordered_jo[cols[0]]))
else:
index = list(ordered_jo[cols[0]].keys())
data = []
for c in cols:
if isinstance(ordered_jo[c], list):
data.append(ordered_jo[c])
else:
data.append(list(ordered_jo[c].values()))
# This goes in 'sideways' (cols=index, index=cols), so it needs to be transposed after to keep
# the correct structure
# We also try to coerce the data to a regular numpy array first. If the shape is correct
# this is a much faster way of creating the DataFrame instance.
try:
np_data = np.array(data)
except ValueError:
np_data = None
if np_data is not None and np_data.shape == (len(cols), len(index)):
df = pd.DataFrame(np_data, columns=index, index=cols).transpose()
else:
# TODO should these heterogenous structure be supported?
# See https://github.com/hydraplatform/hydra-base/issues/72
df = pd.DataFrame(data, columns=index, index=cols).transpose()
except ValueError as e:
""" Raised on scalar types used as pd.DataFrame values
in absence of index arg
"""
raise HydraError(str(e))
except AssertionError as e:
log.warning("An error occurred creating the new data frame: %s. Defaulting to a simple read_json"%(e))
df = pd.read_json(value).fillna(0)
return df | [
"def",
"_create_dataframe",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"ordered_jo",
"=",
"json",
".",
"loads",
"(",
"six",
".",
"text_type",
"(",
"value",
")",
",",
"object_pairs_hook",
"=",
"collections",
".",
"OrderedDict",
")",
"#Pandas does not mai... | Builds a dataframe from the value | [
"Builds",
"a",
"dataframe",
"from",
"the",
"value"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/HydraTypes/Types.py#L193-L248 | train | 46,079 |
hydraplatform/hydra-base | hydra_base/lib/objects.py | Dataset.parse_value | def parse_value(self):
"""
Turn the value of an incoming dataset into a hydra-friendly value.
"""
try:
if self.value is None:
log.warning("Cannot parse dataset. No value specified.")
return None
# attr_data.value is a dictionary but the keys have namespaces which must be stripped
data = six.text_type(self.value)
if data.upper().strip() in ("NULL", ""):
return "NULL"
data = data[0:100]
log.info("[Dataset.parse_value] Parsing %s (%s)", data, type(data))
return HydraObjectFactory.valueFromDataset(self.type, self.value, self.get_metadata_as_dict())
except Exception as e:
log.exception(e)
raise HydraError("Error parsing value %s: %s"%(self.value, e)) | python | def parse_value(self):
"""
Turn the value of an incoming dataset into a hydra-friendly value.
"""
try:
if self.value is None:
log.warning("Cannot parse dataset. No value specified.")
return None
# attr_data.value is a dictionary but the keys have namespaces which must be stripped
data = six.text_type(self.value)
if data.upper().strip() in ("NULL", ""):
return "NULL"
data = data[0:100]
log.info("[Dataset.parse_value] Parsing %s (%s)", data, type(data))
return HydraObjectFactory.valueFromDataset(self.type, self.value, self.get_metadata_as_dict())
except Exception as e:
log.exception(e)
raise HydraError("Error parsing value %s: %s"%(self.value, e)) | [
"def",
"parse_value",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"value",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"Cannot parse dataset. No value specified.\"",
")",
"return",
"None",
"# attr_data.value is a dictionary but the keys have namespaces wh... | Turn the value of an incoming dataset into a hydra-friendly value. | [
"Turn",
"the",
"value",
"of",
"an",
"incoming",
"dataset",
"into",
"a",
"hydra",
"-",
"friendly",
"value",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/objects.py#L214-L236 | train | 46,080 |
hydraplatform/hydra-base | hydra_base/lib/objects.py | Dataset.get_metadata_as_dict | def get_metadata_as_dict(self, user_id=None, source=None):
"""
Convert a metadata json string into a dictionary.
Args:
user_id (int): Optional: Insert user_id into the metadata if specified
source (string): Optional: Insert source (the name of the app typically) into the metadata if necessary.
Returns:
dict: THe metadata as a python dictionary
"""
if self.metadata is None or self.metadata == "":
return {}
metadata_dict = self.metadata if isinstance(self.metadata, dict) else json.loads(self.metadata)
# These should be set on all datasets by default, but we don't enforce this rigidly
metadata_keys = [m.lower() for m in metadata_dict]
if user_id is not None and 'user_id' not in metadata_keys:
metadata_dict['user_id'] = six.text_type(user_id)
if source is not None and 'source' not in metadata_keys:
metadata_dict['source'] = six.text_type(source)
return { k : six.text_type(v) for k, v in metadata_dict.items() } | python | def get_metadata_as_dict(self, user_id=None, source=None):
"""
Convert a metadata json string into a dictionary.
Args:
user_id (int): Optional: Insert user_id into the metadata if specified
source (string): Optional: Insert source (the name of the app typically) into the metadata if necessary.
Returns:
dict: THe metadata as a python dictionary
"""
if self.metadata is None or self.metadata == "":
return {}
metadata_dict = self.metadata if isinstance(self.metadata, dict) else json.loads(self.metadata)
# These should be set on all datasets by default, but we don't enforce this rigidly
metadata_keys = [m.lower() for m in metadata_dict]
if user_id is not None and 'user_id' not in metadata_keys:
metadata_dict['user_id'] = six.text_type(user_id)
if source is not None and 'source' not in metadata_keys:
metadata_dict['source'] = six.text_type(source)
return { k : six.text_type(v) for k, v in metadata_dict.items() } | [
"def",
"get_metadata_as_dict",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"if",
"self",
".",
"metadata",
"is",
"None",
"or",
"self",
".",
"metadata",
"==",
"\"\"",
":",
"return",
"{",
"}",
"metadata_dict",
"=",
"sel... | Convert a metadata json string into a dictionary.
Args:
user_id (int): Optional: Insert user_id into the metadata if specified
source (string): Optional: Insert source (the name of the app typically) into the metadata if necessary.
Returns:
dict: THe metadata as a python dictionary | [
"Convert",
"a",
"metadata",
"json",
"string",
"into",
"a",
"dictionary",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/objects.py#L239-L264 | train | 46,081 |
hydraplatform/hydra-base | hydra_base/lib/groups.py | delete_resourcegroup | def delete_resourcegroup(group_id,**kwargs):
"""
Add a new group to a scenario.
"""
group_i = _get_group(group_id)
#This should cascaded to delete all the group items.
db.DBSession.delete(group_i)
db.DBSession.flush()
return 'OK' | python | def delete_resourcegroup(group_id,**kwargs):
"""
Add a new group to a scenario.
"""
group_i = _get_group(group_id)
#This should cascaded to delete all the group items.
db.DBSession.delete(group_i)
db.DBSession.flush()
return 'OK' | [
"def",
"delete_resourcegroup",
"(",
"group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"group_i",
"=",
"_get_group",
"(",
"group_id",
")",
"#This should cascaded to delete all the group items.",
"db",
".",
"DBSession",
".",
"delete",
"(",
"group_i",
")",
"db",
".",
... | Add a new group to a scenario. | [
"Add",
"a",
"new",
"group",
"to",
"a",
"scenario",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/groups.py#L56-L65 | train | 46,082 |
hydraplatform/hydra-base | hydra_base/db/model.py | _is_admin | def _is_admin(user_id):
"""
Is the specified user an admin
"""
user = get_session().query(User).filter(User.id==user_id).one()
if user.is_admin():
return True
else:
return False | python | def _is_admin(user_id):
"""
Is the specified user an admin
"""
user = get_session().query(User).filter(User.id==user_id).one()
if user.is_admin():
return True
else:
return False | [
"def",
"_is_admin",
"(",
"user_id",
")",
":",
"user",
"=",
"get_session",
"(",
")",
".",
"query",
"(",
"User",
")",
".",
"filter",
"(",
"User",
".",
"id",
"==",
"user_id",
")",
".",
"one",
"(",
")",
"if",
"user",
".",
"is_admin",
"(",
")",
":",
... | Is the specified user an admin | [
"Is",
"the",
"specified",
"user",
"an",
"admin"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L80-L89 | train | 46,083 |
hydraplatform/hydra-base | hydra_base/db/model.py | Dataset.set_metadata | def set_metadata(self, metadata_dict):
"""
Set the metadata on a dataset
**metadata_dict**: A dictionary of metadata key-vals.
Transforms this dict into an array of metadata objects for
storage in the DB.
"""
if metadata_dict is None:
return
existing_metadata = []
for m in self.metadata:
existing_metadata.append(m.key)
if m.key in metadata_dict:
if m.value != metadata_dict[m.key]:
m.value = metadata_dict[m.key]
for k, v in metadata_dict.items():
if k not in existing_metadata:
m_i = Metadata(key=str(k),value=str(v))
self.metadata.append(m_i)
metadata_to_delete = set(existing_metadata).difference(set(metadata_dict.keys()))
for m in self.metadata:
if m.key in metadata_to_delete:
get_session().delete(m) | python | def set_metadata(self, metadata_dict):
"""
Set the metadata on a dataset
**metadata_dict**: A dictionary of metadata key-vals.
Transforms this dict into an array of metadata objects for
storage in the DB.
"""
if metadata_dict is None:
return
existing_metadata = []
for m in self.metadata:
existing_metadata.append(m.key)
if m.key in metadata_dict:
if m.value != metadata_dict[m.key]:
m.value = metadata_dict[m.key]
for k, v in metadata_dict.items():
if k not in existing_metadata:
m_i = Metadata(key=str(k),value=str(v))
self.metadata.append(m_i)
metadata_to_delete = set(existing_metadata).difference(set(metadata_dict.keys()))
for m in self.metadata:
if m.key in metadata_to_delete:
get_session().delete(m) | [
"def",
"set_metadata",
"(",
"self",
",",
"metadata_dict",
")",
":",
"if",
"metadata_dict",
"is",
"None",
":",
"return",
"existing_metadata",
"=",
"[",
"]",
"for",
"m",
"in",
"self",
".",
"metadata",
":",
"existing_metadata",
".",
"append",
"(",
"m",
".",
... | Set the metadata on a dataset
**metadata_dict**: A dictionary of metadata key-vals.
Transforms this dict into an array of metadata objects for
storage in the DB. | [
"Set",
"the",
"metadata",
"on",
"a",
"dataset"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L126-L153 | train | 46,084 |
hydraplatform/hydra-base | hydra_base/db/model.py | Dataset.check_user | def check_user(self, user_id):
"""
Check whether this user can read this dataset
"""
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 | python | def check_user(self, user_id):
"""
Check whether this user can read this dataset
"""
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",
")",
":",
"if",
"self",
".",
"hidden",
"==",
"'N'",
":",
"return",
"True",
"for",
"owner",
"in",
"self",
".",
"owners",
":",
"if",
"int",
"(",
"owner",
".",
"user_id",
")",
"==",
"int",
"(",
"user_i... | Check whether this user can read this dataset | [
"Check",
"whether",
"this",
"user",
"can",
"read",
"this",
"dataset"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L254-L266 | train | 46,085 |
hydraplatform/hydra-base | hydra_base/db/model.py | ResourceAttr.get_network | def get_network(self):
"""
Get the network that this resource attribute is in.
"""
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
elif ref_key == 'PROJECT':
return None | python | def get_network(self):
"""
Get the network that this resource attribute is in.
"""
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
elif ref_key == 'PROJECT':
return None | [
"def",
"get_network",
"(",
"self",
")",
":",
"ref_key",
"=",
"self",
".",
"ref_key",
"if",
"ref_key",
"==",
"'NETWORK'",
":",
"return",
"self",
".",
"network",
"elif",
"ref_key",
"==",
"'NODE'",
":",
"return",
"self",
".",
"node",
".",
"network",
"elif",... | Get the network that this resource attribute is in. | [
"Get",
"the",
"network",
"that",
"this",
"resource",
"attribute",
"is",
"in",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L560-L574 | train | 46,086 |
hydraplatform/hydra-base | hydra_base/db/model.py | ResourceAttr.check_read_permission | def check_read_permission(self, user_id, do_raise=True):
"""
Check whether this user can read this resource attribute
"""
return self.get_resource().check_read_permission(user_id, do_raise=do_raise) | python | def check_read_permission(self, user_id, do_raise=True):
"""
Check whether this user can read this resource attribute
"""
return self.get_resource().check_read_permission(user_id, do_raise=do_raise) | [
"def",
"check_read_permission",
"(",
"self",
",",
"user_id",
",",
"do_raise",
"=",
"True",
")",
":",
"return",
"self",
".",
"get_resource",
"(",
")",
".",
"check_read_permission",
"(",
"user_id",
",",
"do_raise",
"=",
"do_raise",
")"
] | Check whether this user can read this resource attribute | [
"Check",
"whether",
"this",
"user",
"can",
"read",
"this",
"resource",
"attribute"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L602-L606 | train | 46,087 |
hydraplatform/hydra-base | hydra_base/db/model.py | ResourceAttr.check_write_permission | def check_write_permission(self, user_id, do_raise=True):
"""
Check whether this user can write this node
"""
return self.get_resource().check_write_permission(user_id, do_raise=do_raise) | python | def check_write_permission(self, user_id, do_raise=True):
"""
Check whether this user can write this node
"""
return self.get_resource().check_write_permission(user_id, do_raise=do_raise) | [
"def",
"check_write_permission",
"(",
"self",
",",
"user_id",
",",
"do_raise",
"=",
"True",
")",
":",
"return",
"self",
".",
"get_resource",
"(",
")",
".",
"check_write_permission",
"(",
"user_id",
",",
"do_raise",
"=",
"do_raise",
")"
] | Check whether this user can write this node | [
"Check",
"whether",
"this",
"user",
"can",
"write",
"this",
"node"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L608-L612 | train | 46,088 |
hydraplatform/hydra-base | hydra_base/db/model.py | Network.add_link | 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.
"""
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 = desc
l.layout = json.dumps(layout) if layout is not None else None
l.node_a = node_1
l.node_b = node_2
get_session().add(l)
self.links.append(l)
return l | python | 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.
"""
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 = desc
l.layout = json.dumps(layout) if layout is not None else None
l.node_a = node_1
l.node_b = node_2
get_session().add(l)
self.links.append(l)
return l | [
"def",
"add_link",
"(",
"self",
",",
"name",
",",
"desc",
",",
"layout",
",",
"node_1",
",",
"node_2",
")",
":",
"existing_link",
"=",
"get_session",
"(",
")",
".",
"query",
"(",
"Link",
")",
".",
"filter",
"(",
"Link",
".",
"name",
"==",
"name",
"... | Add a link to a network. Links are what effectively
define the network topology, by associating two already
existing nodes. | [
"Add",
"a",
"link",
"to",
"a",
"network",
".",
"Links",
"are",
"what",
"effectively",
"define",
"the",
"network",
"topology",
"by",
"associating",
"two",
"already",
"existing",
"nodes",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L860-L882 | train | 46,089 |
hydraplatform/hydra-base | hydra_base/db/model.py | Network.add_node | def add_node(self, name, desc, layout, node_x, node_y):
"""
Add a node to a network.
"""
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.description = desc
node.layout = str(layout) if layout is not None else None
node.x = node_x
node.y = node_y
#Do not call save here because it is likely that we may want
#to bulk insert nodes, not one at a time.
get_session().add(node)
self.nodes.append(node)
return node | python | def add_node(self, name, desc, layout, node_x, node_y):
"""
Add a node to a network.
"""
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.description = desc
node.layout = str(layout) if layout is not None else None
node.x = node_x
node.y = node_y
#Do not call save here because it is likely that we may want
#to bulk insert nodes, not one at a time.
get_session().add(node)
self.nodes.append(node)
return node | [
"def",
"add_node",
"(",
"self",
",",
"name",
",",
"desc",
",",
"layout",
",",
"node_x",
",",
"node_y",
")",
":",
"existing_node",
"=",
"get_session",
"(",
")",
".",
"query",
"(",
"Node",
")",
".",
"filter",
"(",
"Node",
".",
"name",
"==",
"name",
"... | Add a node to a network. | [
"Add",
"a",
"node",
"to",
"a",
"network",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L885-L907 | train | 46,090 |
hydraplatform/hydra-base | hydra_base/db/model.py | Network.check_read_permission | def check_read_permission(self, user_id, do_raise=True):
"""
Check whether this user can read this network
"""
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_raise is True:
raise PermissionError("Permission denied. User %s does not have read"
" access on network %s" %
(user_id, self.id))
else:
return False
return True | python | def check_read_permission(self, user_id, do_raise=True):
"""
Check whether this user can read this network
"""
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_raise is True:
raise PermissionError("Permission denied. User %s does not have read"
" access on network %s" %
(user_id, self.id))
else:
return False
return True | [
"def",
"check_read_permission",
"(",
"self",
",",
"user_id",
",",
"do_raise",
"=",
"True",
")",
":",
"if",
"_is_admin",
"(",
"user_id",
")",
":",
"return",
"True",
"if",
"int",
"(",
"self",
".",
"created_by",
")",
"==",
"int",
"(",
"user_id",
")",
":",... | Check whether this user can read this network | [
"Check",
"whether",
"this",
"user",
"can",
"read",
"this",
"network"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L960-L982 | train | 46,091 |
hydraplatform/hydra-base | hydra_base/db/model.py | Network.check_share_permission | def check_share_permission(self, user_id):
"""
Check whether this user can write this project
"""
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:
raise PermissionError("Permission denied. User %s does not have share"
" access on network %s" %
(user_id, self.id)) | python | def check_share_permission(self, user_id):
"""
Check whether this user can write this project
"""
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:
raise PermissionError("Permission denied. User %s does not have share"
" access on network %s" %
(user_id, self.id)) | [
"def",
"check_share_permission",
"(",
"self",
",",
"user_id",
")",
":",
"if",
"_is_admin",
"(",
"user_id",
")",
":",
"return",
"if",
"int",
"(",
"self",
".",
"created_by",
")",
"==",
"int",
"(",
"user_id",
")",
":",
"return",
"for",
"owner",
"in",
"sel... | Check whether this user can write this project | [
"Check",
"whether",
"this",
"user",
"can",
"write",
"this",
"project"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1008-L1026 | train | 46,092 |
hydraplatform/hydra-base | hydra_base/db/model.py | Link.check_read_permission | def check_read_permission(self, user_id, do_raise=True):
"""
Check whether this user can read this link
"""
return self.network.check_read_permission(user_id, do_raise=do_raise) | python | def check_read_permission(self, user_id, do_raise=True):
"""
Check whether this user can read this link
"""
return self.network.check_read_permission(user_id, do_raise=do_raise) | [
"def",
"check_read_permission",
"(",
"self",
",",
"user_id",
",",
"do_raise",
"=",
"True",
")",
":",
"return",
"self",
".",
"network",
".",
"check_read_permission",
"(",
"user_id",
",",
"do_raise",
"=",
"do_raise",
")"
] | Check whether this user can read this link | [
"Check",
"whether",
"this",
"user",
"can",
"read",
"this",
"link"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1090-L1094 | train | 46,093 |
hydraplatform/hydra-base | hydra_base/db/model.py | Link.check_write_permission | def check_write_permission(self, user_id, do_raise=True):
"""
Check whether this user can write this link
"""
return self.network.check_write_permission(user_id, do_raise=do_raise) | python | def check_write_permission(self, user_id, do_raise=True):
"""
Check whether this user can write this link
"""
return self.network.check_write_permission(user_id, do_raise=do_raise) | [
"def",
"check_write_permission",
"(",
"self",
",",
"user_id",
",",
"do_raise",
"=",
"True",
")",
":",
"return",
"self",
".",
"network",
".",
"check_write_permission",
"(",
"user_id",
",",
"do_raise",
"=",
"do_raise",
")"
] | Check whether this user can write this link | [
"Check",
"whether",
"this",
"user",
"can",
"write",
"this",
"link"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1096-L1101 | train | 46,094 |
hydraplatform/hydra-base | hydra_base/db/model.py | ResourceGroup.get_items | def get_items(self, scenario_id):
"""
Get all the items in this group, in the given scenario
"""
items = get_session().query(ResourceGroupItem)\
.filter(ResourceGroupItem.group_id==self.id).\
filter(ResourceGroupItem.scenario_id==scenario_id).all()
return items | python | def get_items(self, scenario_id):
"""
Get all the items in this group, in the given scenario
"""
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",
")",
":",
"items",
"=",
"get_session",
"(",
")",
".",
"query",
"(",
"ResourceGroupItem",
")",
".",
"filter",
"(",
"ResourceGroupItem",
".",
"group_id",
"==",
"self",
".",
"id",
")",
".",
"filter",
"(",... | Get all the items in this group, in the given scenario | [
"Get",
"all",
"the",
"items",
"in",
"this",
"group",
"in",
"the",
"given",
"scenario"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1231-L1239 | train | 46,095 |
hydraplatform/hydra-base | hydra_base/db/model.py | Note.set_ref | def set_ref(self, ref_key, ref_id):
"""
Using a ref key and ref id set the
reference to the appropriate resource type.
"""
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':
self.scenario_id = ref_id
elif ref_key == 'PROJECT':
self.project_id = ref_id
else:
raise HydraError("Ref Key %s not recognised."%ref_key) | python | def set_ref(self, ref_key, ref_id):
"""
Using a ref key and ref id set the
reference to the appropriate resource type.
"""
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':
self.scenario_id = ref_id
elif ref_key == 'PROJECT':
self.project_id = ref_id
else:
raise HydraError("Ref Key %s not recognised."%ref_key) | [
"def",
"set_ref",
"(",
"self",
",",
"ref_key",
",",
"ref_id",
")",
":",
"if",
"ref_key",
"==",
"'NETWORK'",
":",
"self",
".",
"network_id",
"=",
"ref_id",
"elif",
"ref_key",
"==",
"'NODE'",
":",
"self",
".",
"node_id",
"=",
"ref_id",
"elif",
"ref_key",
... | Using a ref key and ref id set the
reference to the appropriate resource type. | [
"Using",
"a",
"ref",
"key",
"and",
"ref",
"id",
"set",
"the",
"reference",
"to",
"the",
"appropriate",
"resource",
"type",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1465-L1484 | train | 46,096 |
hydraplatform/hydra-base | hydra_base/db/model.py | User.roles | def roles(self):
"""Return a set with all roles granted to the user."""
roles = []
for ur in self.roleusers:
roles.append(ur.role)
return set(roles) | python | def roles(self):
"""Return a set with all roles granted to the user."""
roles = []
for ur in self.roleusers:
roles.append(ur.role)
return set(roles) | [
"def",
"roles",
"(",
"self",
")",
":",
"roles",
"=",
"[",
"]",
"for",
"ur",
"in",
"self",
".",
"roleusers",
":",
"roles",
".",
"append",
"(",
"ur",
".",
"role",
")",
"return",
"set",
"(",
"roles",
")"
] | Return a set with all roles granted to the user. | [
"Return",
"a",
"set",
"with",
"all",
"roles",
"granted",
"to",
"the",
"user",
"."
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1695-L1700 | train | 46,097 |
hydraplatform/hydra-base | hydra_base/db/model.py | User.is_admin | def is_admin(self):
"""
Check that the user has a role with the code 'admin'
"""
for ur in self.roleusers:
if ur.role.code == 'admin':
return True
return False | python | def is_admin(self):
"""
Check that the user has a role with the code 'admin'
"""
for ur in self.roleusers:
if ur.role.code == 'admin':
return True
return False | [
"def",
"is_admin",
"(",
"self",
")",
":",
"for",
"ur",
"in",
"self",
".",
"roleusers",
":",
"if",
"ur",
".",
"role",
".",
"code",
"==",
"'admin'",
":",
"return",
"True",
"return",
"False"
] | Check that the user has a role with the code 'admin' | [
"Check",
"that",
"the",
"user",
"has",
"a",
"role",
"with",
"the",
"code",
"admin"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1702-L1710 | train | 46,098 |
hydraplatform/hydra-base | hydra_base/lib/template.py | _check_dimension | 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
"""
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 (abbreviation=%s) has dimension_id %s(name=%s), but attribute has no dimension"%
(unit_id, units.get_unit(unit_id).abbreviation,
unit_dimension_id, units.get_dimension(unit_dimension_id, do_accept_dimension_id_none=True).name))
elif unit_id is not None and dimension_id is not None:
unit_dimension_id = units.get_dimension_by_unit_id(unit_id).id
if unit_dimension_id != dimension_id:
# Only error case
raise HydraError("Unit %s (abbreviation=%s) has dimension_id %s(name=%s), but attribute has dimension_id %s(name=%s)"%
(unit_id, units.get_unit(unit_id).abbreviation,
unit_dimension_id, units.get_dimension(unit_dimension_id, do_accept_dimension_id_none=True).name,
dimension_id, units.get_dimension(dimension_id, do_accept_dimension_id_none=True).name)) | python | 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
"""
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 (abbreviation=%s) has dimension_id %s(name=%s), but attribute has no dimension"%
(unit_id, units.get_unit(unit_id).abbreviation,
unit_dimension_id, units.get_dimension(unit_dimension_id, do_accept_dimension_id_none=True).name))
elif unit_id is not None and dimension_id is not None:
unit_dimension_id = units.get_dimension_by_unit_id(unit_id).id
if unit_dimension_id != dimension_id:
# Only error case
raise HydraError("Unit %s (abbreviation=%s) has dimension_id %s(name=%s), but attribute has dimension_id %s(name=%s)"%
(unit_id, units.get_unit(unit_id).abbreviation,
unit_dimension_id, units.get_dimension(unit_dimension_id, do_accept_dimension_id_none=True).name,
dimension_id, units.get_dimension(dimension_id, do_accept_dimension_id_none=True).name)) | [
"def",
"_check_dimension",
"(",
"typeattr",
",",
"unit_id",
"=",
"None",
")",
":",
"if",
"unit_id",
"is",
"None",
":",
"unit_id",
"=",
"typeattr",
".",
"unit_id",
"dimension_id",
"=",
"_get_attr",
"(",
"typeattr",
".",
"attr_id",
")",
".",
"dimension_id",
... | 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 | [
"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"
] | 9251ff7946505f7a272c87837390acd1c435bc6e | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L44-L68 | train | 46,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.