output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def clone_dataset(dataset_id,**kwargs):
"""
Get a single dataset, by ID
"""
user_id = int(kwargs.get('user_id'))
if dataset_id is None:
return None
dataset = db.DBSession.query(Dataset).filter(
Dataset.id==dataset_id).options(joinedload_all('metadata')).first()
if... | Can you write a function in Python 3 where it
gets a single dataset by ID. | As a python code expert, you are capable of creating scripts from specifications. |
def get_datasets(dataset_ids,**kwargs):
"""
Get a single dataset, by ID
"""
user_id = int(kwargs.get('user_id'))
datasets = []
if len(dataset_ids) == 0:
return []
try:
dataset_rs = db.DBSession.query(Dataset.id,
Dataset.type,
Dataset.unit_... | Write a Python 3 function for
getting a list of datasets by ID. | You are a Python code analyst, evaluating scripts for potential improvements. |
Search the datasets in the DB. | How would you explain what the following Python 3 function does
def search_datasets(dataset_id=None,
dataset_name=None,
collection_name=None,
data_type=None,
unit_id=None,
scenario_id=None,
metadata_key=None,
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Update an existing dataset. | Can you generate the documentation for the following Python 3 function
def update_dataset(dataset_id, name, data_type, val, unit_id, metadata={}, flush=True, **kwargs):
if dataset_id is None:
raise HydraError("Dataset must have an ID to be updated.")
user_id = kwargs.get('user_id')
dataset = db.D... | You are a Python code generator, capable of creating scripts from specifications. |
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 valu... | Create a Python 3 function for
adding a dataset to the database. | As a Python code analyst, you investigate and solve complex coding mysteries |
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
... | Can you implement a function in Python 3 that
inserts data into the DB. | As a python code expert, you are capable of creating scripts from specifications. |
Get all the metadata for a given list of datasets
| How would you explain what the following Python 3 function does
def _get_metadata(dataset_ids):
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("Quer... | As a Python code translator, you convert algorithms and pseudocode into 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 =qr... | How would you implement a function in Python 3 that
gets all the datasets in a list of dataset IDS. | As a python code expert, you are capable of creating scripts from specifications. |
Get a dataset collection by ID. | Can you generate a brief explanation for the following Python 3 code
def _get_collection(collection_id):
try:
collection = db.DBSession.query(DatasetCollection).filter(DatasetCollection.id==collection_id).one()
return collection
except NoResultFound:
raise ResourceNotFoundError("No datas... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a single dataset collection entry by collection ID and dataset ID | How would you explain what the following Python 3 function does
def _get_collection_item(collection_id, dataset_id):
collection_item = db.DBSession.query(DatasetCollectionItem).\
filter(DatasetCollectionItem.collection_id==collection_id,
DatasetCollectionItem.dataset_id==dataset_id).f... | As a python code expert, you are capable of creating scripts from specifications. |
Add a single dataset to a dataset collection. | Here you have a function in Python 3, explain what it does
def add_dataset_to_collection(dataset_id, collection_id, **kwargs):
collection_i = _get_collection(collection_id)
collection_item = _get_collection_item(collection_id, dataset_id)
if collection_item is not None:
raise HydraError("Dataset Col... | As a python code expert, you are capable of creating scripts from specifications. |
Remove a single dataset from a dataset collection. | Can you generate the documentation for the following Python 3 function
def remove_dataset_from_collection(dataset_id, collection_id, **kwargs):
collection_i = _get_collection(collection_id)
collection_item = _get_collection_item(collection_id, dataset_id)
if collection_item is None:
raise HydraError... | As a Python code analyst, you investigate and solve complex coding mysteries |
Check whether a dataset is contained inside a collection. | Make a summary of the following Python 3 code
def check_dataset_in_collection(dataset_id, collection_id, **kwargs):
_get_collection(collection_id)
collection_item = _get_collection_item(collection_id, dataset_id)
if collection_item is None:
return 'N'
else:
return 'Y' | As a python code expert, you are capable of creating scripts from specifications. |
def get_collections_like_name(collection_name,**kwargs):
"""
Get all the datasets from the collection with the specified name
"""
try:
collections = db.DBSession.query(DatasetCollection).filter(DatasetCollection.name.like("%%%s%%"%collection_name.lower())).all()
except NoResultFound:
... | Write a Python 3 function that can
get all the datasets from the collection with the specified name | You are a Python code generator, capable of creating scripts from specifications. |
def get_collection_datasets(collection_id,**kwargs):
"""
Get all the datasets from the collection with the specified name
"""
collection_datasets = db.DBSession.query(Dataset).filter(Dataset.id==DatasetCollectionItem.dataset_id,
DatasetCollectionItem.collectio... | Create a Python 3 function for
getting all the datasets from the collection with the specified name | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_val_at_time(dataset_id, timestamps,**kwargs):
"""
Given a timestamp (or list of timestamps) and some timeseries data,
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 times... | Write a Python 3 function for
giving a timestamp or list of timestamps return the values appropriate to the requested times. | As a Python code analyst, you investigate and solve complex coding mysteries |
Given a list of timestamps and a list of datasets return the values appropriate to the requested times. | Make a summary of the following Python 3 code
def get_multiple_vals_at_time(dataset_ids, timestamps,**kwargs):
datasets = _get_datasets(dataset_ids)
datetimes = []
for time in timestamps:
datetimes.append(get_datetime(time))
return_vals = {}
for dataset_i in datasets.values():
data ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function returns the values of a dataset between two specified times within a timeseries. | Given the following Python 3 function, write the documentation
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 = get_datetime(end_time)
times = [server_start_time]
next_tim... | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Implement a function in Python 3 to
delete a dataset from the DB. | You are a Python code generator, capable of creating scripts from specifications. |
Get all the notes for a resource identified by ref_key and ref_id. | Make a summary of the following Python 3 code
def get_notes(ref_key, ref_id, **kwargs):
notes = db.DBSession.query(Note).filter(Note.ref_key==ref_key)
if ref_key == 'NETWORK':
notes = notes.filter(Note.network_id == ref_id)
elif ref_key == 'NODE':
notes = notes.filter(Note.node_id == ref_id)... | You are a Python code generator, capable of creating scripts from specifications. |
Add a note to the
| How would you explain what the following Python 3 function does
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_i.value = note.value
note_i.created_by = kwargs.get('user_id')
db.DBSession.add(note_i)
db.DBSession.... | You are a Python code architect, reviewing and designing scalable and efficient code |
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)
... | Create a Python 3 function for
updating a note in the database | As a Python code analyst, you investigate and solve complex coding mysteries |
Remove a note from the DB permenantly
| Make a summary of the following Python 3 code
def purge_note(note_id, **kwargs):
note_i = _get_note(note_id)
db.DBSession.delete(note_i)
db.DBSession.flush() | As a python code expert, you are capable of creating scripts from specifications. |
Login a user and return a dict containing the user_id and session_id. | Can you generate a brief explanation for the following Python 3 code
def login(username, password, **kwargs):
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', 'VALI... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given a session ID get the user ID that it is associated with
| Make a summary of the following Python 3 code
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('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),
type='file',
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the size of a multidimansional array. | Given the following Python 3 function, write the documentation
def array_dim(arr):
dim = []
while True:
try:
dim.append(len(arr))
arr = arr[0]
except TypeError:
return dim | As a Python code analyst, you investigate and solve complex coding mysteries |
Check to ensure that the given array is symmetrical. | Can you generate a brief explanation for the following Python 3 code
def check_array_struct(array):
#If a list is transformed into a numpy array and the sub elements
#of this array are still lists, then numpy failed to fully convert
#the list, meaning it is not symmetrical.
try:
arr = np.array(... | As a python code expert, you are capable of creating scripts from specifications. |
Reshape a multidimensional array to a vector. | Can you generate the documentation for the following Python 3 function
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 inner:
tmp_arr.append(i)
arr = tmp_arr
tmp_arr = []
return arr | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_val(val, full=False):
"""
Get the value(s) of a dataset as a single value or as 1-d list of
values. In the special case of timeseries, when a check is for time-based
criteria, you can return the entire timeseries.
"""
try:
val = val.strip()
except:
pass
... | Can you create a Python 3 function that
gets the value of a dataset as a single value or as 1 - d list of all the values. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_restriction_as_dict(restriction_xml):
"""
turn:
::
<restrictions>
<restriction>
<type>MAXLEN</type>
<value>3</value>
</restriction>
<restriction>
<type>VALUERANGE</type>
... | Write a Python 3 script for
parsing the XML element of a resource restriction element and returns a dictionary of the types and values. | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Implement a Python 3 function for
testing to ensure that the given value is contained in the ENUM structure. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Can you create a Python 3 function that
validates the NUMPLACES parameter of the resource. | As a Python code composer, you craft elegant and concise scripts. |
Test to ensure that a value sits between a lower and upper bound. | Can you tell what is the following Python 3 function doing
def validate_VALUERANGE(in_value, restriction):
if len(restriction) != 2:
raise ValidationError("Template ERROR: Only two values can be specified in a date range.")
value = _get_val(in_value)
if type(value) is list:
for subval in val... | As a Python code analyst, you investigate and solve complex coding mysteries |
Test to ensure that the times in a timeseries fall between a lower and upper bound. | Make a summary of the following Python 3 code
def validate_DATERANGE(value, restriction):
if len(restriction) != 2:
raise ValidationError("Template ERROR: Only two values can be specified in a date range.")
if type(value) == pd.DataFrame:
dates = [get_datetime(v) for v in list(value.index)]
... | As a Python code composer, you craft elegant and concise scripts. |
def validate_MAXLEN(value, restriction):
"""
Test to ensure that a list has the prescribed length.
Parameters: A list and an integer, which defines the required length of
the list.
"""
#Sometimes restriction values can accidentally be put in the template <item>100</items>,
#Makin... | Can you create a Python 3 function that
tests to ensure that a list has the prescribed length. | As a Python code composer, you craft elegant and concise scripts. |
def validate_LESSTHAN(in_value, restriction):
"""
Test to ensure that a value is less than a prescribed value.
Parameter: Two values, which will be compared for the difference..
"""
#Sometimes restriction values can accidentally be put in the template <item>100</items>,
#Making them a li... | Implement a function in Python 3 to
test to ensure that a value is less than a prescribed value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def validate_LESSTHANEQ(value, restriction):
"""
Test to ensure that a value is less than or equal to a prescribed value.
Parameter: Two values, which will be compared for the difference..
"""
#Sometimes restriction values can accidentally be put in the template <item>100</items>,
#Makin... | Write a Python 3 function for
testing to ensure that a value is less than or equal to a prescribed value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def validate_SUMTO(in_value, restriction):
"""
Test to ensure the values of a list sum to a specified value:
Parameters: a list of numeric values and a target to which the values
in the list must sum
"""
#Sometimes restriction values can accidentally be put in the template <item>100<... | How would you code a function in Python 3 to
test to ensure that the values of a list sum to a specified value | You are a Python code generator, capable of creating scripts from specifications. |
Test to ensure the values in a list are increasing. | Can you generate a brief explanation for the following Python 3 code
def validate_INCREASING(in_value, restriction):
flat_list = _flatten_value(in_value)
previous = None
for a in flat_list:
if previous is None:
previous = a
continue
try:
if a < previous:... | You are a Python code analyst, evaluating scripts for potential improvements. |
Validate that the timesteps in a timeseries are equal to the specified restriction. | Here you have a function in Python 3, explain what it does
def validate_EQUALTIMESTEPS(value, restriction):
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.... | You are a Python code generator, capable of creating scripts from specifications. |
def _flatten_value(value):
"""
1: Turn a multi-dimensional array into a 1-dimensional array
2: Turn a timeseries of values into a single 1-dimensional array
"""
if type(value) == pd.DataFrame:
value = value.values.tolist()
if type(value) != list:
raise ValidationError("... | Implement a function in Python 3 to
flatten a value into a list of lists. | As a python code expert, you are capable of creating scripts from specifications. |
Count how many levels are in a dict | How would you explain what the following Python 3 function does
def count_levels(value):
if not isinstance(value, dict) or len(value) == 0:
return 0
elif len(value) == 0:
return 0 #An emptu dict has 0
else:
nextval = list(value.values())[0]
return 1 + count_levels(nextval) | As a Python code analyst, you investigate and solve complex coding mysteries |
Flatten a hashtable with multiple nested dicts and return a
Taxonomy dict where the keys are a concatenation of each sub - key. | Explain what the following Python 3 code does
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.values())
if len(values) == 0:
return {}
else:
if depth is None:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert a sqlalchemy object into a named tuple | Given the following Python 3 function, write the documentation
def to_named_tuple(keys, values):
values = [dbobject.__dict__[key] for key in dbobject.keys()]
tuple_object = namedtuple('DBObject', dbobject.keys())
tuple_instance = tuple_object._make(values)
return tuple_instance | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the value of a dataset in an appropriate language. | How would you explain what the following Python 3 function does
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)
elif dataset.type == 'descriptor':
return str(data... | You are a Python code architect, reviewing and designing scalable and efficient code |
Take a dict or string and return a string. | Can you generate a brief explanation for the following Python 3 code
def get_layout_as_string(layout):
if isinstance(layout, dict):
return json.dumps(layout)
if(isinstance(layout, six.string_types)):
try:
return get_layout_as_string(json.loads(layout))
except:
r... | As a Python code composer, you craft elegant and concise scripts. |
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 ... | Can you write a function in Python 3 where it
takes a dict or string and return a dict. | As a python code expert, you are capable of creating scripts from specifications. |
Get the username of a given user_id | Given the following Python 3 function, write the documentation
def get_username(uid,**kwargs):
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 | As a Python code composer, you craft elegant and concise scripts. |
Return a list of usernames like the given string. | Make a summary of the following Python 3 code
def get_usernames_like(username,**kwargs):
checkname = "%%%s%%"%username
rs = db.DBSession.query(User.username).filter(User.username.like(checkname)).all()
return [r.username for r in rs] | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_user(user, **kwargs):
"""
Add a user
"""
#check_perm(kwargs.get('user_id'), 'add_user')
u = User()
u.username = user.username
u.display_name = user.display_name
user_id = _get_user_id(u.username)
#If the user is already there, cannot add another with
#the same ... | Write a Python 3 script to
add a user to the user list | As a Python code translator, you convert algorithms and pseudocode into 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 NoResul... | How would you implement a function in Python 3 that
updates a user s display name | As a Python code composer, you craft elegant and concise scripts. |
Update a user s password | Can you generate the documentation for the following Python 3 function
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(User.id==new_pwd_user_id).one()
user_i.password = bcrypt.hashpw(s... | As a Python code translator, you convert algorithms and pseudocode into 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 | Create a Python 3 function for
getting a user by ID | As a python code expert, you are capable of creating scripts from specifications. |
def get_user_by_name(uname,**kwargs):
"""
Get a user by username
"""
try:
user_i = db.DBSession.query(User).filter(User.username==uname).one()
return user_i
except NoResultFound:
return None | Can you write a function in Python 3 where it
gets a user by username | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_user_by_id(uid,**kwargs):
"""
Get a user by username
"""
user_id = kwargs.get('user_id')
try:
user_i = _get_user(uid)
return user_i
except NoResultFound:
return None | Create a Python 3 function to
get a user by id | You are a Python code analyst, evaluating scripts for potential improvements. |
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 | Create a Python 3 function to
add a role to the hierarchy. | As a python code expert, you are capable of creating scripts from specifications. |
Add a permission to a node | Here you have a function in Python 3, explain what it does
def add_perm(perm,**kwargs):
#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 | You are a Python code architect, reviewing and designing scalable and efficient code |
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)
... | Can you write a function in Python 3 where it
applies role_id to new_user_id | You are a Python code analyst, evaluating scripts for potential improvements. |
Remove a user from a role | Make a summary of the following Python 3 code
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.DBSession.query(RoleUser).filter(RoleUser.user_id==deleted_user_id, Ro... | As a Python code analyst, you investigate and solve complex coding mysteries |
Insert a permission into a role | Can you generate the documentation for the following Python 3 function
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(role_id=role_id, perm_id=perm_id)
role_i.roleperms.append(rolepe... | As a python code expert, you are capable of creating scripts from specifications. |
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_... | How would you implement a function in Python 3 that
removes a permission from a role | As a Python code composer, you craft elegant and concise scripts. |
Update the role.
Used to add permissions and users to a role. | Here you have a function in Python 3, explain what it does
def update_role(role,**kwargs):
#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:
... | As a Python code composer, you craft elegant and concise scripts. |
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')
... | Implement a function in Python 3 to
get all users in the current language. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a role by its ID. | Here you have a function in Python 3, explain what it does
def get_role(role_id,**kwargs):
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)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_user_roles(uid,**kwargs):
"""
Get the roles for a user.
@param user_id
"""
try:
user_roles = db.DBSession.query(Role).filter(Role.id==RoleUser.role_id,
RoleUser.user_id==uid).all()
return user_roles
except NoResult... | Create a Python 3 function for
getting the roles for a user. | As a Python code composer, you craft elegant and concise scripts. |
def get_user_permissions(uid, **kwargs):
"""
Get the roles for a user.
@param user_id
"""
try:
_get_user(uid)
user_perms = db.DBSession.query(Perm).filter(Perm.id==RolePerm.perm_id,
RolePerm.role_id==Role.id,
... | Create a Python 3 function to
get the permissions for a user. | You are a Python code generator, capable of creating scripts from specifications. |
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)) | Can you implement a function in Python 3 that
gets a role by its code | You are a Python code architect, reviewing and designing scalable and efficient code |
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)) | Write a Python 3 function for
getting all permissions with the given ID. | You are a Python code generator, capable of creating scripts from specifications. |
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)) | Implement a function in Python 3 to
get a permission by its code | As a Python code translator, you convert algorithms and pseudocode into Python. |
Builds a dataframe from the value | How would you explain what the following Python 3 function does
def _create_dataframe(cls, 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 p... | You are a Python code generator, capable of creating scripts from specifications. |
Turn the value of an incoming dataset into a hydra - friendly value. | Make a summary of the following Python 3 code
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 which must be stripped
... | You are a Python code generator, capable of creating scripts from specifications. |
Convert a metadata json string into a dictionary. | Make a summary of the following Python 3 code
def get_metadata_as_dict(self, user_id=None, source=None):
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... | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_resourcegroup(group, network_id,**kwargs):
"""
Add a new group to a network.
"""
group_i = ResourceGroup()
group_i.name = group.name
group_i.description = group.description
group_i.status = group.status
group_i.network_id ... | Create a Python 3 function for
adding a new resource group to a network. | As a Python code composer, you craft elegant and concise scripts. |
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' | Can you write a function in Python 3 where it
deletes a group from the database. | As a python code expert, you are capable of creating scripts from specifications. |
Update the name description and status of a group in the network. | Here you have a function in Python 3, explain what it does
def update_resourcegroup(group,**kwargs):
group_i = _get_group(group.id)
group_i.name = group.name
group_i.description = group.description
group_i.status = group.status
db.DBSession.flush()
retu... | You are a Python code architect, reviewing and designing scalable and efficient code |
create a sqlite backup DB | Can you generate a brief explanation for the following Python 3 code
def create_sqlite_backup_db(audit_tables):
#we always want to create a whole new DB, so delete the old one first
#if it exists.
try:
Popen("rm %s"%(config.get('sqlite', 'backup_url')), shell=True)
logging.warn("Old sqlite b... | As a Python code analyst, you investigate and solve complex coding mysteries |
Is the specified user an admin? | Explain what the following Python 3 code does
def _is_admin(user_id):
user = get_session().query(User).filter(User.id==user_id).one()
if user.is_admin():
return True
else:
return False | You are a Python code architect, reviewing and designing scalable and efficient code |
Sets the metadata on a dataset | Make a summary of the following Python 3 code
def set_metadata(self, metadata_dict):
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 != metad... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 ... | Implement a function in Python 3 to
check whether this user can read this dataset | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the network that this resource attribute is in. | Explain what the following Python 3 code does
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 ref_key == 'LINK':
return self.link.network
elif ref_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Check whether this user can read this attribute | Here you have a function in Python 3, explain what it does
def check_read_permission(self, user_id, do_raise=True):
return self.get_resource().check_read_permission(user_id, do_raise=do_raise) | As a Python code analyst, you investigate and solve complex coding mysteries |
Check whether this user can write this node. | Given the following Python 3 function, write the documentation
def check_write_permission(self, user_id, do_raise=True):
return self.get_resource().check_write_permission(user_id, do_raise=do_raise) | As a Python code composer, you craft elegant and concise scripts. |
Add a link to a network. | Explain what the following Python 3 code does
def add_link(self, name, desc, layout, node_1, node_2):
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... | As a Python code composer, you craft elegant and concise scripts. |
Add a node to a network. | Here you have a function in Python 3, explain what it does
def add_node(self, name, desc, layout, node_x, node_y):
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 alread... | As a Python code composer, you craft elegant and concise scripts. |
def add_group(self, name, desc, status):
"""
Add a new group to a network.
"""
existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first()
if existing_group is not None:
raise HydraError("A resou... | Implement a function in Python 3 to
add a new resource group to a network. | As a Python code composer, you craft elegant and concise scripts. |
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 in... | How would you implement a function in Python 3 that
checks whether this user can read this network | You are a Python code generator, capable of creating scripts from specifications. |
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(use... | Write a Python 3 function for
checking whether this user can write this project | You are a Python code generator, capable of creating scripts from specifications. |
Check whether this user can read this link. | How would you explain what the following Python 3 function does
def check_read_permission(self, user_id, do_raise=True):
return self.network.check_read_permission(user_id, do_raise=do_raise) | You are a Python code analyst, evaluating scripts for potential improvements. |
Check whether this user can write this link. | Can you generate the documentation for the following Python 3 function
def check_write_permission(self, user_id, do_raise=True):
return self.network.check_write_permission(user_id, do_raise=do_raise) | You are a Python code analyst, evaluating scripts for potential improvements. |
Get all the items in this group in the given scenario | Can you generate the documentation for the following Python 3 function
def get_items(self, scenario_id):
items = get_session().query(ResourceGroupItem)\
.filter(ResourceGroupItem.group_id==self.id).\
filter(ResourceGroupItem.scenario_id==scenario_id).all()
return items | You are a Python code analyst, evaluating scripts for potential improvements. |
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 ... | Implement a Python 3 function for
setting the reference to the appropriate resource type. | As a Python code composer, you craft elegant and concise scripts. |
def get_ref_id(self):
"""
Return the ID of the resource to which this not is attached
"""
if self.ref_key == 'NETWORK':
return self.network_id
elif self.ref_key == 'NODE':
return self.node_id
elif self.ref_key == 'LINK':
return sel... | Can you create a Python 3 function that
returns the ID of the resource to which this not is attached to the resource. | You are a Python code generator, capable of creating scripts from specifications. |
def get_ref(self):
"""
Return the ID of the resource to which this not is attached
"""
if self.ref_key == 'NETWORK':
return self.network
elif self.ref_key == 'NODE':
return self.node
elif self.ref_key == 'LINK':
return self.link
... | How would you code a function in Python 3 to
return the ID of the resource to which this not is attached to the current resource. | As a Python code composer, you craft elegant and concise scripts. |
def permissions(self):
"""Return a set with all permissions granted to the user."""
perms = set()
for r in self.roles:
perms = perms | set(r.permissions)
return perms | How would you code a function in Python 3 to
return a set with all permissions granted to the user. | As a Python code composer, you craft elegant and concise scripts. |
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) | Can you create a Python 3 function that
returns a set with all roles granted to the user. | As a python code expert, you are capable of creating scripts from specifications. |
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 | How would you code a function in Python 3 to
check that the user is an admin | You are a Python code architect, reviewing and designing scalable and efficient code |
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 = _g... | Create a Python 3 function to
check that the unit and dimension on a type attribute match. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get all the types that this resource has the attributes of the resource. | Here you have a function in Python 3, explain what it does
def get_types_by_attr(resource, template_id=None):
resource_type_templates = []
#Create a list of all of this resources attributes.
attr_ids = []
for res_attr in resource.attributes:
attr_ids.append(res_attr.attr_id)
all_resource_a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_attr_by_name_and_dimension(name, dimension_id):
"""
Search for an attribute with the given name and dimension_id.
If such an attribute does not exist, create one.
"""
attr = db.DBSession.query(Attr).filter(Attr.name==name, Attr.dimension_id==dimension_id).first()
if attr is No... | Write a Python 3 function that can
get an attribute by name and dimension_id. | You are a Python code generator, capable of creating scripts from specifications. |
def get_template_as_json(template_id, **kwargs):
"""
Get a template (including attribute and dataset definitions) as a JSON
string. This is just a wrapper around the get_template_as_dict function.
"""
user_id = kwargs['user_id']
return json.dumps(get_template_as_dict(template_id, user_id... | Can you write a function in Python 3 where it
gets a template as a JSON string. | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.