Search is not available for this dataset
text
stringlengths
75
104k
def _product_file_hash(self, product=None): """ Get the hash of the each product file """ if self.hasher is None: return None else: products = self._rectify_products(product) product_file_hash = [ util_hash.hash_file(p, hasher=s...
def expired(self, cfgstr=None, product=None): """ Check to see if a previously existing stamp is still valid and if the expected result of that computation still exists. Args: cfgstr (str, optional): override the default cfgstr if specified product (PathLike or S...
def renew(self, cfgstr=None, product=None): """ Recertify that the product has been recomputed by writing a new certificate to disk. """ products = self._rectify_products(product) certificate = { 'timestamp': util_time.timestamp(), 'product': produ...
def isatty(self): # nocover """ Returns true of the redirect is a terminal. Notes: Needed for IPython.embed to work properly when this class is used to override stdout / stderr. """ return (self.redirect is not None and hasattr(self.redir...
def encoding(self): """ Gets the encoding of the `redirect` IO object Doctest: >>> redirect = io.StringIO() >>> assert TeeStringIO(redirect).encoding is None >>> assert TeeStringIO(None).encoding is None >>> assert TeeStringIO(sys.stdout).encoding...
def write(self, msg): """ Write to this and the redirected stream """ if self.redirect is not None: self.redirect.write(msg) if six.PY2: from xdoctest.utils.util_str import ensure_unicode msg = ensure_unicode(msg) super(TeeStringIO, sel...
def flush(self): # nocover """ Flush to this and the redirected stream """ if self.redirect is not None: self.redirect.flush() super(TeeStringIO, self).flush()
def log_part(self): """ Log what has been captured so far """ self.cap_stdout.seek(self._pos) text = self.cap_stdout.read() self._pos = self.cap_stdout.tell() self.parts.append(text) self.text = text
def stop(self): """ Doctest: >>> CaptureStdout(enabled=False).stop() >>> CaptureStdout(enabled=True).stop() """ if self.enabled: self.started = False sys.stdout = self.orig_stdout
def platform_data_dir(): """ Returns path for user-specific data files Returns: PathLike : path to the data dir used by the current operating system """ if LINUX: # nocover dpath_ = os.environ.get('XDG_DATA_HOME', '~/.local/share') elif DARWIN: # nocover dpath_ = '~/L...
def platform_config_dir(): """ Returns a directory which should be writable for any application This should be used for persistent configuration files. Returns: PathLike : path to the cahce dir used by the current operating system """ if LINUX: # nocover dpath_ = os.environ.get...
def ensure_app_data_dir(appname, *args): """ Calls `get_app_data_dir` but ensures the directory exists. Args: appname (str): the name of the application *args: any other subdirectories may be specified SeeAlso: get_app_data_dir Example: >>> import ubelt as ub ...
def ensure_app_config_dir(appname, *args): """ Calls `get_app_config_dir` but ensures the directory exists. Args: appname (str): the name of the application *args: any other subdirectories may be specified SeeAlso: get_app_config_dir Example: >>> import ubelt as ub...
def ensure_app_cache_dir(appname, *args): """ Calls `get_app_cache_dir` but ensures the directory exists. Args: appname (str): the name of the application *args: any other subdirectories may be specified SeeAlso: get_app_cache_dir Example: >>> import ubelt as ub ...
def startfile(fpath, verbose=True): # nocover """ Uses default program defined by the system to open a file. This is done via `os.startfile` on windows, `open` on mac, and `xdg-open` on linux. Args: fpath (PathLike): a file to open using the program associated with the files ex...
def find_exe(name, multi=False, path=None): """ Locate a command. Search your local filesystem for an executable and return the first matching file with executable permission. Args: name (str): globstr of matching filename multi (bool): if True return all matches instead of just t...
def find_path(name, path=None, exact=False): """ Search for a file or directory on your local filesystem by name (file must be in a directory specified in a PATH environment variable) Args: fname (PathLike or str): file name to match. If exact is False this may be a glob pattern ...
def editfile(fpath, verbose=True): # nocover """ DEPRICATED: This has been ported to xdev, please use that version. Opens a file or code corresponding to a live python object in your preferred visual editor. This function is mainly useful in an interactive IPython session. The visual editor i...
def augpath(path, suffix='', prefix='', ext=None, base=None, multidot=False): """ Augments a path with a new basename, extension, prefix and/or suffix. A prefix is inserted before the basename. A suffix is inserted between the basename and the extension. The basename and extension can be replaced w...
def userhome(username=None): """ Returns the user's home directory. If `username` is None, this is the directory for the current user. Args: username (str): name of a user on the system Returns: PathLike: userhome_dpath: path to the home directory Example: >>> import g...
def compressuser(path, home='~'): """ Inverse of `os.path.expanduser` Args: path (PathLike): path in system file structure home (str): symbol used to replace the home path. Defaults to '~', but you might want to use '$HOME' or '%USERPROFILE%' instead. Returns: PathL...
def truepath(path, real=False): """ Normalizes a string representation of a path and does shell-like expansion. Args: path (PathLike): string representation of a path real (bool): if True, all symbolic links are followed. (default: False) Returns: PathLike : normalized path ...
def ensuredir(dpath, mode=0o1777, verbose=None): r""" Ensures that directory will exist. Creates new dir with sticky bits by default Args: dpath (PathLike): dir to ensure. Can also be a tuple to send to join mode (int): octal mode of directory (default 0o1777) verbose (int): ver...
def parse_version(package): """ Statically parse the version number from __init__.py CommandLine: python -c "import setup; print(setup.parse_version('ubelt'))" """ from os.path import dirname, join, exists import ast # Check if the package is a single-file or multi-file package ...
def parse_description(): """ Parse the description in the README file CommandLine: pandoc --from=markdown --to=rst --output=README.rst README.md python -c "import setup; print(setup.parse_description())" """ from os.path import dirname, join, exists readme_fpath = join(dirname(_...
def parse_requirements_alt(fname='requirements.txt'): """ pip install requirements-parser fname='requirements.txt' """ import requirements from os.path import dirname, join, exists require_fpath = join(dirname(__file__), fname) if exists(require_fpath): # Dont use until this hand...
def parse_requirements(fname='requirements.txt'): """ Parse the package dependencies listed in a requirements file but strips specific versioning information. TODO: perhaps use https://github.com/davidfischer/requirements-parser instead CommandLine: python -c "import setup; print(s...
def inject_method(self, func, name=None): """ Injects a function into an object instance as a bound method The main use case of this function is for monkey patching. While monkey patching is sometimes necessary it should generally be avoided. Thus, we simply remind the developer that there might be...
def writeto(fpath, to_write, aslines=False, verbose=None): r""" Writes (utf8) text to a file. Args: fpath (PathLike): file path to_write (str): text to write (must be unicode text) aslines (bool): if True to_write is assumed to be a list of lines verbose (bool): verbosity fl...
def readfrom(fpath, aslines=False, errors='replace', verbose=None): """ Reads (utf8) text from a file. Args: fpath (PathLike): file path aslines (bool): if True returns list of lines verbose (bool): verbosity flag Returns: str: text from fpath (this is unicode) """ ...
def touch(fpath, mode=0o666, dir_fd=None, verbose=0, **kwargs): """ change file timestamps Works like the touch unix utility Args: fpath (PathLike): name of the file mode (int): file permissions (python3 and unix only) dir_fd (file): optional directory file descriptor. If speci...
def delete(path, verbose=False): """ Removes a file or recursively removes a directory. If a path does not exist, then this is does nothing. Args: path (PathLike): file or directory to remove verbose (bool): if True prints what is being done SeeAlso: send2trash - A cross-pl...
def repr2(data, **kwargs): """ Makes a pretty and easy-to-doctest string representation! This is an alternative to repr, and `pprint.pformat` that attempts to be both more configurable and generate output that is consistent between python versions. Notes: This function has many keyword...
def _format_list(list_, **kwargs): """ Makes a pretty printable / human-readable string representation of a sequence. In most cases this string could be evaled. Args: list_ (list): input list **kwargs: nl, newlines, packed, nobr, nobraces, itemsep, trailing_sep, strvals inde...
def _format_dict(dict_, **kwargs): """ Makes a pretty printable / human-readable string representation of a dictionary. In most cases this string could be evaled. Args: dict_ (dict): a dictionary **kwargs: si, stritems, strkeys, strvals, sk, sv, nl, newlines, nobr, no...
def _join_itemstrs(itemstrs, itemsep, newlines, _leaf_info, nobraces, trailing_sep, compact_brace, lbr, rbr): """ Joins string-ified items with separators newlines and container-braces. """ # positive newlines means start counting from the root use_newline = newlines > 0 # ne...
def _dict_itemstrs(dict_, **kwargs): """ Create a string representation for each item in a dict. Example: >>> from ubelt.util_format import * >>> dict_ = {'b': .1, 'l': 'st', 'g': 1.0, 's': 10, 'm': 0.9, 'w': .5} >>> kwargs = {'strkeys': True} >>> itemstrs, _ = _dict_itemst...
def _list_itemstrs(list_, **kwargs): """ Create a string representation for each item in a list. """ items = list(list_) kwargs['_return_info'] = True _tups = [repr2(item, **kwargs) for item in items] itemstrs = [t[0] for t in _tups] max_height = max([t[1]['max_height'] for t in _tups]) ...
def _sort_itemstrs(items, itemstrs): """ Equivalent to `sorted(items)` except if `items` are unorderable, then string values are used to define an ordering. """ # First try to sort items by their normal values # If that doesnt work, then sort by their string values import ubelt as ub try...
def _rectify_countdown_or_bool(count_or_bool): """ used by recursive functions to specify which level to turn a bool on in counting down yields True, True, ..., False counting up yields False, False, False, ... True Args: count_or_bool (bool or int): if positive and an integer, it will coun...
def register(self, type): """ Registers a custom formatting function with ub.repr2 """ def _decorator(func): if isinstance(type, tuple): for t in type: self.func_registry[t] = func else: self.func_registry[type] ...
def lookup(self, data): """ Returns an appropriate function to format `data` if one has been registered. """ for func in self.lazy_init: func() for type, func in self.func_registry.items(): if isinstance(data, type): return func
def _register_numpy_extensions(self): """ CommandLine: python -m ubelt.util_format FormatterExtensions._register_numpy_extensions Example: >>> import sys >>> import pytest >>> import ubelt as ub >>> if not ub.modname_to_modpath('numpy'...
def _rectify_hasher(hasher): """ Convert a string-based key into a hasher class Notes: In terms of speed on 64bit systems, sha1 is the fastest followed by md5 and sha512. The slowest algorithm is sha256. If xxhash is installed the fastest algorithm is xxh64. Example: >>...
def _rectify_base(base): """ transforms base shorthand into the full list representation Example: >>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET >>> assert _rectify_base('hex') is _ALPHABET_16 >>> assert _rectify_base('abc') is _ALPHABET_26 >>> assert _rectify_base(10...
def _hashable_sequence(data, types=True): r""" Extracts the sequence of bytes that would be hashed by hash_data Example: >>> data = [2, (3, 4)] >>> result1 = (b''.join(_hashable_sequence(data, types=False))) >>> result2 = (b''.join(_hashable_sequence(data, types=True))) >>> ...
def _convert_to_hashable(data, types=True): r""" Converts `data` into a hashable byte representation if an appropriate hashing function is known. Args: data (object): ordered data with structure types (bool): include type prefixes in the hash Returns: tuple(bytes, bytes): p...
def _update_hasher(hasher, data, types=True): """ Converts `data` into a byte representation and calls update on the hasher `hashlib.HASH` algorithm. Args: hasher (HASH): instance of a hashlib algorithm data (object): ordered data with structure types (bool): include type prefix...
def _convert_hexstr_base(hexstr, base): r""" Packs a long hexstr into a shorter length string with a larger base. Args: hexstr (str): string of hexidecimal symbols to convert base (list): symbols of the conversion base Example: >>> print(_convert_hexstr_base('ffffffff', _ALPHAB...
def _digest_hasher(hasher, hashlen, base): """ counterpart to _update_hasher """ # Get a 128 character hex string hex_text = hasher.hexdigest() # Shorten length of string (by increasing base) base_text = _convert_hexstr_base(hex_text, base) # Truncate text = base_text[:hashlen] return te...
def hash_data(data, hasher=NoParam, base=NoParam, types=False, hashlen=NoParam, convert=False): """ Get a unique hash depending on the state of the data. Args: data (object): Any sort of loosely organized data hasher (str or HASHER): Hash algorithm fro...
def hash_file(fpath, blocksize=65536, stride=1, hasher=NoParam, hashlen=NoParam, base=NoParam): """ Hashes the data in a file on disk. Args: fpath (PathLike): file path string blocksize (int): 2 ** 16. Affects speed of reading file stride (int): strides > 1 skip dat...
def register(self, hash_types): """ Registers a function to generate a hash for data of the appropriate types. This can be used to register custom classes. Internally this is used to define how to hash non-builtin objects like ndarrays and uuids. The registered function should r...
def lookup(self, data): """ Returns an appropriate function to hash `data` if one has been registered. Raises: TypeError : if data has no registered hash methods Example: >>> import ubelt as ub >>> import pytest >>> if not ub.modn...
def _register_numpy_extensions(self): """ Numpy extensions are builtin """ # system checks import numpy as np numpy_floating_types = (np.float16, np.float32, np.float64) if hasattr(np, 'float128'): # nocover numpy_floating_types = numpy_floating_types...
def _register_builtin_class_extensions(self): """ Register hashing extensions for a selection of classes included in python stdlib. Example: >>> data = uuid.UUID('7e9d206b-dc02-4240-8bdb-fffe858121d0') >>> print(hash_data(data, base='abc', hasher='sha512', types=...
def _textio_iterlines(stream): """ Iterates over lines in a TextIO stream until an EOF is encountered. This is the iterator version of stream.readlines() """ line = stream.readline() while line != '': yield line line = stream.readline()
def _proc_async_iter_stream(proc, stream, buffersize=1): """ Reads output from a process in a separate thread """ from six.moves import queue from threading import Thread def enqueue_output(proc, stream, stream_queue): while proc.poll() is None: line = stream.readline() ...
def _proc_iteroutput_thread(proc): """ Iterates over output from a process line by line Note: WARNING. Current implementation might have bugs with other threads. This behavior was seen when using earlier versions of tqdm. I'm not sure if this was our bug or tqdm's. Newer versions of...
def _proc_iteroutput_select(proc): """ Iterates over output from a process line by line UNIX only. Use `_proc_iteroutput_thread` instead for a cross platform solution based on threads. Yields: Tuple[str, str]: oline, eline: stdout and stderr line """ from six.moves import zip_longe...
def _tee_output(make_proc, stdout=None, stderr=None, backend='auto'): """ Simultaneously reports and captures stdout and stderr from a process subprocess must be created using (stdout=subprocess.PIPE, stderr=subprocess.PIPE) """ logged_out = [] logged_err = [] if backend == 'auto': ...
def cmd(command, shell=False, detach=False, verbose=0, tee=None, cwd=None, env=None, tee_backend='auto', verbout=None, **kwargs): """ Executes a command in a subprocess. The advantage of this wrapper around subprocess is that (1) you control if the subprocess prints to stdout, (2) the text ...
def timestamp(method='iso8601'): """ make an iso8601 timestamp Args: method (str): type of timestamp Example: >>> stamp = timestamp() >>> print('stamp = {!r}'.format(stamp)) stamp = ...-...-...T... """ if method == 'iso8601': # ISO 8601 # datetim...
def benchmark_hash_data(): """ CommandLine: python ~/code/ubelt/dev/bench_hash.py --convert=True --show python ~/code/ubelt/dev/bench_hash.py --convert=False --show """ import ubelt as ub #ITEM = 'JUST A STRING' * 100 ITEM = [0, 1, 'a', 'b', ['JUST A STRING'] * 4] HASHERS = [...
def import_module_from_path(modpath, index=-1): """ Imports a module via its path Args: modpath (PathLike): path to the module on disk or within a zipfile. Returns: module: the imported module References: https://stackoverflow.com/questions/67631/import-module-given-path ...
def import_module_from_name(modname): """ Imports a module from its string name (__name__) Args: modname (str): module name Returns: module: module Example: >>> # test with modules that wont be imported in normal circumstances >>> # todo write a test where we gaur...
def _extension_module_tags(): """ Returns valid tags an extension module might have """ import sysconfig tags = [] if six.PY2: # see also 'SHLIB_EXT' multiarch = sysconfig.get_config_var('MULTIARCH') if multiarch is not None: tags.append(multiarch) else: ...
def _platform_pylib_exts(): # nocover """ Returns .so, .pyd, or .dylib depending on linux, win or mac. On python3 return the previous with and without abi (e.g. .cpython-35m-x86_64-linux-gnu) flags. On python2 returns with and without multiarch. """ import sysconfig valid_exts = [] ...
def _syspath_modname_to_modpath(modname, sys_path=None, exclude=None): """ syspath version of modname_to_modpath Args: modname (str): name of module to find sys_path (List[PathLike], default=None): if specified overrides `sys.path` exclude (List[PathLike], default=None):...
def modname_to_modpath(modname, hide_init=True, hide_main=False, sys_path=None): """ Finds the path to a python module from its name. Determines the path to a python module without directly import it Converts the name of a module (__name__) to the path (__file__) where it is located without import...
def normalize_modpath(modpath, hide_init=True, hide_main=False): """ Normalizes __init__ and __main__ paths. Notes: Adds __init__ if reasonable, but only removes __main__ by default Args: hide_init (bool): if True, always return package modules as __init__.py files otherwise...
def modpath_to_modname(modpath, hide_init=True, hide_main=False, check=True, relativeto=None): """ Determines importable name from file path Converts the path to a module (__file__) to the importable python name (__name__) without importing the module. The filename is conver...
def split_modpath(modpath, check=True): """ Splits the modpath into the dir that must be in PYTHONPATH for the module to be imported and the modulepath relative to this directory. Args: modpath (str): module filepath check (bool): if False, does not raise an error if modpath is a ...
def argval(key, default=util_const.NoParam, argv=None): """ Get the value of a keyword argument specified on the command line. Values can be specified as `<key> <value>` or `<key>=<value>` Args: key (str or tuple): string or tuple of strings. Each key should be prefixed with two hy...
def argflag(key, argv=None): """ Determines if a key is specified on the command line Args: key (str or tuple): string or tuple of strings. Each key should be prefixed with two hyphens (i.e. `--`) argv (Optional[list]): overrides `sys.argv` if specified Returns: boo...
def hzcat(args, sep=''): """ Horizontally concatenates strings preserving indentation Concatenates a list of objects ensuring that the next item in the list is all the way to the right of any previous items. Args: args (List[str]): strings to concatenate sep (str): separator (defau...
def ensure_unicode(text): r""" Casts bytes into utf8 (mostly for python2 compatibility) References: http://stackoverflow.com/questions/12561063/extract-data-from-file Example: >>> from ubelt.util_str import * >>> import codecs # NOQA >>> assert ensure_unicode('my ünicô...
def symlink(real_path, link_path, overwrite=False, verbose=0): """ Create a symbolic link. This will work on linux or windows, however windows does have some corner cases. For more details see notes in `ubelt._win32_links`. Args: path (PathLike): path to real file or directory link...
def _dirstats(dpath=None): # nocover """ Testing helper for printing directory information (mostly for investigating windows weirdness) CommandLine: python -m ubelt.util_links _dirstats """ from ubelt import util_colors if dpath is None: dpath = os.getcwd() print('=====...
def _make_signature_key(args, kwargs): """ Transforms function args into a key that can be used by the cache CommandLine: xdoctest -m ubelt.util_memoize _make_signature_key Example: >>> args = (4, [1, 2]) >>> kwargs = {'a': 'b'} >>> key = _make_signature_key(args, kwarg...
def memoize(func): """ memoization decorator that respects args and kwargs References: https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize Args: func (Callable): live python function Returns: func: memoized wrapper CommandLine: xdoctest -m ubelt.util_m...
def memoize_property(fget): """ Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. This decorator can either be used by itself or by decoratin...
def highlight_code(text, lexer_name='python', **kwargs): """ Highlights a block of text using ANSI tags based on language syntax. Args: text (str): plain text to highlight lexer_name (str): name of language **kwargs: passed to pygments.lexers.get_lexer_by_name Returns: ...
def color_text(text, color): r""" Colorizes text a single color using ansii tags. Args: text (str): text to colorize color (str): may be one of the following: yellow, blink, lightgray, underline, darkyellow, blue, darkblue, faint, fuchsia, black, white, red, brown, t...
def iterable(obj, strok=False): """ Checks if the input implements the iterator interface. An exception is made for strings, which return False unless `strok` is True Args: obj (object): a scalar or iterable input strok (bool): if True allow strings to be interpreted as iterable R...
def unique(items, key=None): """ Generates unique items in the order they appear. Args: items (Iterable): list of items key (Callable, optional): custom normalization function. If specified returns items where `key(item)` is unique. Yields: object: a unique item fr...
def argunique(items, key=None): """ Returns indices corresponding to the first instance of each unique item. Args: items (Sequence): indexable collection of items key (Callable, optional): custom normalization function. If specified returns items where `key(item)` is unique. ...
def unique_flags(items, key=None): """ Returns a list of booleans corresponding to the first instance of each unique item. Args: items (Sequence): indexable collection of items key (Callable, optional): custom normalization function. If specified returns items where `key(it...
def boolmask(indices, maxval=None): """ Constructs a list of booleans where an item is True if its position is in `indices` otherwise it is False. Args: indices (list): list of integer indices maxval (int): length of the returned list. If not specified this is inferred from...
def allsame(iterable, eq=operator.eq): """ Determine if all items in a sequence are the same Args: iterable (Iterable): items to determine if they are all the same eq (Callable, optional): function to determine equality (default: operator.eq) Example: >>> allsame([...
def argsort(indexable, key=None, reverse=False): """ Returns the indices that would sort a indexable object. This is similar to `numpy.argsort`, but it is written in pure python and works on both lists and dictionaries. Args: indexable (Iterable or Mapping): indexable to sort by k...
def argmax(indexable, key=None): """ Returns index / key of the item with the largest value. This is similar to `numpy.argmax`, but it is written in pure python and works on both lists and dictionaries. Args: indexable (Iterable or Mapping): indexable to sort by key (Callable, opt...
def argmin(indexable, key=None): """ Returns index / key of the item with the smallest value. This is similar to `numpy.argmin`, but it is written in pure python and works on both lists and dictionaries. Args: indexable (Iterable or Mapping): indexable to sort by key (Callable, op...
def dzip(items1, items2, cls=dict): """ Zips elementwise pairs between items1 and items2 into a dictionary. Values from items2 can be broadcast onto items1. Args: items1 (Iterable): full sequence items2 (Iterable): can either be a sequence of one item or a sequence of equal ...
def group_items(items, groupids): r""" Groups a list of items by group id. Args: items (Iterable): a list of items to group groupids (Iterable or Callable): a corresponding list of item groupids or a function mapping an item to a groupid. Returns: dict: groupid_to_i...
def dict_hist(item_list, weight_list=None, ordered=False, labels=None): """ Builds a histogram of items, counting the number of time each item appears in the input. Args: item_list (Iterable): hashable items (usually containing duplicates) weight_list (Iterable): corresponding weights f...
def find_duplicates(items, k=2, key=None): """ Find all duplicate items in a list. Search for all items that appear more than `k` times and return a mapping from each (k)-duplicate item to the positions it appeared in. Args: items (Iterable): hashable items possibly containing duplicates ...
def dict_take(dict_, keys, default=util_const.NoParam): r""" Generates values from a dictionary Args: dict_ (Mapping): a dictionary to take from keys (Iterable): the keys to take default (object, optional): if specified uses default if keys are missing CommandLine: pyth...
def dict_union(*args): """ Combines the disjoint keys in multiple dictionaries. For intersecting keys, dictionaries towards the end of the sequence are given precedence. Args: *args : a sequence of dictionaries Returns: Dict | OrderedDict : OrderedDict if the first argu...
def dict_isect(*args): """ Constructs a dictionary that contains keys common between all inputs. The returned values will only belong to the first dictionary. Args: *args : a sequence of dictionaries (or sets of keys) Returns: Dict | OrderedDict : OrderedDict if the fir...