INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a ContextManagerFuture to be yielded in a with statement.
def connected_client(self): """Returns a ContextManagerFuture to be yielded in a with statement. Returns: A ContextManagerFuture object. Examples: >>> with (yield pool.connected_client()) as client: # client is a connected tornadis.Client instance ...
Releases a client object to the pool.
def release_client(self, client): """Releases a client object to the pool. Args: client: Client object. """ if isinstance(client, Client): if not self._is_expired_client(client): LOG.debug('Client is not expired. Adding back to pool') ...
Disconnects all pooled client objects.
def destroy(self): """Disconnects all pooled client objects.""" while True: try: client = self.__pool.popleft() if isinstance(client, Client): client.disconnect() except IndexError: break
( pre ) Connects some or all redis clients inside the pool.
def preconnect(self, size=-1): """(pre)Connects some or all redis clients inside the pool. Args: size (int): number of redis clients to build and to connect (-1 means all clients if pool max_size > -1) Raises: ClientError: when size == -1 and pool max_si...
Setup python search and add TASKS_VENDOR_DIR ( if available ).
def setup_path(invoke_minversion=None): """Setup python search and add ``TASKS_VENDOR_DIR`` (if available).""" # print("INVOKE.tasks: setup_path") if not os.path.isdir(TASKS_VENDOR_DIR): print("SKIP: TASKS_VENDOR_DIR=%s is missing" % TASKS_VENDOR_DIR) return elif os.path.abspath(TASKS_VE...
Ensures that: mod: invoke has at the least the: param: min_version. Otherwise
def require_invoke_minversion(min_version, verbose=False): """Ensures that :mod:`invoke` has at the least the :param:`min_version`. Otherwise, :param min_version: Minimal acceptable invoke version (as string). :param verbose: Indicates if invoke.version should be shown. :raises: VersionRequirem...
Decorator for SectionSchema classes to define the mapping between a config section schema class and one or more config sections with matching name ( s ).
def matches_section(section_name): """Decorator for SectionSchema classes to define the mapping between a config section schema class and one or more config sections with matching name(s). .. sourcecode:: @matches_section("foo") class FooSchema(SectionSchema): pass ...
Class decorator to assign parameter name to instances of: class: Param.
def assign_param_names(cls=None, param_class=None): """Class decorator to assign parameter name to instances of :class:`Param`. .. sourcecode:: @assign_param_names class ConfigSectionSchema(object): alice = Param(type=str) bob = Param(type=str) assert ConfigS...
Selects the parameters of a config section schema.
def select_params_from_section_schema(section_schema, param_class=Param, deep=False): """Selects the parameters of a config section schema. :param section_schema: Configuration file section schema to use. :return: Generator of params """ # pylint: disable=inva...
Parse a config file section ( INI file ) by using its schema/ description.
def parse_config_section(config_section, section_schema): """Parse a config file section (INI file) by using its schema/description. .. sourcecode:: import configparser # -- NOTE: Use backport for Python2 import click from click_configfile import SectionSchema, Param, parse_config_...
Generates all configuration file name combinations to read.
def generate_configfile_names(config_files, config_searchpath=None): """Generates all configuration file name combinations to read. .. sourcecode:: # -- ALGORITHM: # First basenames/directories are prefered and override other files. for config_path in reversed(config_searchpath): ...
Select a subset of the sections in a configuration file by using a list of section names of list of section name patters ( supporting: mod: fnmatch wildcards ).
def select_config_sections(configfile_sections, desired_section_patterns): """Select a subset of the sections in a configuration file by using a list of section names of list of section name patters (supporting :mod:`fnmatch` wildcards). :param configfile_sections: List of config section names (as stri...
Indicates if this schema can be used for a config section by using the section name.
def matches_section(cls, section_name, supported_section_names=None): """Indicates if this schema can be used for a config section by using the section name. :param section_name: Config section name to check. :return: True, if this schema can be applied to the config section. ...
Derive support config section names from config section schemas. If no: param: config_section_schemas are provided the schemas from this class are used ( normally defined in the DerivedClass ).
def collect_config_sections_from_schemas(cls, config_section_schemas=None): # pylint: disable=invalid-name """Derive support config section names from config section schemas. If no :param:`config_section_schemas` are provided, the schemas from this class are used (normally defined in the...
Process the config section and store the extracted data in the param: storage ( as outgoing param ).
def process_config_section(cls, config_section, storage): """Process the config section and store the extracted data in the param:`storage` (as outgoing param). """ # -- CONCEPT: # if not storage: # # -- INIT DATA: With default parts. # storage.update(dict...
Select the config schema that matches the config section ( by name ).
def select_config_schema_for(cls, section_name): """Select the config schema that matches the config section (by name). :param section_name: Config section name (as key). :return: Config section schmema to use (subclass of: SectionSchema). """ # pylint: disable=cell-var-from-...
Selects the data storage for a config section within the: param: storage. The primary config section is normally merged into the: param: storage.
def select_storage_for(cls, section_name, storage): """Selects the data storage for a config section within the :param:`storage`. The primary config section is normally merged into the :param:`storage`. :param section_name: Config section (name) to process. :param storage: ...
Cleanup temporary dirs/ files to regain a clean state.
def clean(ctx, dry_run=False): """Cleanup temporary dirs/files to regain a clean state.""" # -- VARIATION-POINT 1: Allow user to override in configuration-file directories = ctx.clean.directories files = ctx.clean.files # -- VARIATION-POINT 2: Allow user to add more files/dirs to be removed. ex...
Clean up everything even the precious stuff. NOTE: clean task is executed first.
def clean_all(ctx, dry_run=False): """Clean up everything, even the precious stuff. NOTE: clean task is executed first. """ cleanup_dirs(ctx.clean_all.directories or [], dry_run=dry_run) cleanup_dirs(ctx.clean_all.extra_directories or [], dry_run=dry_run) cleanup_files(ctx.clean_all.files or [],...
Cleanup python related files/ dirs: *. pyc *. pyo...
def clean_python(ctx, dry_run=False): """Cleanup python related files/dirs: *.pyc, *.pyo, ...""" # MAYBE NOT: "**/__pycache__" cleanup_dirs(["build", "dist", "*.egg-info", "**/__pycache__"], dry_run=dry_run) if not dry_run: ctx.run("py.cleanup") cleanup_files(["**/*.pyc", "*...
Remove files or files selected by file patterns. Skips removal if file does not exist.
def cleanup_files(patterns, dry_run=False, workdir="."): """Remove files or files selected by file patterns. Skips removal if file does not exist. :param patterns: File patterns, like "**/*.pyc" (as list). :param dry_run: Dry-run mode indicator (as bool). :param workdir: Current work dir...
Use pathlib for ant - like patterns like: **/ *. py
def path_glob(pattern, current_dir=None): """Use pathlib for ant-like patterns, like: "**/*.py" :param pattern: File/directory pattern to use (as string). :param current_dir: Current working directory (as Path, pathlib.Path, str) :return Resolved Path (as path.Path). """ if not current_di...
Stacks a redis command inside the object.
def stack_call(self, *args): """Stacks a redis command inside the object. The syntax is the same than the call() method a Client class. Args: *args: full redis command as variable length argument list. Examples: >>> pipeline = Pipeline() >>> pipelin...
Connects the object to the host: port.
def connect(self): """Connects the object to the host:port. Returns: Future: a Future object with True as result if the connection process was ok. """ if self.is_connected() or self.is_connecting(): raise tornado.gen.Return(True) if self.u...
Disconnects the object.
def disconnect(self): """Disconnects the object. Safe method (no exception, even if it's already disconnected or if there are some connection errors). """ if not self.is_connected() and not self.is_connecting(): return LOG.debug("disconnecting from %s...", se...
Buffers some data to be sent to the host: port in a non blocking way.
def write(self, data): """Buffers some data to be sent to the host:port in a non blocking way. So the data is always buffered and not sent on the socket in a synchronous way. You can give a WriteBuffer as parameter. The internal Connection WriteBuffer will be extended with this...
Simulate the Python 3 surrogateescape handler but for Python 2 only.
def surrogate_escape(error): """ Simulate the Python 3 ``surrogateescape`` handler, but for Python 2 only. """ chars = error.object[error.start:error.end] assert len(chars) == 1 val = ord(chars) val += 0xdc00 return __builtin__.unichr(val), error.end
Ensure the path as retrieved from a Python API such as: func: os. listdir is a proper Unicode string.
def _always_unicode(cls, path): """ Ensure the path as retrieved from a Python API, such as :func:`os.listdir`, is a proper Unicode string. """ if PY3 or isinstance(path, text_type): return path return path.decode(sys.getfilesystemencoding(), 'surrogateescape'...
The same as: meth: name but with one file extension stripped off.
def namebase(self): """ The same as :meth:`name`, but with one file extension stripped off. For example, ``Path('/home/guido/python.tar.gz').name == 'python.tar.gz'``, but ``Path('/home/guido/python.tar.gz').namebase == 'python.tar'``. """ base, ext = self.module...
D. listdir () - > List of items in this directory.
def listdir(self, pattern=None): """ D.listdir() -> List of items in this directory. Use :meth:`files` or :meth:`dirs` instead if you want a listing of just files or just subdirectories. The elements of the list are Path objects. With the optional `pattern` argument, this only...
D. dirs () - > List of this directory s subdirectories.
def dirs(self, pattern=None): """ D.dirs() -> List of this directory's subdirectories. The elements of the list are Path objects. This does not walk recursively into subdirectories (but see :meth:`walkdirs`). With the optional `pattern` argument, this only lists directo...
D. files () - > List of the files in this directory.
def files(self, pattern=None): """ D.files() -> List of the files in this directory. The elements of the list are Path objects. This does not walk into subdirectories (see :meth:`walkfiles`). With the optional `pattern` argument, this only lists files whose names match the give...
D. walkdirs () - > iterator over subdirs recursively.
def walkdirs(self, pattern=None, errors='strict'): """ D.walkdirs() -> iterator over subdirs, recursively. With the optional `pattern` argument, this yields only directories whose names match the given pattern. For example, ``mydir.walkdirs('*test')`` yields only directories wi...
D. walkfiles () - > iterator over files in D recursively.
def walkfiles(self, pattern=None, errors='strict'): """ D.walkfiles() -> iterator over files in D, recursively. The optional argument `pattern` limits the results to files with names that match the pattern. For example, ``mydir.walkfiles('*.tmp')`` yields only files with the ``.tmp`` ...
Open this file and return a corresponding: class: file object.
def open(self, *args, **kwargs): """ Open this file and return a corresponding :class:`file` object. Keyword arguments work as in :func:`io.open`. If the file cannot be opened, an :class:`~exceptions.OSError` is raised. """ with io_error_compat(): return io.open(sel...
r Write the given text to this file.
def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two diff...
r Write the given lines of text to this file.
def write_lines(self, lines, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given lines of text to this file. By default this overwrites any existing file at this path. This puts a platform-specific newline sequence on every line. ...
Like: meth: mkdir but does not raise an exception if the directory already exists.
def mkdir_p(self, mode=0o777): """ Like :meth:`mkdir`, but does not raise an exception if the directory already exists. """ try: self.mkdir(mode) except OSError: _, e, _ = sys.exc_info() if e.errno != errno.EEXIST: raise return ...
Like: meth: makedirs but does not raise an exception if the directory already exists.
def makedirs_p(self, mode=0o777): """ Like :meth:`makedirs`, but does not raise an exception if the directory already exists. """ try: self.makedirs(mode) except OSError: _, e, _ = sys.exc_info() if e.errno != errno.EEXIST: raise ...
Like: meth: rmdir but does not raise an exception if the directory is not empty or does not exist.
def rmdir_p(self): """ Like :meth:`rmdir`, but does not raise an exception if the directory is not empty or does not exist. """ try: self.rmdir() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST: ...
Like: meth: removedirs but does not raise an exception if the directory is not empty or does not exist.
def removedirs_p(self): """ Like :meth:`removedirs`, but does not raise an exception if the directory is not empty or does not exist. """ try: self.removedirs() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOTEMPTY and e.errno != errno...
Like: meth: remove but does not raise an exception if the file does not exist.
def remove_p(self): """ Like :meth:`remove`, but does not raise an exception if the file does not exist. """ try: self.unlink() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOENT: raise return self
Like: meth: rmtree but does not raise an exception if the directory does not exist.
def rmtree_p(self): """ Like :meth:`rmtree`, but does not raise an exception if the directory does not exist. """ try: self.rmtree() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOENT: raise return self
Copy entire contents of self to dst overwriting existing contents in dst with those in self.
def merge_tree(self, dst, symlinks=False, *args, **kwargs): """ Copy entire contents of self to dst, overwriting existing contents in dst with those in self. If the additional keyword `update` is True, each `src` will only be copied if `dst` does not exist, or `src` is n...
DiskReader implementation.
def __gdal_dataset_default(self): """DiskReader implementation.""" if not os.path.exists(self.file_name): return None if os.path.splitext(self.file_name)[1].lower() not in self.file_types: raise RuntimeError('Filename %s does not have extension type %s.' % (self.file_nam...
Connects the client object to redis.
def connect(self): """Connects the client object to redis. It's safe to use this method even if you are already connected. Note: this method is useless with autoconnect mode (default). Returns: a Future object with True as result if the connection was ok. """ ...
Callback called when redis closed the connection.
def _close_callback(self): """Callback called when redis closed the connection. The callback queue is emptied and we call each callback found with None or with an exception object to wake up blocked client. """ while True: try: callback = self.__callb...
Callback called when some data are read on the socket.
def _read_callback(self, data=None): """Callback called when some data are read on the socket. The buffer is given to the hiredis parser. If a reply is complete, we put the decoded reply to on the reply queue. Args: data (str): string (buffer) read on the socket. ""...
Calls a redis command and returns a Future of the reply.
def call(self, *args, **kwargs): """Calls a redis command and returns a Future of the reply. Args: *args: full redis command as variable length argument list or a Pipeline object (as a single argument). **kwargs: internal private options (do not use). Re...
Calls a redis command waits for the reply and call a callback.
def async_call(self, *args, **kwargs): """Calls a redis command, waits for the reply and call a callback. Following options are available (not part of the redis command itself): - callback Function called (with the result as argument) when the result is available. If no...
Formats arguments into redis protocol...
def format_args_in_redis_protocol(*args): """Formats arguments into redis protocol... This function makes and returns a string/buffer corresponding to given arguments formated with the redis protocol. integer, text, string or binary types are automatically converted (using utf8 if necessary). ...
Internal done callback to set the result of the object.
def _done_callback(self, wrapped): """Internal "done callback" to set the result of the object. The result of the object if forced by the wrapped future. So this internal callback must be called when the wrapped future is ready. Args: wrapped (Future): the wrapped Future ob...
The result method which returns a context manager
def result(self): """The result method which returns a context manager Returns: ContextManager: The corresponding context manager """ if self.exception(): raise self.exception() # Otherwise return a context manager that cleans up after the block. ...
Create the URL in the LyricWikia format
def create_url(artist, song): """Create the URL in the LyricWikia format""" return (__BASE_URL__ + '/wiki/{artist}:{song}'.format(artist=urlize(artist), song=urlize(song)))
Retrieve the lyrics of the song and return the first one in case multiple versions are available.
def get_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve the lyrics of the song and return the first one in case multiple versions are available.""" return get_all_lyrics(artist, song, linesep, timeout)[0]
Retrieve a list of all the lyrics versions of a song.
def get_all_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve a list of all the lyrics versions of a song.""" url = create_url(artist, song) response = _requests.get(url, timeout=timeout) soup = _BeautifulSoup(response.content, "html.parser") lyricboxes = soup.findAll('div', {'class': 'l...
Open an ARF file creating as necessary.
def open_file(name, mode=None, driver=None, libver=None, userblock_size=None, **kwargs): """Open an ARF file, creating as necessary. Use this instead of h5py.File to ensure that root-level attributes and group creation property lists are set correctly. """ import sys import os from h5py im...
Create a new ARF entry under group setting required attributes.
def create_entry(group, name, timestamp, **attributes): """Create a new ARF entry under group, setting required attributes. An entry is an abstract collection of data which all refer to the same time frame. Data can include physiological recordings, sound recordings, and derived data such as spike time...
Create an ARF dataset under group setting required attributes
def create_dataset(group, name, data, units='', datatype=DataTypes.UNDEFINED, chunks=True, maxshape=None, compression=None, **attributes): """Create an ARF dataset under group, setting required attributes Required arguments: name -- the name of dataset in which to st...
Create a new array dataset under group with compound datatype and maxshape = ( None )
def create_table(group, name, dtype, **attributes): """Create a new array dataset under group with compound datatype and maxshape=(None,)""" dset = group.create_dataset( name, shape=(0,), dtype=dtype, maxshape=(None,)) set_attributes(dset, **attributes) return dset
Append data to dset along axis 0. Data must be a single element or a 1D array of the same type as the dataset ( including compound datatypes ).
def append_data(dset, data): """Append data to dset along axis 0. Data must be a single element or a 1D array of the same type as the dataset (including compound datatypes).""" N = data.shape[0] if hasattr(data, 'shape') else 1 if N == 0: return oldlen = dset.shape[0] newlen = oldlen + N...
Check the ARF version attribute of file for compatibility.
def check_file_version(file): """Check the ARF version attribute of file for compatibility. Raises DeprecationWarning for backwards-incompatible files, FutureWarning for (potentially) forwards-incompatible files, and UserWarning for files that may not have been created by an ARF library. Returns t...
Set multiple attributes on node.
def set_attributes(node, overwrite=True, **attributes): """Set multiple attributes on node. If overwrite is False, and the attribute already exists, does nothing. If the value for a key is None, the attribute is deleted. """ aset = node.attrs for k, v in attributes.items(): if not over...
Returns a sequence of links in group in order of creation.
def keys_by_creation(group): """Returns a sequence of links in group in order of creation. Raises an error if the group was not set to track creation order. """ from h5py import h5 out = [] try: group._id.links.iterate( out.append, idx_type=h5.INDEX_CRT_ORDER, order=h5.ITER...
Make an ARF timestamp from an object.
def convert_timestamp(obj): """Make an ARF timestamp from an object. Argument can be a datetime.datetime object, a time.struct_time, an integer, a float, or a tuple of integers. The returned value is a numpy array with the integer number of seconds since the Epoch and any additional microseconds. ...
Convert an ARF timestamp to a datetime. datetime object ( naive local time )
def timestamp_to_datetime(timestamp): """Convert an ARF timestamp to a datetime.datetime object (naive local time)""" from datetime import datetime, timedelta obj = datetime.fromtimestamp(timestamp[0]) return obj + timedelta(microseconds=int(timestamp[1]))
Set the uuid attribute of an HDF5 object. Use this method to ensure correct dtype
def set_uuid(obj, uuid=None): """Set the uuid attribute of an HDF5 object. Use this method to ensure correct dtype """ from uuid import uuid4, UUID if uuid is None: uuid = uuid4() elif isinstance(uuid, bytes): if len(uuid) == 16: uuid = UUID(bytes=uuid) else: ...
Return the uuid for obj or null uuid if none is set
def get_uuid(obj): """Return the uuid for obj, or null uuid if none is set""" # TODO: deprecate null uuid ret val from uuid import UUID try: uuid = obj.attrs['uuid'] except KeyError: return UUID(int=0) # convert to unicode for python 3 try: uuid = uuid.decode('ascii')...
Return the number of children of obj optionally restricting by class
def count_children(obj, type=None): """Return the number of children of obj, optionally restricting by class""" if type is None: return len(obj) else: # there doesn't appear to be any hdf5 function for getting this # information without inspecting each child, which makes this somewha...
generate a dict keyed by value
def _todict(cls): """ generate a dict keyed by value """ return dict((getattr(cls, attr), attr) for attr in dir(cls) if not attr.startswith('_'))
get_template will return a template in the template folder with some substitutions ( eg { {{ graph | safe }}: fill this in! }
def get_template(template_name,fields=None): '''get_template will return a template in the template folder, with some substitutions (eg, {'{{ graph | safe }}':"fill this in!"} ''' template = None if not template_name.endswith('.html'): template_name = "%s.html" %(template_name) here = "%...
container similarity_vector is similar to compare_packages but intended to compare a container object ( singularity image or singularity hub container ) to a list of packages. If packages_set is not provided the default used is docker - os. This can be changed to docker - library or if the user wants a custom list shou...
def container_similarity_vector(container1=None,packages_set=None,by=None): '''container similarity_vector is similar to compare_packages, but intended to compare a container object (singularity image or singularity hub container) to a list of packages. If packages_set is not provided, the default used is ...
compare_singularity_images is a wrapper for compare_containers to compare singularity containers. If image_paths2 is not defined pairwise comparison is done with image_paths1
def compare_singularity_images(image_paths1, image_paths2=None): '''compare_singularity_images is a wrapper for compare_containers to compare singularity containers. If image_paths2 is not defined, pairwise comparison is done with image_paths1 ''' repeat = False if image_paths2 is None: ...
compare_containers will generate a data structure with common and unique files to two images. If environmental variable SINGULARITY_HUB is set will use container database objects.: param container1: first container for comparison: param container2: second container for comparison if either not defined must include defa...
def compare_containers(container1=None, container2=None): '''compare_containers will generate a data structure with common and unique files to two images. If environmental variable SINGULARITY_HUB is set, will use container database objects. :param container1: first container for comparison :param ...
compare lists is the lowest level that drives compare_containers and compare_packages. It returns a comparison object ( dict ) with the unique total and intersecting things between two lists: param list1: the list for container1: param list2: the list for container2
def compare_lists(list1,list2): '''compare lists is the lowest level that drives compare_containers and compare_packages. It returns a comparison object (dict) with the unique, total, and intersecting things between two lists :param list1: the list for container1 :param list2: the list for container...
calculate_similarity will calculate similarity of two containers by files content default will calculate 2. 0 * len ( intersect )/ total package1 + total package2
def calculate_similarity(container1=None, container2=None, comparison=None, metric=None): '''calculate_similarity will calculate similarity of two containers by files content, default will calculate 2.0*len(intersect) / to...
package node aims to package a ( present working node ) for a user into a container. This assumes that the node is a single partition.: param root: the root of the node to package default is/: param name: the name for the image. If not specified will use machine s
def package_node(root=None, name=None): '''package node aims to package a (present working node) for a user into a container. This assumes that the node is a single partition. :param root: the root of the node to package, default is / :param name: the name for the image. If not specified, will use ma...
unpackage node is intended to unpackage a node that was packaged with package_node. The image should be a. tgz file. The general steps are to: 1. Package the node using the package_node function 2. Transfer the package somewhere that Singularity is installed
def unpack_node(image_path,name=None,output_folder=None,size=None): '''unpackage node is intended to unpackage a node that was packaged with package_node. The image should be a .tgz file. The general steps are to: 1. Package the node using the package_node function 2. Transfer the package somewhere that...
get_build template returns a string or file for a particular build template which is intended to build a version of a Singularity image on a cloud resource.: param template_name: the name of the template to retrieve in build/ scripts: param params: ( if needed ) a dictionary of parameters to substitute in the file: par...
def get_build_template(template_name,params=None,to_file=None): '''get_build template returns a string or file for a particular build template, which is intended to build a version of a Singularity image on a cloud resource. :param template_name: the name of the template to retrieve in build/scripts :pa...
sniff_extension will attempt to determine the file type based on the extension and return the proper mimetype: param file_path: the full path to the file to sniff: param verbose: print stuff out
def sniff_extension(file_path,verbose=True): '''sniff_extension will attempt to determine the file type based on the extension, and return the proper mimetype :param file_path: the full path to the file to sniff :param verbose: print stuff out ''' mime_types = { "xls": 'application/vnd.ms-exc...
get_script will return a build script_name if it is included in singularity/ build/ scripts otherwise will alert the user and return None: param script_name: the name of the script to look for
def get_script(script_name): '''get_script will return a build script_name, if it is included in singularity/build/scripts, otherwise will alert the user and return None :param script_name: the name of the script to look for ''' install_dir = get_installdir() script_path = "%s/build/scripts/%s"...
zip_up will zip up some list of files into a package (. zip ): param file_list: a list of files to include in the zip.: param output_folder: the output folder to create the zip in. If not: param zip_name: the name of the zipfile to return. specified a temporary folder will be given.
def zip_up(file_list,zip_name,output_folder=None): '''zip_up will zip up some list of files into a package (.zip) :param file_list: a list of files to include in the zip. :param output_folder: the output folder to create the zip in. If not :param zip_name: the name of the zipfile to return. specifi...
get_container_contents will return a list of folders and or files for a container. The environmental variable SINGULARITY_HUB being set means that container objects are referenced instead of packages: param container: the container to get content for: param gets: a list of file names to return without parent folders: p...
def get_container_contents(container, split_delim=None): '''get_container_contents will return a list of folders and or files for a container. The environmental variable SINGULARITY_HUB being set means that container objects are referenced instead of packages :param container: the container to get conte...
get_image_hashes returns the hash for an image across all levels. This is the quickest easiest way to define a container s reproducibility on each level.
def get_image_hashes(image_path, version=None, levels=None): '''get_image_hashes returns the hash for an image across all levels. This is the quickest, easiest way to define a container's reproducibility on each level. ''' if levels is None: levels = get_levels(version=version) hashes = dict...
get_image_hash will generate a sha1 hash of an image depending on a level of reproducibility specified by the user. ( see function get_levels for descriptions ) the user can also provide a level_filter manually with level_filter ( for custom levels ): param level: the level of reproducibility to use which maps to a set...
def get_image_hash(image_path, level=None,level_filter=None, include_files=None, skip_files=None, version=None): '''get_image_hash will generate a sha1 hash of an image, depending on a level of reproducibility specified by the user. (s...
get_content_hashes is like get_image_hash but it returns a complete dictionary of file names ( keys ) and their respective hashes ( values ). This function is intended for more research purposes and was used to generate the levels in the first place. If include_sizes is True we include a second data structure with size...
def get_content_hashes(image_path, level=None, regexp=None, include_files=None, tag_root=True, level_filter=None, skip_files=None, version=None, ...
get_image_hash will return an md5 hash of the file based on a criteria level.: param level: one of LOW MEDIUM HIGH: param image_path: full path to the singularity image
def get_image_file_hash(image_path): '''get_image_hash will return an md5 hash of the file based on a criteria level. :param level: one of LOW, MEDIUM, HIGH :param image_path: full path to the singularity image ''' hasher = hashlib.md5() with open(image_path, "rb") as f: for chunk in ite...
container_difference will return a data structure to render an html tree ( graph ) of the differences between two images or packages. The second container is subtracted from the first: param container: the primary container object ( to subtract from ): param container_subtract: the second container object to remove: pa...
def container_difference(container=None,container_subtract=None,image_package=None, image_package_subtract=None,comparison=None): '''container_difference will return a data structure to render an html tree (graph) of the differences between two images or packages. The second contai...
container_sim will return a data structure to render an html tree ( graph ) of the intersection ( commonalities ) between two images or packages: param container1: the first container object: param container2: the second container object if either not defined need: param image_package1: a packaged container1 ( produced...
def container_similarity(container1=None,container2=None,image_package1=None, image_package2=None,comparison=None): '''container_sim will return a data structure to render an html tree (graph) of the intersection (commonalities) between two images or packages :param container1: the...
tree will render an html tree ( graph ) of a container
def container_tree(container=None,image_package=None): '''tree will render an html tree (graph) of a container ''' guts = get_container_contents(container=container, image_package=image_package, split_delim="\n") # Make the tree and r...
make_container_tree will convert a list of folders and files into a json structure that represents a graph.: param folders: a list of folders in the image: param files: a list of files in the folder: param parse_files: return files lookup in result to associate ID of node with files ( default True ): param path_delim: ...
def make_container_tree(folders,files,path_delim="/",parse_files=True): '''make_container_tree will convert a list of folders and files into a json structure that represents a graph. :param folders: a list of folders in the image :param files: a list of files in the folder :param parse_files: return 'fi...
make package tree will make a dendrogram comparing a matrix of packages: param matrix: a pandas df of packages with names in index and columns: param labels: a list of labels corresponding to row names will be pulled from rows if not defined: param title: a title for the plot if not defined will be left out.: returns a...
def make_package_tree(matrix=None,labels=None,width=25,height=10,title=None,font_size=None): '''make package tree will make a dendrogram comparing a matrix of packages :param matrix: a pandas df of packages, with names in index and columns :param labels: a list of labels corresponding to row names, will be ...
make interactive tree will return complete html for an interactive tree: param title: a title for the plot if not defined will be left out.
def make_interactive_tree(matrix=None,labels=None): '''make interactive tree will return complete html for an interactive tree :param title: a title for the plot, if not defined, will be left out. ''' from scipy.cluster.hierarchy import ( dendrogram, linkage, to_tree ) ...
add_node will add a node to it s parent
def add_node(node, parent): '''add_node will add a node to it's parent ''' newNode = dict(node_id=node.id, children=[]) parent["children"].append(newNode) if node.left: add_node(node.left, newNode) if node.right: add_node(node.right, newNode)
label tree will again recursively label the tree: param n: the root node usually d3 [ children ] [ 0 ]: param lookup: the node/ id lookup
def label_tree(n,lookup): '''label tree will again recursively label the tree :param n: the root node, usually d3['children'][0] :param lookup: the node/id lookup ''' if len(n["children"]) == 0: leaves = [lookup[n["node_id"]]] else: leaves = reduce(lambda ls, c: ls + label_tree(c...
extract app will extract metadata for one or more apps Parameters ========== image: the absolute path to the image app_name: the name of the app under/ scif/ apps
def extract_apps(image, app_names): ''' extract app will extract metadata for one or more apps Parameters ========== image: the absolute path to the image app_name: the name of the app under /scif/apps ''' apps = dict() if isinstance(app_names, tuple): app_names...
run_command uses subprocess to send a command to the terminal.: param cmd: the command to send should be a list for subprocess: param error_message: the error message to give to user if fails if none specified will alert that command failed.: param sudopw: if specified ( not None ) command will be run asking for sudo
def run_command(cmd, sudo=False): '''run_command uses subprocess to send a command to the terminal. :param cmd: the command to send, should be a list for subprocess :param error_message: the error message to give to user if fails, if none specified, will alert that command failed. :param sudopw: if ...
download_repo: param repo_url: the url of the repo to clone from: param destination: the full path to the destination for the repo
def download_repo(repo_url, destination, commit=None): '''download_repo :param repo_url: the url of the repo to clone from :param destination: the full path to the destination for the repo ''' command = "git clone %s %s" % (repo_url, destination) os.system(command) return destination
get tags will return a list of tags that describe the software in an image meaning inside of a paricular folder. If search_folder is not defined uses lib: param container: if provided will use container as image. Can also provide: param image_package: if provided can be used instead of container: param search_folders: ...
def get_tags(container=None, search_folders=None, file_list=None, return_unique=True): '''get tags will return a list of tags that describe the software in an image, meaning inside of a paricular folder. If search_folder is not defined, uses lib :param container: if p...
file counts will return a list of files that match one or more regular expressions. if no patterns is defined a default of readme is used. All patterns and files are made case insensitive.
def file_counts(container=None, patterns=None, image_package=None, file_list=None): '''file counts will return a list of files that match one or more regular expressions. if no patterns is defined, a default of readme is used. All patterns and files are made ...