sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def filtered(self): """Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options""" if not is_tagged(self.tags, self.opt.tags): LOG.info("Skipping %s as it does not have requested tags", self.path) return False if not specific_path_check(self.path, self.opt): LOG.info("Skipping %s as it does not match specified paths", self.path) return False return True
Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options
entailment
def diff_write_only(resource): """A different implementation of diff that is used for those Vault resources that are write-only such as AWS root configs""" if resource.present and not resource.existing: return ADD elif not resource.present and resource.existing: return DEL elif resource.present and resource.existing: return OVERWRITE return NOOP
A different implementation of diff that is used for those Vault resources that are write-only such as AWS root configs
entailment
def read(self, client): """Read from Vault while handling non surprising errors.""" val = None if self.no_resource: return val LOG.debug("Reading from %s", self) try: val = client.read(self.path) except hvac.exceptions.InvalidRequest as vault_exception: if str(vault_exception).startswith('no handler for route'): val = None return val
Read from Vault while handling non surprising errors.
entailment
def write(self, client): """Write to Vault while handling non-surprising errors.""" val = None if not self.no_resource: val = client.write(self.path, **self.obj()) return val
Write to Vault while handling non-surprising errors.
entailment
def find_file(name, directory): """Searches up from a directory looking for a file""" path_bits = directory.split(os.sep) for i in range(0, len(path_bits) - 1): check_path = path_bits[0:len(path_bits) - i] check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name) if os.path.exists(check_file): return abspath(check_file) return None
Searches up from a directory looking for a file
entailment
def in_file(string, search_file): """Looks in a file for a string.""" handle = open(search_file, 'r') for line in handle.readlines(): if string in line: return True return False
Looks in a file for a string.
entailment
def gitignore(opt): """Will check directories upwards from the Secretfile in order to ensure the gitignore file is set properly""" directory = os.path.dirname(abspath(opt.secretfile)) gitignore_file = find_file('.gitignore', directory) if gitignore_file: secrets_path = subdir_path(abspath(opt.secrets), gitignore_file) if secrets_path: if not in_file(secrets_path, gitignore_file): e_msg = "The path %s was not found in %s" \ % (secrets_path, gitignore_file) raise aomi.exceptions.AomiFile(e_msg) else: LOG.debug("Using a non-relative secret directory") else: raise aomi.exceptions.AomiFile("You should really have a .gitignore")
Will check directories upwards from the Secretfile in order to ensure the gitignore file is set properly
entailment
def secret_file(filename): """Will check the permissions of things which really should be secret files""" filestat = os.stat(abspath(filename)) if stat.S_ISREG(filestat.st_mode) == 0 and \ stat.S_ISLNK(filestat.st_mode) == 0: e_msg = "Secret file %s must be a real file or symlink" % filename raise aomi.exceptions.AomiFile(e_msg) if platform.system() != "Windows": if filestat.st_mode & stat.S_IROTH or \ filestat.st_mode & stat.S_IWOTH or \ filestat.st_mode & stat.S_IWGRP: e_msg = "Secret file %s has too loose permissions" % filename raise aomi.exceptions.AomiFile(e_msg)
Will check the permissions of things which really should be secret files
entailment
def validate_obj(keys, obj): """Super simple "object" validation.""" msg = '' for k in keys: if isinstance(k, str): if k not in obj or (not isinstance(obj[k], list) and not obj[k]): if msg: msg = "%s," % msg msg = "%s%s" % (msg, k) elif isinstance(k, list): found = False for k_a in k: if k_a in obj: found = True if not found: if msg: msg = "%s," % msg msg = "%s(%s" % (msg, ','.join(k)) if msg: msg = "%s missing" % msg return msg
Super simple "object" validation.
entailment
def specific_path_check(path, opt): """Will make checks against include/exclude to determine if we actually care about the path in question.""" if opt.exclude: if path in opt.exclude: return False if opt.include: if path not in opt.include: return False return True
Will make checks against include/exclude to determine if we actually care about the path in question.
entailment
def check_obj(keys, name, obj): """Do basic validation on an object""" msg = validate_obj(keys, obj) if msg: raise aomi.exceptions.AomiData("object check : %s in %s" % (msg, name))
Do basic validation on an object
entailment
def sanitize_mount(mount): """Returns a quote-unquote sanitized mount path""" sanitized_mount = mount if sanitized_mount.startswith('/'): sanitized_mount = sanitized_mount[1:] if sanitized_mount.endswith('/'): sanitized_mount = sanitized_mount[:-1] sanitized_mount = sanitized_mount.replace('//', '/') return sanitized_mount
Returns a quote-unquote sanitized mount path
entailment
def gpg_fingerprint(key): """Validates a GPG key fingerprint This handles both pre and post GPG 2.1""" if (len(key) == 8 and re.match(r'^[0-9A-F]{8}$', key)) or \ (len(key) == 40 and re.match(r'^[0-9A-F]{40}$', key)): return raise aomi.exceptions.Validation('Invalid GPG Fingerprint')
Validates a GPG key fingerprint This handles both pre and post GPG 2.1
entailment
def is_unicode_string(string): """Validates that we are some kinda unicode string""" try: if sys.version_info >= (3, 0): # isn't a python 3 str actually unicode if not isinstance(string, str): string.decode('utf-8') else: string.decode('utf-8') except UnicodeError: raise aomi.exceptions.Validation('Not a unicode string')
Validates that we are some kinda unicode string
entailment
def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
Validates that the object itself is some kinda string
entailment
def safe_modulo(s, meta, checked='', print_warning=True, stacklevel=2): """Safe version of the modulo operation (%) of strings Parameters ---------- s: str string to apply the modulo operation with meta: dict or tuple meta informations to insert (usually via ``s % meta``) checked: {'KEY', 'VALUE'}, optional Security parameter for the recursive structure of this function. It can be set to 'VALUE' if an error shall be raised when facing a TypeError or ValueError or to 'KEY' if an error shall be raised when facing a KeyError. This parameter is mainly for internal processes. print_warning: bool If True and a key is not existent in `s`, a warning is raised stacklevel: int The stacklevel for the :func:`warnings.warn` function Examples -------- The effects are demonstrated by this example:: >>> from docrep import safe_modulo >>> s = "That's %(one)s string %(with)s missing 'with' and %s key" >>> s % {'one': 1} # raises KeyError because of missing 'with' Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'with' >>> s % {'one': 1, 'with': 2} # raises TypeError because of '%s' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: not enough arguments for format string >>> safe_modulo(s, {'one': 1}) "That's 1 string %(with)s missing 'with' and %s key" """ try: return s % meta except (ValueError, TypeError, KeyError): # replace the missing fields by %% keys = substitution_pattern.finditer(s) for m in keys: key = m.group('key') if not isinstance(meta, dict) or key not in meta: if print_warning: warn("%r is not a valid key!" % key, SyntaxWarning, stacklevel) full = m.group() s = s.replace(full, '%' + full) if 'KEY' not in checked: return safe_modulo(s, meta, checked=checked + 'KEY', print_warning=print_warning, stacklevel=stacklevel) if not isinstance(meta, dict) or 'VALUE' in checked: raise s = re.sub(r"""(?<!%)(%%)*%(?!%) # uneven number of % \s*(\w|$) # format strings""", '%\g<0>', s, flags=re.VERBOSE) return safe_modulo(s, meta, checked=checked + 'VALUE', print_warning=print_warning, stacklevel=stacklevel)
Safe version of the modulo operation (%) of strings Parameters ---------- s: str string to apply the modulo operation with meta: dict or tuple meta informations to insert (usually via ``s % meta``) checked: {'KEY', 'VALUE'}, optional Security parameter for the recursive structure of this function. It can be set to 'VALUE' if an error shall be raised when facing a TypeError or ValueError or to 'KEY' if an error shall be raised when facing a KeyError. This parameter is mainly for internal processes. print_warning: bool If True and a key is not existent in `s`, a warning is raised stacklevel: int The stacklevel for the :func:`warnings.warn` function Examples -------- The effects are demonstrated by this example:: >>> from docrep import safe_modulo >>> s = "That's %(one)s string %(with)s missing 'with' and %s key" >>> s % {'one': 1} # raises KeyError because of missing 'with' Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'with' >>> s % {'one': 1, 'with': 2} # raises TypeError because of '%s' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: not enough arguments for format string >>> safe_modulo(s, {'one': 1}) "That's 1 string %(with)s missing 'with' and %s key"
entailment
def get_sections(self, s, base, sections=['Parameters', 'Other Parameters']): """ Method that extracts the specified sections out of the given string if (and only if) the docstring follows the numpy documentation guidelines [1]_. Note that the section either must appear in the :attr:`param_like_sections` or the :attr:`text_sections` attribute. Parameters ---------- s: str Docstring to split base: str base to use in the :attr:`sections` attribute sections: list of str sections to look for. Each section must be followed by a newline character ('\\n') and a bar of '-' (following the numpy (napoleon) docstring conventions). Returns ------- str The replaced string References ---------- .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt See Also -------- delete_params, keep_params, delete_types, keep_types, delete_kwargs: For manipulating the docstring sections save_docstring: for saving an entire docstring """ params = self.params # Remove the summary and dedent the rest s = self._remove_summary(s) for section in sections: key = '%s.%s' % (base, section.lower().replace(' ', '_')) params[key] = self._get_section(s, section) return s
Method that extracts the specified sections out of the given string if (and only if) the docstring follows the numpy documentation guidelines [1]_. Note that the section either must appear in the :attr:`param_like_sections` or the :attr:`text_sections` attribute. Parameters ---------- s: str Docstring to split base: str base to use in the :attr:`sections` attribute sections: list of str sections to look for. Each section must be followed by a newline character ('\\n') and a bar of '-' (following the numpy (napoleon) docstring conventions). Returns ------- str The replaced string References ---------- .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt See Also -------- delete_params, keep_params, delete_types, keep_types, delete_kwargs: For manipulating the docstring sections save_docstring: for saving an entire docstring
entailment
def get_sectionsf(self, *args, **kwargs): """ Decorator method to extract sections from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_sections` method. Note, that the first argument will be the docstring of the specified function Returns ------- function Wrapper that takes a function as input and registers its sections via the :meth:`get_sections` method""" def func(f): doc = f.__doc__ self.get_sections(doc or '', *args, **kwargs) return f return func
Decorator method to extract sections from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_sections` method. Note, that the first argument will be the docstring of the specified function Returns ------- function Wrapper that takes a function as input and registers its sections via the :meth:`get_sections` method
entailment
def _set_object_doc(self, obj, doc, stacklevel=3): """Convenience method to set the __doc__ attribute of a python object """ if isinstance(obj, types.MethodType) and six.PY2: obj = obj.im_func try: obj.__doc__ = doc except AttributeError: # probably python2 class if (self.python2_classes != 'raise' and (inspect.isclass(obj) and six.PY2)): if self.python2_classes == 'warn': warn("Cannot modify docstring of classes in python2!", stacklevel=stacklevel) else: raise return obj
Convenience method to set the __doc__ attribute of a python object
entailment
def dedent(self, func): """ Dedent the docstring of a function and substitute with :attr:`params` Parameters ---------- func: function function with the documentation to dedent and whose sections shall be inserted from the :attr:`params` attribute""" doc = func.__doc__ and self.dedents(func.__doc__, stacklevel=4) return self._set_object_doc(func, doc)
Dedent the docstring of a function and substitute with :attr:`params` Parameters ---------- func: function function with the documentation to dedent and whose sections shall be inserted from the :attr:`params` attribute
entailment
def dedents(self, s, stacklevel=3): """ Dedent a string and substitute with the :attr:`params` attribute Parameters ---------- s: str string to dedent and insert the sections of the :attr:`params` attribute stacklevel: int The stacklevel for the warning raised in :func:`safe_module` when encountering an invalid key in the string""" s = dedents(s) return safe_modulo(s, self.params, stacklevel=stacklevel)
Dedent a string and substitute with the :attr:`params` attribute Parameters ---------- s: str string to dedent and insert the sections of the :attr:`params` attribute stacklevel: int The stacklevel for the warning raised in :func:`safe_module` when encountering an invalid key in the string
entailment
def with_indent(self, indent=0): """ Substitute in the docstring of a function with indented :attr:`params` Parameters ---------- indent: int The number of spaces that the substitution should be indented Returns ------- function Wrapper that takes a function as input and substitutes it's ``__doc__`` with the indented versions of :attr:`params` See Also -------- with_indents, dedent""" def replace(func): doc = func.__doc__ and self.with_indents( func.__doc__, indent=indent, stacklevel=4) return self._set_object_doc(func, doc) return replace
Substitute in the docstring of a function with indented :attr:`params` Parameters ---------- indent: int The number of spaces that the substitution should be indented Returns ------- function Wrapper that takes a function as input and substitutes it's ``__doc__`` with the indented versions of :attr:`params` See Also -------- with_indents, dedent
entailment
def with_indents(self, s, indent=0, stacklevel=3): """ Substitute a string with the indented :attr:`params` Parameters ---------- s: str The string in which to substitute indent: int The number of spaces that the substitution should be indented stacklevel: int The stacklevel for the warning raised in :func:`safe_module` when encountering an invalid key in the string Returns ------- str The substituted string See Also -------- with_indent, dedents""" # we make a new dictionary with objects that indent the original # strings if necessary. Note that the first line is not indented d = {key: _StrWithIndentation(val, indent) for key, val in six.iteritems(self.params)} return safe_modulo(s, d, stacklevel=stacklevel)
Substitute a string with the indented :attr:`params` Parameters ---------- s: str The string in which to substitute indent: int The number of spaces that the substitution should be indented stacklevel: int The stacklevel for the warning raised in :func:`safe_module` when encountering an invalid key in the string Returns ------- str The substituted string See Also -------- with_indent, dedents
entailment
def delete_params(self, base_key, *params): """ Method to delete a parameter from a parameter documentation. This method deletes the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation without the description of the param. This method works for the ``'Parameters'`` sections. The new docstring without the selected parts will be accessible as ``base_key + '.no_' + '|'.join(params)``, e.g. ``'original_key.no_param1|param2'``. See the :meth:`keep_params` method for an example. Parameters ---------- base_key: str key in the :attr:`params` dictionary ``*params`` str. Parameter identifier of which the documentations shall be deleted See Also -------- delete_types, keep_params""" self.params[ base_key + '.no_' + '|'.join(params)] = self.delete_params_s( self.params[base_key], params)
Method to delete a parameter from a parameter documentation. This method deletes the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation without the description of the param. This method works for the ``'Parameters'`` sections. The new docstring without the selected parts will be accessible as ``base_key + '.no_' + '|'.join(params)``, e.g. ``'original_key.no_param1|param2'``. See the :meth:`keep_params` method for an example. Parameters ---------- base_key: str key in the :attr:`params` dictionary ``*params`` str. Parameter identifier of which the documentations shall be deleted See Also -------- delete_types, keep_params
entailment
def delete_params_s(s, params): """ Delete the given parameters from a string Same as :meth:`delete_params` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the parameters section params: list of str The names of the parameters to delete Returns ------- str The modified string `s` without the descriptions of `params` """ patt = '(?s)' + '|'.join( '(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params) return re.sub(patt, '', '\n' + s.strip() + '\n').strip()
Delete the given parameters from a string Same as :meth:`delete_params` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the parameters section params: list of str The names of the parameters to delete Returns ------- str The modified string `s` without the descriptions of `params`
entailment
def delete_kwargs(self, base_key, args=None, kwargs=None): """ Deletes the ``*args`` or ``**kwargs`` part from the parameters section Either `args` or `kwargs` must not be None. The resulting key will be stored in ``base_key + 'no_args'`` if `args` is not None and `kwargs` is None ``base_key + 'no_kwargs'`` if `args` is None and `kwargs` is not None ``base_key + 'no_args_kwargs'`` if `args` is not None and `kwargs` is not None Parameters ---------- base_key: str The key in the :attr:`params` attribute to use args: None or str The string for the args to delete kwargs: None or str The string for the kwargs to delete Notes ----- The type name of `args` in the base has to be like ````*<args>```` (i.e. the `args` argument preceeded by a ``'*'`` and enclosed by double ``'`'``). Similarily, the type name of `kwargs` in `s` has to be like ````**<kwargs>````""" if not args and not kwargs: warn("Neither args nor kwargs are given. I do nothing for %s" % ( base_key)) return ext = '.no' + ('_args' if args else '') + ('_kwargs' if kwargs else '') self.params[base_key + ext] = self.delete_kwargs_s( self.params[base_key], args, kwargs)
Deletes the ``*args`` or ``**kwargs`` part from the parameters section Either `args` or `kwargs` must not be None. The resulting key will be stored in ``base_key + 'no_args'`` if `args` is not None and `kwargs` is None ``base_key + 'no_kwargs'`` if `args` is None and `kwargs` is not None ``base_key + 'no_args_kwargs'`` if `args` is not None and `kwargs` is not None Parameters ---------- base_key: str The key in the :attr:`params` attribute to use args: None or str The string for the args to delete kwargs: None or str The string for the kwargs to delete Notes ----- The type name of `args` in the base has to be like ````*<args>```` (i.e. the `args` argument preceeded by a ``'*'`` and enclosed by double ``'`'``). Similarily, the type name of `kwargs` in `s` has to be like ````**<kwargs>````
entailment
def delete_kwargs_s(cls, s, args=None, kwargs=None): """ Deletes the ``*args`` or ``**kwargs`` part from the parameters section Either `args` or `kwargs` must not be None. Parameters ---------- s: str The string to delete the args and kwargs from args: None or str The string for the args to delete kwargs: None or str The string for the kwargs to delete Notes ----- The type name of `args` in `s` has to be like ````*<args>```` (i.e. the `args` argument preceeded by a ``'*'`` and enclosed by double ``'`'``). Similarily, the type name of `kwargs` in `s` has to be like ````**<kwargs>````""" if not args and not kwargs: return s types = [] if args is not None: types.append('`?`?\*%s`?`?' % args) if kwargs is not None: types.append('`?`?\*\*%s`?`?' % kwargs) return cls.delete_types_s(s, types)
Deletes the ``*args`` or ``**kwargs`` part from the parameters section Either `args` or `kwargs` must not be None. Parameters ---------- s: str The string to delete the args and kwargs from args: None or str The string for the args to delete kwargs: None or str The string for the kwargs to delete Notes ----- The type name of `args` in `s` has to be like ````*<args>```` (i.e. the `args` argument preceeded by a ``'*'`` and enclosed by double ``'`'``). Similarily, the type name of `kwargs` in `s` has to be like ````**<kwargs>````
entailment
def delete_types(self, base_key, out_key, *types): """ Method to delete a parameter from a parameter documentation. This method deletes the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation without the description of the param. This method works for ``'Results'`` like sections. See the :meth:`keep_types` method for an example. Parameters ---------- base_key: str key in the :attr:`params` dictionary out_key: str Extension for the base key (the final key will be like ``'%s.%s' % (base_key, out_key)`` ``*types`` str. The type identifier of which the documentations shall deleted See Also -------- delete_params""" self.params['%s.%s' % (base_key, out_key)] = self.delete_types_s( self.params[base_key], types)
Method to delete a parameter from a parameter documentation. This method deletes the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation without the description of the param. This method works for ``'Results'`` like sections. See the :meth:`keep_types` method for an example. Parameters ---------- base_key: str key in the :attr:`params` dictionary out_key: str Extension for the base key (the final key will be like ``'%s.%s' % (base_key, out_key)`` ``*types`` str. The type identifier of which the documentations shall deleted See Also -------- delete_params
entailment
def delete_types_s(s, types): """ Delete the given types from a string Same as :meth:`delete_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str The type identifiers to delete Returns ------- str The modified string `s` without the descriptions of `types` """ patt = '(?s)' + '|'.join( '(?<=\n)' + s + '\n.+?\n(?=\S+|$)' for s in types) return re.sub(patt, '', '\n' + s.strip() + '\n',).strip()
Delete the given types from a string Same as :meth:`delete_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str The type identifiers to delete Returns ------- str The modified string `s` without the descriptions of `types`
entailment
def keep_params(self, base_key, *params): """ Method to keep only specific parameters from a parameter documentation. This method extracts the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation with only the description of the param. This method works for ``'Parameters'`` like sections. The new docstring with the selected parts will be accessible as ``base_key + '.' + '|'.join(params)``, e.g. ``'original_key.param1|param2'`` Parameters ---------- base_key: str key in the :attr:`params` dictionary ``*params`` str. Parameter identifier of which the documentations shall be in the new section See Also -------- keep_types, delete_params Examples -------- To extract just two parameters from a function and reuse their docstrings, you can type:: >>> from docrep import DocstringProcessor >>> d = DocstringProcessor() >>> @d.get_sectionsf('do_something') ... def do_something(a=1, b=2, c=3): ... ''' ... That's %(doc_key)s ... ... Parameters ... ---------- ... a: int, optional ... A dummy parameter description ... b: int, optional ... A second dummy parameter that will be excluded ... c: float, optional ... A third parameter''' ... print(a) >>> d.keep_params('do_something.parameters', 'a', 'c') >>> @d.dedent ... def do_less(a=1, c=4): ... ''' ... My second function with only `a` and `c` ... ... Parameters ... ---------- ... %(do_something.parameters.a|c)s''' ... pass >>> print(do_less.__doc__) My second function with only `a` and `c` <BLANKLINE> Parameters ---------- a: int, optional A dummy parameter description c: float, optional A third parameter Equivalently, you can use the :meth:`delete_params` method to remove parameters:: >>> d.delete_params('do_something.parameters', 'b') >>> @d.dedent ... def do_less(a=1, c=4): ... ''' ... My second function with only `a` and `c` ... ... Parameters ... ---------- ... %(do_something.parameters.no_b)s''' ... pass """ self.params[base_key + '.' + '|'.join(params)] = self.keep_params_s( self.params[base_key], params)
Method to keep only specific parameters from a parameter documentation. This method extracts the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation with only the description of the param. This method works for ``'Parameters'`` like sections. The new docstring with the selected parts will be accessible as ``base_key + '.' + '|'.join(params)``, e.g. ``'original_key.param1|param2'`` Parameters ---------- base_key: str key in the :attr:`params` dictionary ``*params`` str. Parameter identifier of which the documentations shall be in the new section See Also -------- keep_types, delete_params Examples -------- To extract just two parameters from a function and reuse their docstrings, you can type:: >>> from docrep import DocstringProcessor >>> d = DocstringProcessor() >>> @d.get_sectionsf('do_something') ... def do_something(a=1, b=2, c=3): ... ''' ... That's %(doc_key)s ... ... Parameters ... ---------- ... a: int, optional ... A dummy parameter description ... b: int, optional ... A second dummy parameter that will be excluded ... c: float, optional ... A third parameter''' ... print(a) >>> d.keep_params('do_something.parameters', 'a', 'c') >>> @d.dedent ... def do_less(a=1, c=4): ... ''' ... My second function with only `a` and `c` ... ... Parameters ... ---------- ... %(do_something.parameters.a|c)s''' ... pass >>> print(do_less.__doc__) My second function with only `a` and `c` <BLANKLINE> Parameters ---------- a: int, optional A dummy parameter description c: float, optional A third parameter Equivalently, you can use the :meth:`delete_params` method to remove parameters:: >>> d.delete_params('do_something.parameters', 'b') >>> @d.dedent ... def do_less(a=1, c=4): ... ''' ... My second function with only `a` and `c` ... ... Parameters ... ---------- ... %(do_something.parameters.no_b)s''' ... pass
entailment
def keep_params_s(s, params): """ Keep the given parameters from a string Same as :meth:`keep_params` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the parameters like section params: list of str The parameter names to keep Returns ------- str The modified string `s` with only the descriptions of `params` """ patt = '(?s)' + '|'.join( '(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params) return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip()
Keep the given parameters from a string Same as :meth:`keep_params` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the parameters like section params: list of str The parameter names to keep Returns ------- str The modified string `s` with only the descriptions of `params`
entailment
def keep_types(self, base_key, out_key, *types): """ Method to keep only specific parameters from a parameter documentation. This method extracts the given `type` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation with only the description of the type. This method works for the ``'Results'`` sections. Parameters ---------- base_key: str key in the :attr:`params` dictionary out_key: str Extension for the base key (the final key will be like ``'%s.%s' % (base_key, out_key)`` ``*types`` str. The type identifier of which the documentations shall be in the new section See Also -------- delete_types, keep_params Examples -------- To extract just two return arguments from a function and reuse their docstrings, you can type:: >>> from docrep import DocstringProcessor >>> d = DocstringProcessor() >>> @d.get_sectionsf('do_something', sections=['Returns']) ... def do_something(): ... ''' ... That's %(doc_key)s ... ... Returns ... ------- ... float ... A random number ... int ... A random integer''' ... return 1.0, 4 >>> d.keep_types('do_something.returns', 'int_only', 'int') >>> @d.dedent ... def do_less(): ... ''' ... My second function that only returns an integer ... ... Returns ... ------- ... %(do_something.returns.int_only)s''' ... return do_something()[1] >>> print(do_less.__doc__) My second function that only returns an integer <BLANKLINE> Returns ------- int A random integer Equivalently, you can use the :meth:`delete_types` method to remove parameters:: >>> d.delete_types('do_something.returns', 'no_float', 'float') >>> @d.dedent ... def do_less(): ... ''' ... My second function with only `a` and `c` ... ... Returns ... ---------- ... %(do_something.returns.no_float)s''' ... return do_something()[1] """ self.params['%s.%s' % (base_key, out_key)] = self.keep_types_s( self.params[base_key], types)
Method to keep only specific parameters from a parameter documentation. This method extracts the given `type` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation with only the description of the type. This method works for the ``'Results'`` sections. Parameters ---------- base_key: str key in the :attr:`params` dictionary out_key: str Extension for the base key (the final key will be like ``'%s.%s' % (base_key, out_key)`` ``*types`` str. The type identifier of which the documentations shall be in the new section See Also -------- delete_types, keep_params Examples -------- To extract just two return arguments from a function and reuse their docstrings, you can type:: >>> from docrep import DocstringProcessor >>> d = DocstringProcessor() >>> @d.get_sectionsf('do_something', sections=['Returns']) ... def do_something(): ... ''' ... That's %(doc_key)s ... ... Returns ... ------- ... float ... A random number ... int ... A random integer''' ... return 1.0, 4 >>> d.keep_types('do_something.returns', 'int_only', 'int') >>> @d.dedent ... def do_less(): ... ''' ... My second function that only returns an integer ... ... Returns ... ------- ... %(do_something.returns.int_only)s''' ... return do_something()[1] >>> print(do_less.__doc__) My second function that only returns an integer <BLANKLINE> Returns ------- int A random integer Equivalently, you can use the :meth:`delete_types` method to remove parameters:: >>> d.delete_types('do_something.returns', 'no_float', 'float') >>> @d.dedent ... def do_less(): ... ''' ... My second function with only `a` and `c` ... ... Returns ... ---------- ... %(do_something.returns.no_float)s''' ... return do_something()[1]
entailment
def keep_types_s(s, types): """ Keep the given types from a string Same as :meth:`keep_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str The type identifiers to keep Returns ------- str The modified string `s` with only the descriptions of `types` """ patt = '|'.join('(?<=\n)' + s + '\n(?s).+?\n(?=\S+|$)' for s in types) return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip()
Keep the given types from a string Same as :meth:`keep_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str The type identifiers to keep Returns ------- str The modified string `s` with only the descriptions of `types`
entailment
def save_docstring(self, key): """ Descriptor method to save a docstring from a function Like the :meth:`get_sectionsf` method this method serves as a descriptor for functions but saves the entire docstring""" def func(f): self.params[key] = f.__doc__ or '' return f return func
Descriptor method to save a docstring from a function Like the :meth:`get_sectionsf` method this method serves as a descriptor for functions but saves the entire docstring
entailment
def get_summary(self, s, base=None): """ Get the summary of the given docstring This method extracts the summary from the given docstring `s` which is basicly the part until two newlines appear Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.summary'``. Otherwise, it will not be stored at all Returns ------- str The extracted summary""" summary = summary_patt.search(s).group() if base is not None: self.params[base + '.summary'] = summary return summary
Get the summary of the given docstring This method extracts the summary from the given docstring `s` which is basicly the part until two newlines appear Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.summary'``. Otherwise, it will not be stored at all Returns ------- str The extracted summary
entailment
def get_summaryf(self, *args, **kwargs): """ Extract the summary from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_summary` method. Note, that the first argument will be the docstring of the specified function Returns ------- function Wrapper that takes a function as input and registers its summary via the :meth:`get_summary` method""" def func(f): doc = f.__doc__ self.get_summary(doc or '', *args, **kwargs) return f return func
Extract the summary from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_summary` method. Note, that the first argument will be the docstring of the specified function Returns ------- function Wrapper that takes a function as input and registers its summary via the :meth:`get_summary` method
entailment
def get_extended_summary(self, s, base=None): """Get the extended summary from a docstring This here is the extended summary Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.summary_ext'``. Otherwise, it will not be stored at all Returns ------- str The extracted extended summary""" # Remove the summary and dedent s = self._remove_summary(s) ret = '' if not self._all_sections_patt.match(s): m = self._extended_summary_patt.match(s) if m is not None: ret = m.group().strip() if base is not None: self.params[base + '.summary_ext'] = ret return ret
Get the extended summary from a docstring This here is the extended summary Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.summary_ext'``. Otherwise, it will not be stored at all Returns ------- str The extracted extended summary
entailment
def get_extended_summaryf(self, *args, **kwargs): """Extract the extended summary from a function docstring This function can be used as a decorator to extract the extended summary of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_extended_summary` method. Note, that the first argument will be the docstring of the specified function Returns ------- function Wrapper that takes a function as input and registers its summary via the :meth:`get_extended_summary` method""" def func(f): doc = f.__doc__ self.get_extended_summary(doc or '', *args, **kwargs) return f return func
Extract the extended summary from a function docstring This function can be used as a decorator to extract the extended summary of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_extended_summary` method. Note, that the first argument will be the docstring of the specified function Returns ------- function Wrapper that takes a function as input and registers its summary via the :meth:`get_extended_summary` method
entailment
def get_full_description(self, s, base=None): """Get the full description from a docstring This here and the line above is the full description (i.e. the combination of the :meth:`get_summary` and the :meth:`get_extended_summary`) output Parameters ---------- s: str The docstring to use base: str or None A key under which the description shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.full_desc'``. Otherwise, it will not be stored at all Returns ------- str The extracted full description""" summary = self.get_summary(s) extended_summary = self.get_extended_summary(s) ret = (summary + '\n\n' + extended_summary).strip() if base is not None: self.params[base + '.full_desc'] = ret return ret
Get the full description from a docstring This here and the line above is the full description (i.e. the combination of the :meth:`get_summary` and the :meth:`get_extended_summary`) output Parameters ---------- s: str The docstring to use base: str or None A key under which the description shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.full_desc'``. Otherwise, it will not be stored at all Returns ------- str The extracted full description
entailment
def get_full_descriptionf(self, *args, **kwargs): """Extract the full description from a function docstring This function can be used as a decorator to extract the full descriptions of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_full_description` method. Note, that the first argument will be the docstring of the specified function Returns ------- function Wrapper that takes a function as input and registers its summary via the :meth:`get_full_description` method""" def func(f): doc = f.__doc__ self.get_full_description(doc or '', *args, **kwargs) return f return func
Extract the full description from a function docstring This function can be used as a decorator to extract the full descriptions of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_full_description` method. Note, that the first argument will be the docstring of the specified function Returns ------- function Wrapper that takes a function as input and registers its summary via the :meth:`get_full_description` method
entailment
def make_mergable_if_possible(cls, data, context): """ Makes an object mergable if possible. Returns the virgin object if cannot convert it to a mergable instance. :returns: :class:`.Mergable` or type(data) """ if isinstance(data, dict): return MergableDict(data=data, context=context) elif isiterable(data): return MergableList( data=[cls.make_mergable_if_possible(i, context) for i in data], context=context ) else: return data
Makes an object mergable if possible. Returns the virgin object if cannot convert it to a mergable instance. :returns: :class:`.Mergable` or type(data)
entailment
def merge(self, *args): """ Merges this instance with new instances, in-place. :param \\*args: Configuration values to merge with current instance. :type \\*args: iterable """ for data in args: if isinstance(data, str): to_merge = load_string(data, self.context) if not to_merge: continue else: to_merge = data if not self.can_merge(to_merge): raise TypeError( 'Cannot merge myself:%s with %s. data: %s' \ % (type(self), type(data), data) ) self._merge(to_merge)
Merges this instance with new instances, in-place. :param \\*args: Configuration values to merge with current instance. :type \\*args: iterable
entailment
def load_file(self, filename): """ load file which contains yaml configuration entries.and merge it by current instance :param files: files to load and merge into existing configuration instance :type files: list """ if not path.exists(filename): raise FileNotFoundError(filename) loaded_yaml = load_yaml(filename, self.context) if loaded_yaml: self.merge(loaded_yaml)
load file which contains yaml configuration entries.and merge it by current instance :param files: files to load and merge into existing configuration instance :type files: list
entailment
def initialize(self, init_value, context=None, force=False): """ Initialize the configuration manager :param force: force initialization even if it's already initialized :return: """ if not force and self._instance is not None: raise ConfigurationAlreadyInitializedError( 'Configuration manager object is already initialized.' ) self.__class__._instance = Root(init_value, context=context)
Initialize the configuration manager :param force: force initialization even if it's already initialized :return:
entailment
def grok_filter_name(element): """Extracts the name, which may be embedded, for a Jinja2 filter node""" e_name = None if element.name == 'default': if isinstance(element.node, jinja2.nodes.Getattr): e_name = element.node.node.name else: e_name = element.node.name return e_name
Extracts the name, which may be embedded, for a Jinja2 filter node
entailment
def grok_for_node(element, default_vars): """Properly parses a For loop element""" if isinstance(element.iter, jinja2.nodes.Filter): if element.iter.name == 'default' \ and element.iter.node.name not in default_vars: default_vars.append(element.iter.node.name) default_vars = default_vars + grok_vars(element) return default_vars
Properly parses a For loop element
entailment
def grok_if_node(element, default_vars): """Properly parses a If element""" if isinstance(element.test, jinja2.nodes.Filter) and \ element.test.name == 'default': default_vars.append(element.test.node.name) return default_vars + grok_vars(element)
Properly parses a If element
entailment
def grok_vars(elements): """Returns a list of vars for which the value is being appropriately set This currently includes the default filter, for-based iterators, and the explicit use of set""" default_vars = [] iterbody = None if hasattr(elements, 'body'): iterbody = elements.body elif hasattr(elements, 'nodes'): iterbody = elements.nodes for element in iterbody: if isinstance(element, jinja2.nodes.Output): default_vars = default_vars + grok_vars(element) elif isinstance(element, jinja2.nodes.Filter): e_name = grok_filter_name(element) if e_name not in default_vars: default_vars.append(e_name) elif isinstance(element, jinja2.nodes.For): default_vars = grok_for_node(element, default_vars) elif isinstance(element, jinja2.nodes.If): default_vars = grok_if_node(element, default_vars) elif isinstance(element, jinja2.nodes.Assign): default_vars.append(element.target.name) elif isinstance(element, jinja2.nodes.FromImport): for from_var in element.names: default_vars.append(from_var) return default_vars
Returns a list of vars for which the value is being appropriately set This currently includes the default filter, for-based iterators, and the explicit use of set
entailment
def jinja_env(template_path): """Sets up our Jinja environment, loading the few filters we have""" fs_loader = FileSystemLoader(os.path.dirname(template_path)) env = Environment(loader=fs_loader, autoescape=True, trim_blocks=True, lstrip_blocks=True) env.filters['b64encode'] = portable_b64encode env.filters['b64decode'] = f_b64decode return env
Sets up our Jinja environment, loading the few filters we have
entailment
def missing_vars(template_vars, parsed_content, obj): """If we find missing variables when rendering a template we want to give the user a friendly error""" missing = [] default_vars = grok_vars(parsed_content) for var in template_vars: if var not in default_vars and var not in obj: missing.append(var) if missing: e_msg = "Missing required variables %s" % \ ','.join(missing) raise aomi_excep.AomiData(e_msg)
If we find missing variables when rendering a template we want to give the user a friendly error
entailment
def render(filename, obj): """Render a template, maybe mixing in extra variables""" template_path = abspath(filename) env = jinja_env(template_path) template_base = os.path.basename(template_path) try: parsed_content = env.parse(env .loader .get_source(env, template_base)) template_vars = meta.find_undeclared_variables(parsed_content) if template_vars: missing_vars(template_vars, parsed_content, obj) LOG.debug("rendering %s with %s vars", template_path, len(template_vars)) return env \ .get_template(template_base) \ .render(**obj) except jinja2.exceptions.TemplateSyntaxError as exception: template_trace = traceback.format_tb(sys.exc_info()[2]) # Different error context depending on whether it is the # pre-render variable scan or not if exception.filename: template_line = template_trace[len(template_trace) - 1] raise aomi_excep.Validation("Bad template %s %s" % (template_line, str(exception))) template_str = '' if isinstance(exception.source, tuple): # PyLint seems confused about whether or not this is a tuple # pylint: disable=locally-disabled, unsubscriptable-object template_str = "Embedded Template\n%s" % exception.source[0] raise aomi_excep.Validation("Bad template %s" % str(exception), source=template_str) except jinja2.exceptions.UndefinedError as exception: template_traces = [x.strip() for x in traceback.format_tb(sys.exc_info()[2]) if 'template code' in x] raise aomi_excep.Validation("Missing template variable %s" % ' '.join(template_traces))
Render a template, maybe mixing in extra variables
entailment
def load_vars(opt): """Loads variable from cli and var files, passing in cli options as a seed (although they can be overwritten!). Note, turn this into an object so it's a nicer "cache".""" if not hasattr(opt, '_vars_cache'): cli_opts = cli_hash(opt.extra_vars) setattr(opt, '_vars_cache', merge_dicts(load_var_files(opt, cli_opts), cli_opts)) return getattr(opt, '_vars_cache')
Loads variable from cli and var files, passing in cli options as a seed (although they can be overwritten!). Note, turn this into an object so it's a nicer "cache".
entailment
def load_var_files(opt, p_obj=None): """Load variable files, merge, return contents""" obj = {} if p_obj: obj = p_obj for var_file in opt.extra_vars_file: LOG.debug("loading vars from %s", var_file) obj = merge_dicts(obj.copy(), load_var_file(var_file, obj)) return obj
Load variable files, merge, return contents
entailment
def load_var_file(filename, obj): """Loads a varible file, processing it as a template""" rendered = render(filename, obj) ext = os.path.splitext(filename)[1][1:] v_obj = dict() if ext == 'json': v_obj = json.loads(rendered) elif ext == 'yaml' or ext == 'yml': v_obj = yaml.safe_load(rendered) else: LOG.warning("assuming yaml for unrecognized extension %s", ext) v_obj = yaml.safe_load(rendered) return v_obj
Loads a varible file, processing it as a template
entailment
def load_template_help(builtin): """Loads the help for a given template""" help_file = "templates/%s-help.yml" % builtin help_file = resource_filename(__name__, help_file) help_obj = {} if os.path.exists(help_file): help_data = yaml.safe_load(open(help_file)) if 'name' in help_data: help_obj['name'] = help_data['name'] if 'help' in help_data: help_obj['help'] = help_data['help'] if 'args' in help_data: help_obj['args'] = help_data['args'] return help_obj
Loads the help for a given template
entailment
def builtin_list(): """Show a listing of all our builtin templates""" for template in resource_listdir(__name__, "templates"): builtin, ext = os.path.splitext(os.path.basename(abspath(template))) if ext == '.yml': continue help_obj = load_template_help(builtin) if 'name' in help_obj: print("%-*s %s" % (20, builtin, help_obj['name'])) else: print("%s" % builtin)
Show a listing of all our builtin templates
entailment
def builtin_info(builtin): """Show information on a particular builtin template""" help_obj = load_template_help(builtin) if help_obj.get('name') and help_obj.get('help'): print("The %s template" % (help_obj['name'])) print(help_obj['help']) else: print("No help for %s" % builtin) if help_obj.get('args'): for arg, arg_help in iteritems(help_obj['args']): print(" %-*s %s" % (20, arg, arg_help))
Show information on a particular builtin template
entailment
def render_secretfile(opt): """Renders and returns the Secretfile construct""" LOG.debug("Using Secretfile %s", opt.secretfile) secretfile_path = abspath(opt.secretfile) obj = load_vars(opt) return render(secretfile_path, obj)
Renders and returns the Secretfile construct
entailment
def update_user_password(client, userpass): """Will update the password for a userpass user""" vault_path = '' user = '' user_path_bits = userpass.split('/') if len(user_path_bits) == 1: user = user_path_bits[0] vault_path = "auth/userpass/users/%s/password" % user LOG.debug("Updating password for user %s at the default path", user) elif len(user_path_bits) == 2: mount = user_path_bits[0] user = user_path_bits[1] vault_path = "auth/%s/users/%s/password" % (mount, user) LOG.debug("Updating password for user %s at path %s", user, mount) else: client.revoke_self_token() raise aomi.exceptions.AomiCommand("invalid user path") new_password = get_password() obj = { 'user': user, 'password': new_password } client.write(vault_path, **obj)
Will update the password for a userpass user
entailment
def update_generic_password(client, path): """Will update a single key in a generic secret backend as thought it were a password""" vault_path, key = path_pieces(path) mount = mount_for_path(vault_path, client) if not mount: client.revoke_self_token() raise aomi.exceptions.VaultConstraint('invalid path') if backend_type(mount, client) != 'generic': client.revoke_self_token() raise aomi.exceptions.AomiData("Unsupported backend type") LOG.debug("Updating generic password at %s", path) existing = client.read(vault_path) if not existing or 'data' not in existing: LOG.debug("Nothing exists yet at %s!", vault_path) existing = {} else: LOG.debug("Updating %s at %s", key, vault_path) existing = existing['data'] new_password = get_password() if key in existing and existing[key] == new_password: client.revoke_self_token() raise aomi.exceptions.AomiData("Password is same as existing") existing[key] = new_password client.write(vault_path, **existing)
Will update a single key in a generic secret backend as thought it were a password
entailment
def password(client, path): """Will attempt to contextually update a password in Vault""" if path.startswith('user:'): update_user_password(client, path[5:]) else: update_generic_password(client, path)
Will attempt to contextually update a password in Vault
entailment
def vault_file(env, default): """The path to a misc Vault file This function will check for the env override on a file path, compute a fully qualified OS appropriate path to the desired file and return it if it exists. Otherwise returns None """ home = os.environ['HOME'] if 'HOME' in os.environ else \ os.environ['USERPROFILE'] filename = os.environ.get(env, os.path.join(home, default)) filename = abspath(filename) if os.path.exists(filename): return filename return None
The path to a misc Vault file This function will check for the env override on a file path, compute a fully qualified OS appropriate path to the desired file and return it if it exists. Otherwise returns None
entailment
def vault_time_to_s(time_string): """Will convert a time string, as recognized by other Vault tooling, into an integer representation of seconds""" if not time_string or len(time_string) < 2: raise aomi.exceptions \ .AomiData("Invalid timestring %s" % time_string) last_char = time_string[len(time_string) - 1] if last_char == 's': return int(time_string[0:len(time_string) - 1]) elif last_char == 'm': cur = int(time_string[0:len(time_string) - 1]) return cur * 60 elif last_char == 'h': cur = int(time_string[0:len(time_string) - 1]) return cur * 3600 elif last_char == 'd': cur = int(time_string[0:len(time_string) - 1]) return cur * 86400 else: raise aomi.exceptions \ .AomiData("Invalid time scale %s" % last_char)
Will convert a time string, as recognized by other Vault tooling, into an integer representation of seconds
entailment
def run(*args, **kwargs): """Execute a command. Command can be passed as several arguments, each being a string or a list of strings; lists are flattened. If opts.verbose is True, output of the command is shown. If the command exits with non-zero, print an error message and exit. If keyward argument get_output is True, output is returned. Additionally, non-zero exit code with empty output is ignored. """ capture = kwargs.get("get_output", False) args = [arg for arglist in args for arg in (arglist if isinstance(arglist, list) else [arglist])] if opts.verbose: print("Running {}".format(" ".join(args))) live_output = opts.verbose and not capture runner = subprocess.check_call if live_output else subprocess.check_output try: output = runner(args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exception: if capture and not exception.output.strip(): # Ignore errors if output is empty. return "" if not live_output: sys.stdout.write(exception.output.decode(default_encoding, "ignore")) sys.exit("Error: got exitcode {} from command {}".format( exception.returncode, " ".join(args))) except OSError: sys.exit("Error: couldn't run {}: is {} in PATH?".format(" ".join(args), args[0])) if opts.verbose and capture: sys.stdout.write(output.decode(default_encoding, "ignore")) return capture and output.decode(default_encoding, "ignore").strip()
Execute a command. Command can be passed as several arguments, each being a string or a list of strings; lists are flattened. If opts.verbose is True, output of the command is shown. If the command exits with non-zero, print an error message and exit. If keyward argument get_output is True, output is returned. Additionally, non-zero exit code with empty output is ignored.
entailment
def set_executing(on: bool): """ Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing a step file. """ my_thread = threading.current_thread() if isinstance(my_thread, threads.CauldronThread): my_thread.is_executing = on
Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing a step file.
entailment
def get_file_contents(source_path: str) -> str: """ Loads the contents of the source into a string for execution using multiple loading methods to handle cross-platform encoding edge cases. If none of the load methods work, a string is returned that contains an error function response that will be displayed when the step is run alert the user to the error. :param source_path: Path of the step file to load. """ open_funcs = [ functools.partial(codecs.open, source_path, encoding='utf-8'), functools.partial(open, source_path, 'r') ] for open_func in open_funcs: try: with open_func() as f: return f.read() except Exception: pass return ( 'raise IOError("Unable to load step file at: {}")' .format(source_path) )
Loads the contents of the source into a string for execution using multiple loading methods to handle cross-platform encoding edge cases. If none of the load methods work, a string is returned that contains an error function response that will be displayed when the step is run alert the user to the error. :param source_path: Path of the step file to load.
entailment
def load_step_file(source_path: str) -> str: """ Loads the source for a step file at the given path location and then renders it in a template to add additional footer data. The footer is used to force the display to flush the print buffer and breathe the step to open things up for resolution. This shouldn't be necessary, but it seems there's an async race condition with print buffers that is hard to reproduce and so this is in place to fix the problem. """ return templating.render_template( template_name='embedded-step.py.txt', source_contents=get_file_contents(source_path) )
Loads the source for a step file at the given path location and then renders it in a template to add additional footer data. The footer is used to force the display to flush the print buffer and breathe the step to open things up for resolution. This shouldn't be necessary, but it seems there's an async race condition with print buffers that is hard to reproduce and so this is in place to fix the problem.
entailment
def create_module( project: 'projects.Project', step: 'projects.ProjectStep' ): """ Creates an artificial module that will encompass the code execution for the specified step. The target module is populated with the standard dunder attributes like __file__ to simulate the normal way that Python populates values when loading a module. :param project: The currently open project. :param step: The step whose code will be run inside the target_module. :return The created and populated module for the given step. """ module_name = step.definition.name.rsplit('.', 1)[0] target_module = types.ModuleType(module_name) dunders = dict( __file__=step.source_path, __package__='.'.join( [project.id.replace('.', '-')] + step.filename.rsplit('.', 1)[0].split(os.sep) ) ) for key, value in dunders.items(): setattr(target_module, key, value) return target_module
Creates an artificial module that will encompass the code execution for the specified step. The target module is populated with the standard dunder attributes like __file__ to simulate the normal way that Python populates values when loading a module. :param project: The currently open project. :param step: The step whose code will be run inside the target_module. :return The created and populated module for the given step.
entailment
def run( project: 'projects.Project', step: 'projects.ProjectStep', ) -> dict: """ Carries out the execution of the step python source file by loading it into an artificially created module and then executing that module and returning the result. :param project: The currently open project. :param step: The project step for which the run execution will take place. :return: A dictionary containing the results of the run execution, which indicate whether or not the run was successful. If the run failed for any reason, the dictionary will contain error information for display. """ target_module = create_module(project, step) source_code = load_step_file(step.source_path) try: code = InspectLoader.source_to_code(source_code, step.source_path) except SyntaxError as error: return render_syntax_error(project, error) def exec_test(): step.test_locals = dict() step.test_locals.update(target_module.__dict__) exec(code, step.test_locals) try: set_executing(True) threads.abort_thread() if environ.modes.has(environ.modes.TESTING): exec_test() else: exec(code, target_module.__dict__) out = { 'success': True, 'stop_condition': projects.StopCondition(False, False) } except threads.ThreadAbortError: # Raised when a user explicitly aborts the running of the step through # a user-interface action. out = { 'success': False, 'stop_condition': projects.StopCondition(True, True) } except UserAbortError as error: # Raised when a user explicitly aborts the running of the step using # a cd.step.stop(). This behavior should be considered a successful # outcome as it was intentional on the part of the user that the step # abort running early. out = { 'success': True, 'stop_condition': projects.StopCondition(True, error.halt) } except Exception as error: out = render_error(project, error) set_executing(False) return out
Carries out the execution of the step python source file by loading it into an artificially created module and then executing that module and returning the result. :param project: The currently open project. :param step: The project step for which the run execution will take place. :return: A dictionary containing the results of the run execution, which indicate whether or not the run was successful. If the run failed for any reason, the dictionary will contain error information for display.
entailment
def render_syntax_error( project: 'projects.Project', error: SyntaxError ) -> dict: """ Renders a SyntaxError, which has a shallow, custom stack trace derived from the data included in the error, instead of the standard stack trace pulled from the exception frames. :param project: Currently open project. :param error: The SyntaxError to be rendered to html and text for display. :return: A dictionary containing the error response with rendered display messages for both text and html output. """ return render_error( project=project, error=error, stack=[dict( filename=getattr(error, 'filename'), location=None, line_number=error.lineno, line=error.text.rstrip() )] )
Renders a SyntaxError, which has a shallow, custom stack trace derived from the data included in the error, instead of the standard stack trace pulled from the exception frames. :param project: Currently open project. :param error: The SyntaxError to be rendered to html and text for display. :return: A dictionary containing the error response with rendered display messages for both text and html output.
entailment
def render_error( project: 'projects.Project', error: Exception, stack: typing.List[dict] = None ) -> dict: """ Renders an Exception to an error response that includes rendered text and html error messages for display. :param project: Currently open project. :param error: The SyntaxError to be rendered to html and text for display. :param stack: Optionally specify a parsed stack. If this value is None the standard Cauldron stack frames will be rendered. :return: A dictionary containing the error response with rendered display messages for both text and html output. """ data = dict( type=error.__class__.__name__, message='{}'.format(error), stack=( stack if stack is not None else render_stack.get_formatted_stack_frame(project) ) ) return dict( success=False, error=error, message=templating.render_template('user-code-error.txt', **data), html_message=templating.render_template('user-code-error.html', **data) )
Renders an Exception to an error response that includes rendered text and html error messages for display. :param project: Currently open project. :param error: The SyntaxError to be rendered to html and text for display. :param stack: Optionally specify a parsed stack. If this value is None the standard Cauldron stack frames will be rendered. :return: A dictionary containing the error response with rendered display messages for both text and html output.
entailment
def execute(asynchronous: bool = False): """ :param asynchronous: Whether or not to allow asynchronous command execution that returns before the command is complete with a run_uid that can be used to track the continued execution of the command until completion. """ r = Response() r.update(server=server_runner.get_server_data()) cmd, args = parse_command_args(r) if r.failed: return flask.jsonify(r.serialize()) try: commander.execute(cmd, args, r) if not r.thread: return flask.jsonify(r.serialize()) if not asynchronous: r.thread.join() server_runner.active_execution_responses[r.thread.uid] = r # Watch the thread for a bit to see if the command finishes in # that time. If it does the command result will be returned directly # to the caller. Otherwise, a waiting command will be issued count = 0 while count < 5: count += 1 r.thread.join(0.25) if not r.thread.is_alive(): break if r.thread.is_alive(): return flask.jsonify( Response() .update( run_log=r.get_thread_log(), run_status='running', run_uid=r.thread.uid, step_changes=server_runner.get_running_step_changes(True), server=server_runner.get_server_data() ) .serialize() ) del server_runner.active_execution_responses[r.thread.uid] r.update( run_log=r.get_thread_log(), run_status='complete', run_multiple_updates=False, run_uid=r.thread.uid ) except Exception as err: r.fail( code='KERNEL_EXECUTION_FAILURE', message='Unable to execute command', cmd=cmd, args=args, error=err ) return flask.jsonify(r.serialize())
:param asynchronous: Whether or not to allow asynchronous command execution that returns before the command is complete with a run_uid that can be used to track the continued execution of the command until completion.
entailment
def abort(): """...""" uid_list = list(server_runner.active_execution_responses.keys()) while len(uid_list) > 0: uid = uid_list.pop() response = server_runner.active_execution_responses.get(uid) if not response: continue try: del server_runner.active_execution_responses[uid] except Exception: pass if not response.thread or not response.thread.is_alive(): continue # Try to stop the thread gracefully response.thread.abort = True response.thread.join(2) try: # Force stop the thread explicitly if response.thread.is_alive(): response.thread.abort_running() except Exception: pass project = cd.project.internal_project if project and project.current_step: step = project.current_step if step.is_running: step.is_running = False step.progress = 0 step.progress_message = None step.dumps() # Make sure this is called prior to printing response information to # the console or that will come along for the ride redirection.disable(step) # Make sure no print redirection will survive the abort process regardless # of whether an active step was found or not (prevents race conditions) redirection.restore_default_configuration() project_data = project.kernel_serialize() if project else None return flask.jsonify( Response() .update(project=project_data) .serialize() )
...
entailment
def remove_key(key: str, persists: bool = True): """ Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param persists: """ environ.configs.remove(key, include_persists=persists) environ.configs.save() environ.log( '[REMOVED]: "{}" from configuration settings'.format(key) )
Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param persists:
entailment
def set_key(key: str, value: typing.List[str], persists: bool = True): """ Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param value: :param persists: """ if key.endswith('_path') or key.endswith('_paths'): for index in range(len(value)): value[index] = environ.paths.clean(value[index]) if len(value) == 1: value = value[0] environ.configs.put(**{key: value}, persists=persists) environ.configs.save() environ.log('[SET]: "{}" to "{}"'.format(key, value))
Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param value: :param persists:
entailment
def save(self) -> 'Configuration': """ Saves the configuration settings object to the current user's home directory :return: """ data = self.load().persistent if data is None: return self directory = os.path.dirname(self._source_path) if not os.path.exists(directory): os.makedirs(directory) path = self._source_path with open(path, 'w+') as f: json.dump(data, f) return self
Saves the configuration settings object to the current user's home directory :return:
entailment
def _get_userinfo(self): """ Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields. """ if not hasattr(self, "_userinfo"): userinfo = { "name": self.user_name, "email": self.user_email, "url": self.user_url } if self.user_id: u = self.user if u.email: userinfo["email"] = u.email # If the user has a full name, use that for the user name. # However, a given user_name overrides the raw user.username, # so only use that if this comment has no associated name. if u.get_full_name(): userinfo["name"] = self.user.get_full_name() elif not self.user_name: userinfo["name"] = u.get_username() self._userinfo = userinfo return self._userinfo
Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields.
entailment
def get_as_text(self): """ Return this comment as plain text. Useful for emails. """ d = { 'user': self.user or self.name, 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url() } return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d
Return this comment as plain text. Useful for emails.
entailment
def entry_from_dict( data: dict ) -> typing.Union[FILE_WRITE_ENTRY, FILE_COPY_ENTRY]: """ Converts the given data dictionary into either a file write or file copy entry depending on the keys in the dictionary. The dictionary should contain either ('path', 'contents') keys for file write entries or ('source', 'destination') keys for file copy entries. """ if 'contents' in data: return FILE_WRITE_ENTRY(**data) return FILE_COPY_ENTRY(**data)
Converts the given data dictionary into either a file write or file copy entry depending on the keys in the dictionary. The dictionary should contain either ('path', 'contents') keys for file write entries or ('source', 'destination') keys for file copy entries.
entailment
def deploy(files_list: typing.List[tuple]): """ Iterates through the specified files_list and copies or writes each entry depending on whether its a file copy entry or a file write entry. :param files_list: A list of file write entries and file copy entries """ def deploy_entry(entry): if not entry: return if hasattr(entry, 'source') and hasattr(entry, 'destination'): return copy(entry) if hasattr(entry, 'path') and hasattr(entry, 'contents'): return write(entry) raise ValueError('Unrecognized deployment entry {}'.format(entry)) return [deploy_entry(f) for f in files_list]
Iterates through the specified files_list and copies or writes each entry depending on whether its a file copy entry or a file write entry. :param files_list: A list of file write entries and file copy entries
entailment
def make_output_directory(output_path: str) -> str: """ Creates the parent directory or directories for the specified output path if they do not already exist to prevent incomplete directory path errors during copying/writing operations. :param output_path: The path of the destination file or directory that will be written. :return: The absolute path to the output directory that was created if missing or already existed. """ output_directory = os.path.dirname(environ.paths.clean(output_path)) if not os.path.exists(output_directory): os.makedirs(output_directory) return output_directory
Creates the parent directory or directories for the specified output path if they do not already exist to prevent incomplete directory path errors during copying/writing operations. :param output_path: The path of the destination file or directory that will be written. :return: The absolute path to the output directory that was created if missing or already existed.
entailment
def copy(copy_entry: FILE_COPY_ENTRY): """ Copies the specified file from its source location to its destination location. """ source_path = environ.paths.clean(copy_entry.source) output_path = environ.paths.clean(copy_entry.destination) copier = shutil.copy2 if os.path.isfile(source_path) else shutil.copytree make_output_directory(output_path) for i in range(3): try: copier(source_path, output_path) return except Exception: time.sleep(0.5) raise IOError('Unable to copy "{source}" to "{destination}"'.format( source=source_path, destination=output_path ))
Copies the specified file from its source location to its destination location.
entailment
def write(write_entry: FILE_WRITE_ENTRY): """ Writes the contents of the specified file entry to its destination path. """ output_path = environ.paths.clean(write_entry.path) make_output_directory(output_path) writer.write_file(output_path, write_entry.contents)
Writes the contents of the specified file entry to its destination path.
entailment
def enable(step: 'projects.ProjectStep'): """ Create a print equivalent function that also writes the output to the project page. The write_through is enabled so that the TextIOWrapper immediately writes all of its input data directly to the underlying BytesIO buffer. This is needed so that we can safely access the buffer data in a multi-threaded environment to display updates while the buffer is being written to. :param step: """ # Prevent anything unusual from causing buffer issues restore_default_configuration() stdout_interceptor = RedirectBuffer(sys.stdout) sys.stdout = stdout_interceptor step.report.stdout_interceptor = stdout_interceptor stderr_interceptor = RedirectBuffer(sys.stderr) sys.stderr = stderr_interceptor step.report.stderr_interceptor = stderr_interceptor stdout_interceptor.active = True stderr_interceptor.active = True
Create a print equivalent function that also writes the output to the project page. The write_through is enabled so that the TextIOWrapper immediately writes all of its input data directly to the underlying BytesIO buffer. This is needed so that we can safely access the buffer data in a multi-threaded environment to display updates while the buffer is being written to. :param step:
entailment
def restore_default_configuration(): """ Restores the sys.stdout and the sys.stderr buffer streams to their default values without regard to what step has currently overridden their values. This is useful during cleanup outside of the running execution block """ def restore(target, default_value): if target == default_value: return default_value if not isinstance(target, RedirectBuffer): return target try: target.active = False target.close() except Exception: pass return default_value sys.stdout = restore(sys.stdout, sys.__stdout__) sys.stderr = restore(sys.stderr, sys.__stderr__)
Restores the sys.stdout and the sys.stderr buffer streams to their default values without regard to what step has currently overridden their values. This is useful during cleanup outside of the running execution block
entailment
def create( project: 'projects.Project', destination_directory, destination_filename: str = None ) -> file_io.FILE_WRITE_ENTRY: """ Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given project that will be saved in the destination directory with the given filename. :param project: The project for which the rendered HTML file will be created :param destination_directory: The absolute path to the folder where the HTML file will be saved :param destination_filename: The name of the HTML file to be written in the destination directory. Defaults to the project uuid. :return: A FILE_WRITE_ENTRY for the project's HTML file output """ template_path = environ.paths.resources('web', 'project.html') with open(template_path, 'r') as f: dom = f.read() dom = dom.replace( '<!-- CAULDRON:EXPORT -->', templating.render_template( 'notebook-script-header.html', uuid=project.uuid, version=environ.version ) ) filename = ( destination_filename if destination_filename else '{}.html'.format(project.uuid) ) html_out_path = os.path.join(destination_directory, filename) return file_io.FILE_WRITE_ENTRY( path=html_out_path, contents=dom )
Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given project that will be saved in the destination directory with the given filename. :param project: The project for which the rendered HTML file will be created :param destination_directory: The absolute path to the folder where the HTML file will be saved :param destination_filename: The name of the HTML file to be written in the destination directory. Defaults to the project uuid. :return: A FILE_WRITE_ENTRY for the project's HTML file output
entailment
def run_container(): """Runs an interactive container""" os.chdir(my_directory) cmd = [ 'docker', 'run', '-it', '--rm', '-v', '{}:/cauldron'.format(my_directory), '-p', '5010:5010', 'cauldron_app', '/bin/bash' ] return os.system(' '.join(cmd))
Runs an interactive container
entailment
def run(): """Execute the Cauldron container command""" command = sys.argv[1].strip().lower() print('[COMMAND]:', command) if command == 'test': return run_test() elif command == 'build': return run_build() elif command == 'up': return run_container() elif command == 'serve': import cauldron cauldron.run_server(port=5010, public=True)
Execute the Cauldron container command
entailment
def gatekeeper(func): """ This function is used to handle authorization code authentication of protected endpoints. This form of authentication is not recommended because it's not very secure, but can be used in places where SSH tunneling or similar strong connection security is not possible. The function looks for a special "Cauldron-Authentication-Code" header in the request and confirms that the specified value matches the code that was provided by arguments to the Cauldron kernel server. This function acts as a pass-through if no code is specified when the server starts. """ @wraps(func) def check_identity(*args, **kwargs): code = server_runner.authorization['code'] comparison = request.headers.get('Cauldron-Authentication-Code') return ( abort(401) if code and code != comparison else func(*args, **kwargs) ) return check_identity
This function is used to handle authorization code authentication of protected endpoints. This form of authentication is not recommended because it's not very secure, but can be used in places where SSH tunneling or similar strong connection security is not possible. The function looks for a special "Cauldron-Authentication-Code" header in the request and confirms that the specified value matches the code that was provided by arguments to the Cauldron kernel server. This function acts as a pass-through if no code is specified when the server starts.
entailment
def inspect(source: dict): """ Inspects the data and structure of the source dictionary object and adds the results to the display for viewing. :param source: A dictionary object to be inspected. :return: """ r = _get_report() r.append_body(render.inspect(source))
Inspects the data and structure of the source dictionary object and adds the results to the display for viewing. :param source: A dictionary object to be inspected. :return:
entailment
def header(header_text: str, level: int = 1, expand_full: bool = False): """ Adds a text header to the display with the specified level. :param header_text: The text to display in the header. :param level: The level of the header, which corresponds to the html header levels, such as <h1>, <h2>, ... :param expand_full: Whether or not the header will expand to fill the width of the entire notebook page, or be constrained by automatic maximum page width. The default value of False lines the header up with text displays. """ r = _get_report() r.append_body(render.header( header_text, level=level, expand_full=expand_full ))
Adds a text header to the display with the specified level. :param header_text: The text to display in the header. :param level: The level of the header, which corresponds to the html header levels, such as <h1>, <h2>, ... :param expand_full: Whether or not the header will expand to fill the width of the entire notebook page, or be constrained by automatic maximum page width. The default value of False lines the header up with text displays.
entailment
def text(value: str, preformatted: bool = False): """ Adds text to the display. If the text is not preformatted, it will be displayed in paragraph format. Preformatted text will be displayed inside a pre tag with a monospace font. :param value: The text to display. :param preformatted: Whether or not to preserve the whitespace display of the text. """ if preformatted: result = render_texts.preformatted_text(value) else: result = render_texts.text(value) r = _get_report() r.append_body(result) r.stdout_interceptor.write_source( '{}\n'.format(textwrap.dedent(value)) )
Adds text to the display. If the text is not preformatted, it will be displayed in paragraph format. Preformatted text will be displayed inside a pre tag with a monospace font. :param value: The text to display. :param preformatted: Whether or not to preserve the whitespace display of the text.
entailment
def markdown( source: str = None, source_path: str = None, preserve_lines: bool = False, font_size: float = None, **kwargs ): """ Renders the specified source string or source file using markdown and adds the resulting HTML to the notebook display. :param source: A markdown formatted string. :param source_path: A file containing markdown text. :param preserve_lines: If True, all line breaks will be treated as hard breaks. Use this for pre-formatted markdown text where newlines should be retained during rendering. :param font_size: Specifies a relative font size adjustment. The default value is 1.0, which preserves the inherited font size values. Set it to a value below 1.0 for smaller font-size rendering and greater than 1.0 for larger font size rendering. :param kwargs: Any variable replacements to make within the string using Jinja2 templating syntax. """ r = _get_report() result = render_texts.markdown( source=source, source_path=source_path, preserve_lines=preserve_lines, font_size=font_size, **kwargs ) r.library_includes += result['library_includes'] r.append_body(result['body']) r.stdout_interceptor.write_source( '{}\n'.format(textwrap.dedent(result['rendered'])) )
Renders the specified source string or source file using markdown and adds the resulting HTML to the notebook display. :param source: A markdown formatted string. :param source_path: A file containing markdown text. :param preserve_lines: If True, all line breaks will be treated as hard breaks. Use this for pre-formatted markdown text where newlines should be retained during rendering. :param font_size: Specifies a relative font size adjustment. The default value is 1.0, which preserves the inherited font size values. Set it to a value below 1.0 for smaller font-size rendering and greater than 1.0 for larger font size rendering. :param kwargs: Any variable replacements to make within the string using Jinja2 templating syntax.
entailment
def json(**kwargs): """ Adds the specified data to the the output display window with the specified key. This allows the user to make available arbitrary JSON-compatible data to the display for runtime use. :param kwargs: Each keyword argument is added to the CD.data object with the specified key and value. """ r = _get_report() r.append_body(render.json(**kwargs)) r.stdout_interceptor.write_source( '{}\n'.format(_json_io.dumps(kwargs, indent=2)) )
Adds the specified data to the the output display window with the specified key. This allows the user to make available arbitrary JSON-compatible data to the display for runtime use. :param kwargs: Each keyword argument is added to the CD.data object with the specified key and value.
entailment
def plotly( data: typing.Union[dict, list] = None, layout: dict = None, scale: float = 0.5, figure: dict = None, static: bool = False ): """ Creates a Plotly plot in the display with the specified data and layout. :param data: The Plotly trace data to be plotted. :param layout: The layout data used for the plot. :param scale: The display scale with units of fractional screen height. A value of 0.5 constrains the output to a maximum height equal to half the height of browser window when viewed. Values below 1.0 are usually recommended so the entire output can be viewed without scrolling. :param figure: In cases where you need to create a figure instead of separate data and layout information, you can pass the figure here and leave the data and layout values as None. :param static: If true, the plot will be created without interactivity. This is useful if you have a lot of plots in your notebook. """ r = _get_report() if not figure and not isinstance(data, (list, tuple)): data = [data] if 'plotly' not in r.library_includes: r.library_includes.append('plotly') r.append_body(render.plotly( data=data, layout=layout, scale=scale, figure=figure, static=static )) r.stdout_interceptor.write_source('[ADDED] Plotly plot\n')
Creates a Plotly plot in the display with the specified data and layout. :param data: The Plotly trace data to be plotted. :param layout: The layout data used for the plot. :param scale: The display scale with units of fractional screen height. A value of 0.5 constrains the output to a maximum height equal to half the height of browser window when viewed. Values below 1.0 are usually recommended so the entire output can be viewed without scrolling. :param figure: In cases where you need to create a figure instead of separate data and layout information, you can pass the figure here and leave the data and layout values as None. :param static: If true, the plot will be created without interactivity. This is useful if you have a lot of plots in your notebook.
entailment
def table( data_frame, scale: float = 0.7, include_index: bool = False, max_rows: int = 500 ): """ Adds the specified data frame to the display in a nicely formatted scrolling table. :param data_frame: The pandas data frame to be rendered to a table. :param scale: The display scale with units of fractional screen height. A value of 0.5 constrains the output to a maximum height equal to half the height of browser window when viewed. Values below 1.0 are usually recommended so the entire output can be viewed without scrolling. :param include_index: Whether or not the index column should be included in the displayed output. The index column is not included by default because it is often unnecessary extra information in the display of the data. :param max_rows: This argument exists to prevent accidentally writing very large data frames to a table, which can cause the notebook display to become sluggish or unresponsive. If you want to display large tables, you need only increase the value of this argument. """ r = _get_report() r.append_body(render.table( data_frame=data_frame, scale=scale, include_index=include_index, max_rows=max_rows )) r.stdout_interceptor.write_source('[ADDED] Table\n')
Adds the specified data frame to the display in a nicely formatted scrolling table. :param data_frame: The pandas data frame to be rendered to a table. :param scale: The display scale with units of fractional screen height. A value of 0.5 constrains the output to a maximum height equal to half the height of browser window when viewed. Values below 1.0 are usually recommended so the entire output can be viewed without scrolling. :param include_index: Whether or not the index column should be included in the displayed output. The index column is not included by default because it is often unnecessary extra information in the display of the data. :param max_rows: This argument exists to prevent accidentally writing very large data frames to a table, which can cause the notebook display to become sluggish or unresponsive. If you want to display large tables, you need only increase the value of this argument.
entailment
def svg(svg_dom: str, filename: str = None): """ Adds the specified SVG string to the display. If a filename is included, the SVG data will also be saved to that filename within the project results folder. :param svg_dom: The SVG string data to add to the display. :param filename: An optional filename where the SVG data should be saved within the project results folder. """ r = _get_report() r.append_body(render.svg(svg_dom)) r.stdout_interceptor.write_source('[ADDED] SVG\n') if not filename: return if not filename.endswith('.svg'): filename += '.svg' r.files[filename] = svg_dom
Adds the specified SVG string to the display. If a filename is included, the SVG data will also be saved to that filename within the project results folder. :param svg_dom: The SVG string data to add to the display. :param filename: An optional filename where the SVG data should be saved within the project results folder.
entailment
def jinja(path: str, **kwargs): """ Renders the specified Jinja2 template to HTML and adds the output to the display. :param path: The fully-qualified path to the template to be rendered. :param kwargs: Any keyword arguments that will be use as variable replacements within the template. """ r = _get_report() r.append_body(render.jinja(path, **kwargs)) r.stdout_interceptor.write_source('[ADDED] Jinja2 rendered HTML\n')
Renders the specified Jinja2 template to HTML and adds the output to the display. :param path: The fully-qualified path to the template to be rendered. :param kwargs: Any keyword arguments that will be use as variable replacements within the template.
entailment
def whitespace(lines: float = 1.0): """ Adds the specified number of lines of whitespace. :param lines: The number of lines of whitespace to show. """ r = _get_report() r.append_body(render.whitespace(lines)) r.stdout_interceptor.write_source('\n')
Adds the specified number of lines of whitespace. :param lines: The number of lines of whitespace to show.
entailment
def image( filename: str, width: int = None, height: int = None, justify: str = 'left' ): """ Adds an image to the display. The image must be located within the assets directory of the Cauldron notebook's folder. :param filename: Name of the file within the assets directory, :param width: Optional width in pixels for the image. :param height: Optional height in pixels for the image. :param justify: One of 'left', 'center' or 'right', which specifies how the image is horizontally justified within the notebook display. """ r = _get_report() path = '/'.join(['reports', r.project.uuid, 'latest', 'assets', filename]) r.append_body(render.image(path, width, height, justify)) r.stdout_interceptor.write_source('[ADDED] Image\n')
Adds an image to the display. The image must be located within the assets directory of the Cauldron notebook's folder. :param filename: Name of the file within the assets directory, :param width: Optional width in pixels for the image. :param height: Optional height in pixels for the image. :param justify: One of 'left', 'center' or 'right', which specifies how the image is horizontally justified within the notebook display.
entailment