text stringlengths 81 112k |
|---|
checks if user is member of a group
def has_membership(self, user, role):
""" checks if user is member of a group"""
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if targetRecord:
return role in [i.role for i in targetRecord.groups]
return Fal... |
authorize a group for something
def add_permission(self, role, name):
""" authorize a group for something """
if self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
... |
revoke authorization of a group
def del_permission(self, role, name):
""" revoke authorization of a group """
if not self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
target = AuthPermission.objects(groups=ta... |
verify user has permission
def user_has_permission(self, user, name):
""" verify user has permission """
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return False
for group in targetRecord.groups:
if self.has_... |
patch: patch, minor, major
def bump_version(version, bump='patch'):
"""patch: patch, minor, major"""
try:
parts = map(int, version.split('.'))
except ValueError:
fail('Current version is not numeric')
if bump == 'patch':
parts[2] += 1
elif bump == 'minor':
parts[1] ... |
Signal decorator to allow use of callback functions as class decorators.
def handler(event):
"""Signal decorator to allow use of callback functions as class decorators."""
def decorator(fn):
def apply(cls):
event.connect(fn, sender=cls)
return cls
fn.apply = apply
... |
dumps all valid jsons
This is the latest after hook
def stringify(req, resp):
"""
dumps all valid jsons
This is the latest after hook
"""
if isinstance(resp.body, dict):
try:
resp.body = json.dumps(resp.body)
except(nameError):
resp.status = falcon.HTTP_5... |
Post-processing of the response (after routing).
Args:
req: Request object.
resp: Response object.
resource: Resource object to which the request was
routed. May be None if no route was found
for the request.
def process_response(self, req, r... |
Run the given command.
Parameters:
:param command: A string describing a command.
:param arguments: A list of strings describing arguments to the command.
def run(command=None, *arguments):
"""
Run the given command.
Parameters:
:param command: A string describing a command.
:param ar... |
Create a ParamList instance for actual interpretation
:args: TODO
:returns: A ParamList object
def instantiate(self, scope, args, interp):
"""Create a ParamList instance for actual interpretation
:args: TODO
:returns: A ParamList object
"""
param_instances = [... |
get_experiments will return loaded json for all valid experiments from an experiment folder
:param base: full path to the base folder with experiments inside
:param load: if True, returns a list of loaded config.json objects. If False (default) returns the paths to the experiments
def get_experiments(base, loa... |
load_experiments
a wrapper for load_experiment to read multiple experiments
:param experiment_folders: a list of experiment folders to load, full paths
def load_experiments(folders):
'''load_experiments
a wrapper for load_experiment to read multiple experiments
:param experiment_folders: a list of ... |
load_experiment:
reads in the config.json for a folder, returns None if not found.
:param folder: full path to experiment folder
:param return_path: if True, don't load the config.json, but return it
def load_experiment(folder, return_path=False):
'''load_experiment:
reads in the config.json for a ... |
we compare the basename (the exp_id) of the selection and available,
regardless of parent directories
def get_selection(available, selection, base='/scif/apps'):
'''we compare the basename (the exp_id) of the selection and available,
regardless of parent directories'''
if isinstance(selection,... |
make_lookup returns dict object to quickly look up query experiment on exp_id
:param experiment_list: a list of query (dict objects)
:param key_field: the key in the dictionary to base the lookup key (str)
:returns lookup: dict (json) with key as "key_field" from query_list
def make_lookup(experiment_list,... |
validate
:param folder: full path to experiment folder with config.json. If path begins
with https, we assume to be starting from a repository.
def validate(folder=None, cleanup=False):
'''validate
:param folder: full path to experiment folder with config.json. If path begins
... |
return the raw library, without parsing
def get_library(lookup=True, key='exp_id'):
''' return the raw library, without parsing'''
library = None
response = requests.get(EXPFACTORY_LIBRARY)
if response.status_code == 200:
library = response.json()
if lookup is True:
return m... |
Define the ``Int3()`` function in the interpreter. Calling
``Int3()`` will drop the user into an interactive debugger.
def int3(params, ctxt, scope, stream, coord, interp):
"""Define the ``Int3()`` function in the interpreter. Calling
``Int3()`` will drop the user into an interactive debugger.
"""
... |
initdb will check for writability of the data folder, meaning
that it is bound to the local machine. If the folder isn't bound,
expfactory runs in demo mode (not saving data)
def initdb(self):
'''initdb will check for writability of the data folder, meaning
that it is bound to ... |
obtain database and filesystem preferences from defaults,
and compare with selection in container.
def setup(self):
''' obtain database and filesystem preferences from defaults,
and compare with selection in container.
'''
self.selection = EXPFACTORY_EXPERIMENTS
... |
return the name of the next experiment, depending on the user's
choice to randomize. We don't remove any experiments here, that is
done on finish, in the case the user doesn't submit data (and
thus finish). A return of None means the user has completed the
battery of experime... |
remove an experiment from the list after completion.
def finish_experiment(self, session, exp_id):
'''remove an experiment from the list after completion.
'''
self.logger.debug('Finishing %s' %exp_id)
experiments = session.get('experiments', [])
experiments = [x for x in experim... |
Return directories (and sub) starting from a base
def find_subdirectories(basepath):
'''
Return directories (and sub) starting from a base
'''
directories = []
for root, dirnames, filenames in os.walk(basepath):
new_directories = [d for d in dirnames if d not in directories]
directo... |
Return directories at one level specified by user
(not recursive)
def find_directories(root,fullpath=True):
'''
Return directories at one level specified by user
(not recursive)
'''
directories = []
for item in os.listdir(root):
# Don't include hidden directories
if not re.m... |
Copy an entire directory recursively
def copy_directory(src, dest, force=False):
''' Copy an entire directory recursively
'''
if os.path.exists(dest) and force is True:
shutil.rmtree(dest)
try:
shutil.copytree(src, dest)
except OSError as e:
# If the error was caused becaus... |
clone a repository from Github
def clone(url, tmpdir=None):
'''clone a repository from Github'''
if tmpdir is None:
tmpdir = tempfile.mkdtemp()
name = os.path.basename(url).replace('.git', '')
dest = '%s/%s' %(tmpdir,name)
return_code = os.system('git clone %s %s' %(url,dest))
if return... |
run_command uses subprocess to send a command to the terminal.
:param cmd: the command to send, should be a list for subprocess
def run_command(cmd):
'''run_command uses subprocess to send a command to the terminal.
:param cmd: the command to send, should be a list for subprocess
'''
output = Popen... |
read in and return a template file
def get_template(name, base=None):
'''read in and return a template file
'''
# If the file doesn't exist, assume relative to base
template_file = name
if not os.path.exists(template_file):
if base is None:
base = get_templatedir()
templ... |
make a substitution for a template_tag in a template
def sub_template(template,template_tag,substitution):
'''make a substitution for a template_tag in a template
'''
template = template.replace(template_tag,substitution)
return template |
parse through a request, and return fields from post in a dictionary
def get_post_fields(request):
'''parse through a request, and return fields from post in a dictionary
'''
fields = dict()
for field,value in request.form.items():
fields[field] = value
return fields |
getenv will attempt to get an environment variable. If the variable
is not found, None is returned.
:param variable_key: the variable name
:param required: exit with error if not found
:param silent: Do not print debugging information for variable
def getenv(variable_key, default=None, required=False, ... |
Parse the data stream using the supplied template. The data stream
WILL NOT be automatically closed.
:data: Input data, can be either a string or a file-like object (StringIO, file, etc)
:template: template contents (str)
:data_file: PATH to the data to be used as the input stream
:template_file: t... |
Runs a simple checksum on a file and returns the result as a int64. The
algorithm can be one of the following constants:
CHECKSUM_BYTE - Treats the file as a set of unsigned bytes
CHECKSUM_SHORT_LE - Treats the file as a set of unsigned little-endian shorts
CHECKSUM_SHORT_BE - Treats the file as a set ... |
This function converts the argument data into a set of hex bytes
and then searches the current file for all occurrences of those
bytes. data may be any of the basic types or an array of one of
the types. If data is an array of signed bytes, it is assumed to
be a null-terminated string. To search for an ... |
This function is identical to the FindAll function except that the
return value is the position of the first occurrence of the target
found. A negative number is returned if the value could not be found.
def FindFirst(params, ctxt, scope, stream, coord, interp):
"""
This function is identical to the Fi... |
This function returns the position of the next occurrence of the
target value specified with the FindFirst function. If dir is 1, the
find direction is down. If dir is 0, the find direction is up. The
return value is the address of the found data, or -1 if the target
is not found.
def FindNext(params, ... |
assumes a flat (file system) database, organized by experiment id, and
subject id, with data (json) organized by subject identifier
def generate_subid(self, token=None):
'''assumes a flat (file system) database, organized by experiment id, and
subject id, with data (json) organized by subject identif... |
list users, each associated with a filesystem folder
def list_users(self):
'''list users, each associated with a filesystem folder
'''
folders = glob('%s/*' %(self.database))
folders.sort()
return [self.print_user(x) for x in folders] |
print a filesystem database user. A "database" folder that might end with
the participant status (e.g. _finished) is extracted to print in format
[folder] [identifier][studyid]
/scif/data/expfactory/xxxx-xxxx xxxx-xxxx[studyid]
def print_user(self, user):
'''print a ... |
generate a new user on the filesystem, still session based so we
create a new identifier. This function is called from the users new
entrypoint, and it assumes we want a user generated with a token.
since we don't have a database proper, we write the folder name to
the filesystem
def gene... |
finish user will append "finished" (or other) to the data folder when
the user has completed (or been revoked from) the battery.
For headless, this means that the session is ended and the token
will not work again to rewrite the result. If the user needs to update
or redo an experiment, th... |
restart user will remove any "finished" or "revoked" extensions from
the user folder to restart the session. This command always comes from
the client users function, so we know subid does not start with the
study identifer first
def restart_user(self, subid):
'''restart user will remove any "finished... |
retrieve a subject based on a token. Valid means we return a participant
invalid means we return None
def validate_token(self, token):
'''retrieve a subject based on a token. Valid means we return a participant
invalid means we return None
'''
# A token that is finished or revoked is not vali... |
refresh or generate a new token for a user. If the user is finished,
this will also make the folder available again for using.
def refresh_token(self, subid):
'''refresh or generate a new token for a user. If the user is finished,
this will also make the folder available again for using.'''
if os... |
save data will obtain the current subid from the session, and save it
depending on the database type. Currently we just support flat files
def save_data(self, session, exp_id, content):
'''save data will obtain the current subid from the session, and save it
depending on the database type. Currently ... |
init_db for the filesystem ensures that the base folder (named
according to the studyid) exists.
def init_db(self):
'''init_db for the filesystem ensures that the base folder (named
according to the studyid) exists.
'''
self.session = None
if not os.path.exists(self.data_base):
... |
Used as a decorator to add the decorated function to the
pfp interpreter so that it can be used from within scripts.
:param str name: The name of the function as it will be exposed in template scripts.
:param pfp.fields.Field ret: The return type of the function (a class)
:param pfp.interp.PfpInterp in... |
Peek at the next 16 bytes in the stream::
Example:
The peek command will display the next 16 hex bytes in the input
stream::
pfp> peek
89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 .PNG........IHDR
def do_peek(self, args):
"""Peek at the next ... |
Step over the next statement
def do_next(self, args):
"""Step over the next statement
"""
self._do_print_from_last_cmd = True
self._interp.step_over()
return True |
Step INTO the next statement
def do_step(self, args):
"""Step INTO the next statement
"""
self._do_print_from_last_cmd = True
self._interp.step_into()
return True |
Continue the interpreter
def do_continue(self, args):
"""Continue the interpreter
"""
self._do_print_from_last_cmd = True
self._interp.cont()
return True |
Eval the user-supplied statement. Note that you can do anything with
this command that you can do in a template.
The resulting value of your statement will be displayed.
def do_eval(self, args):
"""Eval the user-supplied statement. Note that you can do anything with
this command that y... |
Show the current structure of __root (no args),
or show the result of the expression (something that can be eval'd).
def do_show(self, args):
"""Show the current structure of __root (no args),
or show the result of the expression (something that can be eval'd).
"""
args = args.s... |
The quit command
def do_quit(self, args):
"""The quit command
"""
self._interp.set_break(self._interp.BREAK_NONE)
return True |
takes in a Github repository for validation of preview and
runtime (and possibly tests passing?
def validate(self, url):
''' takes in a Github repository for validation of preview and
runtime (and possibly tests passing?
'''
# Preview must provide the live URL of the ... |
Replace passwords with a secret in a dictionary.
def mask_dict_password(dictionary, secret='***'):
"""Replace passwords with a secret in a dictionary."""
d = dictionary.copy()
for k in d:
if 'password' in k:
d[k] = secret
return d |
save is a view to save data. We might want to adjust this to allow for
updating saved data, but given single file is just one post for now
def save():
'''save is a view to save data. We might want to adjust this to allow for
updating saved data, but given single file is just one post for now
'''
... |
this is the main entrypoint for a container based web server, with
most of the variables coming from the environment. See the Dockerfile
template for how this function is executed.
def main(args,parser,subparser=None):
'''this is the main entrypoint for a container based web server, with
most ... |
save data will obtain the current subid from the session, and save it
depending on the database type.
def save_data(self,session, exp_id, content):
'''save data will obtain the current subid from the session, and save it
depending on the database type.'''
from expfactory.database.models import (
... |
initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db
def init_db(self):
'''initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db
'''
# Database Setup, use default if ur... |
Used to "reserve" ``num_bits`` amount of bits in order to keep track
of consecutive bitfields (or are the called bitfield groups?).
E.g. ::
struct {
char a:8, b:8;
char c:4, d:4, e:8;
}
:param int num_bits: The number of bits to claim
... |
Return ``num_bits`` bits, taking into account endianness and
left-right bit directions
def read_bits(self, stream, num_bits, padded, left_right, endian):
"""Return ``num_bits`` bits, taking into account endianness and
left-right bit directions
"""
if self._cls_bits is None and... |
Write the bits. Once the size of the written bits is equal
to the number of the reserved bits, flush it to the stream
def write_bits(self, stream, raw_bits, padded, left_right, endian):
"""Write the bits. Once the size of the written bits is equal
to the number of the reserved bits, flush it to... |
Save off the current value of the field
def _pfp__snapshot(self, recurse=True):
"""Save off the current value of the field
"""
if hasattr(self, "_pfp__value"):
self._pfp__snapshot_value = self._pfp__value |
Process the metadata once the entire struct has been
declared.
def _pfp__process_metadata(self):
"""Process the metadata once the entire struct has been
declared.
"""
if self._pfp__metadata_processor is None:
return
metadata_info = self._pfp__metadata_proces... |
Add the watcher to the list of fields that
are watching this field
def _pfp__watch(self, watcher):
"""Add the watcher to the list of fields that
are watching this field
"""
if self._pfp__parent is not None and isinstance(self._pfp__parent, Union):
self._pfp__parent._... |
Subscribe to update events on each field in ``watch_fields``, using
``update_func`` to update self's value when ``watch_field``
changes
def _pfp__set_watch(self, watch_fields, update_func, *func_call_info):
"""Subscribe to update events on each field in ``watch_fields``, using
``update_... |
Set the packer/pack/unpack functions for this field, as
well as the pack type.
:pack_type: The data type of the packed data
:packer: A function that can handle packing and unpacking. First
arg is true/false (to pack or unpack). Second arg is the stream.
Must re... |
Pack the nested field
def _pfp__pack_data(self):
"""Pack the nested field
"""
if self._pfp__pack_type is None:
return
tmp_stream = six.BytesIO()
self._._pfp__build(bitwrap.BitwrappedStream(tmp_stream))
raw_data = tmp_stream.getvalue()
unpack_func = ... |
Means that the field has already been parsed normally,
and that it now needs to be unpacked.
:raw_data: A string of the data that the field consumed while parsing
def _pfp__unpack_data(self, raw_data):
"""Means that the field has already been parsed normally,
and that it now needs to b... |
Handle the watched field that was updated
def _pfp__handle_updated(self, watched_field):
"""Handle the watched field that was updated
"""
self._pfp__no_notify = True
# nested data has been changed, so rebuild the
# nested data to update the field
# TODO a global setting... |
Return the width of the field (sizeof)
def _pfp__width(self):
"""Return the width of the field (sizeof)
"""
raw_output = six.BytesIO()
output = bitwrap.BitwrappedStream(raw_output)
self._pfp__build(output)
output.flush()
return len(raw_output.getvalue()) |
Set the new value if type checking is passes, potentially
(TODO? reevaluate this) casting the value to something else
:new_val: The new value
:returns: TODO
def _pfp__set_value(self, new_val):
"""Set the new value if type checking is passes, potentially
(TODO? reevaluate this) ... |
Save off the current value of the field
def _pfp__snapshot(self, recurse=True):
"""Save off the current value of the field
"""
super(Struct, self)._pfp__snapshot(recurse=recurse)
if recurse:
for child in self._pfp__children:
child._pfp__snapshot(recurse=recu... |
Restore the snapshotted value without triggering any events
def _pfp__restore_snapshot(self, recurse=True):
"""Restore the snapshotted value without triggering any events
"""
super(Struct, self)._pfp__restore_snapshot(recurse=recurse)
if recurse:
for child in self._pfp__chi... |
Initialize the struct. Value should be an array of
fields, one each for each struct member.
:value: An array of fields to initialize the struct with
:returns: None
def _pfp__set_value(self, value):
"""Initialize the struct. Value should be an array of
fields, one each for each ... |
Add a child to the Struct field. If multiple consecutive fields are
added with the same name, an implicit array will be created to store
all fields of that name.
:param str name: The name of the child
:param pfp.fields.Field child: The field to add
:param bool overwrite: Overwri... |
This new child, and potentially one already existing child, need to
have a numeric suffix appended to their name.
An entry will be made for this name in ``self._pfp__name_collisions`` to keep
track of the next available suffix number
def _pfp__handle_non_consecutive_duplicate(self, nam... |
Return True/False if the child is a non-consecutive duplicately named
field. Consecutive duplicately-named fields are stored in an implicit array,
non-consecutive duplicately named fields have a numeric suffix appended to their name
def _pfp__is_non_consecutive_duplicate(self, name, child):
"""... |
Handle inserting implicit array elements
def _pfp__handle_implicit_array(self, name, child):
"""Handle inserting implicit array elements
"""
existing_child = self._pfp__children_map[name]
if isinstance(existing_child, Array):
# I don't think we should check this
... |
Parse the incoming stream
:stream: Input stream to be parsed
:returns: Number of bytes parsed
def _pfp__parse(self, stream, save_offset=False):
"""Parse the incoming stream
:stream: Input stream to be parsed
:returns: Number of bytes parsed
"""
if save_offset:... |
Build the field and write the result into the stream
:stream: An IO stream that can be written to
:returns: None
def _pfp__build(self, stream=None, save_offset=False):
"""Build the field and write the result into the stream
:stream: An IO stream that can be written to
:returns... |
Show the contents of the struct
def _pfp__show(self, level=0, include_offset=False):
"""Show the contents of the struct
"""
res = []
res.append("{}{} {{".format(
"{:04x} ".format(self._pfp__offset) if include_offset else "",
self._pfp__show_name
))
... |
Add a child to the Union field
:name: The name of the child
:child: A :class:`.Field` instance
:returns: The resulting field
def _pfp__add_child(self, name, child, stream=None):
"""Add a child to the Union field
:name: The name of the child
:child: A :class:`.Field` in... |
Handle a child with an updated value
def _pfp__notify_update(self, child=None):
"""Handle a child with an updated value
"""
if getattr(self, "_pfp__union_update_other_children", True):
self._pfp__union_update_other_children = False
new_data = child._pfp__build()
... |
Parse the incoming stream
:stream: Input stream to be parsed
:returns: Number of bytes parsed
def _pfp__parse(self, stream, save_offset=False):
"""Parse the incoming stream
:stream: Input stream to be parsed
:returns: Number of bytes parsed
"""
if save_offset:
... |
Build the union and write the result into the stream.
:stream: None
:returns: None
def _pfp__build(self, stream=None, save_offset=False):
"""Build the union and write the result into the stream.
:stream: None
:returns: None
"""
max_size = -1
if stream i... |
Parse the IO stream for this numeric field
:stream: An IO stream that can be read from
:returns: The number of bytes parsed
def _pfp__parse(self, stream, save_offset=False):
"""Parse the IO stream for this numeric field
:stream: An IO stream that can be read from
:returns: The... |
Build the field and write the result into the stream
:stream: An IO stream that can be written to
:returns: None
def _pfp__build(self, stream=None, save_offset=False):
"""Build the field and write the result into the stream
:stream: An IO stream that can be written to
:returns... |
Return the dominating numeric class between the two
:obj1: TODO
:obj2: TODO
:returns: TODO
def _dom_class(self, obj1, obj2):
"""Return the dominating numeric class between the two
:obj1: TODO
:obj2: TODO
:returns: TODO
"""
if isinstance(obj1, D... |
Set the value, potentially converting an unsigned
value to a signed one (and visa versa)
def _pfp__set_value(self, new_val):
"""Set the value, potentially converting an unsigned
value to a signed one (and visa versa)"""
if self._pfp__frozen:
raise errors.UnmodifiableConst()
... |
Parse the IO stream for this enum
:stream: An IO stream that can be read from
:returns: The number of bytes parsed
def _pfp__parse(self, stream, save_offset=False):
"""Parse the IO stream for this enum
:stream: An IO stream that can be read from
:returns: The number of bytes p... |
Save off the current value of the field
def _pfp__snapshot(self, recurse=True):
"""Save off the current value of the field
"""
super(Array, self)._pfp__snapshot(recurse=recurse)
self.snapshot_raw_data = self.raw_data
if recurse:
for item in self.items:
... |
Set the value of the String, taking into account
escaping and such as well
def _pfp__set_value(self, new_val):
"""Set the value of the String, taking into account
escaping and such as well
"""
if not isinstance(new_val, Field):
new_val = utils.binary(utils.string_esc... |
Read from the stream until the string is null-terminated
:stream: The input stream
:returns: None
def _pfp__parse(self, stream, save_offset=False):
"""Read from the stream until the string is null-terminated
:stream: The input stream
:returns: None
"""
if save... |
Build the String field
:stream: TODO
:returns: TODO
def _pfp__build(self, stream=None, save_offset=False):
"""Build the String field
:stream: TODO
:returns: TODO
"""
if stream is not None and save_offset:
self._pfp__offset = stream.tell()
... |
Prints format string to stdout
:params: TODO
:returns: TODO
def Printf(params, ctxt, scope, stream, coord, interp):
"""Prints format string to stdout
:params: TODO
:returns: TODO
"""
if len(params) == 1:
if interp._printf:
sys.stdout.write(PYSTR(params[0]))
re... |
Mutate the provided field (probably a Dom or struct instance) using the
strategy specified with ``strat_name_or_class``, yielding ``num`` mutations
that affect up to ``at_once`` fields at once.
This function will yield back the field after each mutation, optionally
also yielding a ``set`` of fields tha... |
Return the strategy identified by its name. If ``name_or_class`` is a class,
it will be simply returned.
def get_strategy(name_or_cls):
"""Return the strategy identified by its name. If ``name_or_class`` is a class,
it will be simply returned.
"""
if isinstance(name_or_cls, six.string_types):
... |
Mutate the given field, modifying it directly. This is not
intended to preserve the value of the field.
:field: The pfp.fields.Field instance that will receive the new value
def mutate(self, field):
"""Mutate the given field, modifying it directly. This is not
intended to preserve the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.