partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
valid | CacheStamp._product_file_hash | Get the hash of the each product file | ubelt/util_cache.py | 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 _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... | [
"Get",
"the",
"hash",
"of",
"the",
"each",
"product",
"file"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L579-L591 | [
"def",
"_product_file_hash",
"(",
"self",
",",
"product",
"=",
"None",
")",
":",
"if",
"self",
".",
"hasher",
"is",
"None",
":",
"return",
"None",
"else",
":",
"products",
"=",
"self",
".",
"_rectify_products",
"(",
"product",
")",
"product_file_hash",
"="... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | CacheStamp.expired | 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 Sequence[PathLike], optional): override the
default... | ubelt/util_cache.py | 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 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... | [
"Check",
"to",
"see",
"if",
"a",
"previously",
"existing",
"stamp",
"is",
"still",
"valid",
"and",
"if",
"the",
"expected",
"result",
"of",
"that",
"computation",
"still",
"exists",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L593-L620 | [
"def",
"expired",
"(",
"self",
",",
"cfgstr",
"=",
"None",
",",
"product",
"=",
"None",
")",
":",
"products",
"=",
"self",
".",
"_rectify_products",
"(",
"product",
")",
"certificate",
"=",
"self",
".",
"_get_certificate",
"(",
"cfgstr",
"=",
"cfgstr",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | CacheStamp.renew | Recertify that the product has been recomputed by writing a new
certificate to disk. | ubelt/util_cache.py | 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 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... | [
"Recertify",
"that",
"the",
"product",
"has",
"been",
"recomputed",
"by",
"writing",
"a",
"new",
"certificate",
"to",
"disk",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cache.py#L622-L638 | [
"def",
"renew",
"(",
"self",
",",
"cfgstr",
"=",
"None",
",",
"product",
"=",
"None",
")",
":",
"products",
"=",
"self",
".",
"_rectify_products",
"(",
"product",
")",
"certificate",
"=",
"{",
"'timestamp'",
":",
"util_time",
".",
"timestamp",
"(",
")",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | TeeStringIO.isatty | 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. | ubelt/util_stream.py | 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 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... | [
"Returns",
"true",
"of",
"the",
"redirect",
"is",
"a",
"terminal",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L28-L37 | [
"def",
"isatty",
"(",
"self",
")",
":",
"# nocover",
"return",
"(",
"self",
".",
"redirect",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"self",
".",
"redirect",
",",
"'isatty'",
")",
"and",
"self",
".",
"redirect",
".",
"isatty",
"(",
")",
")"
] | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | TeeStringIO.encoding | 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 is sys.stdout.encoding
>>> ... | ubelt/util_stream.py | 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 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... | [
"Gets",
"the",
"encoding",
"of",
"the",
"redirect",
"IO",
"object"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L40-L55 | [
"def",
"encoding",
"(",
"self",
")",
":",
"if",
"self",
".",
"redirect",
"is",
"not",
"None",
":",
"return",
"self",
".",
"redirect",
".",
"encoding",
"else",
":",
"return",
"super",
"(",
"TeeStringIO",
",",
"self",
")",
".",
"encoding"
] | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | TeeStringIO.write | Write to this and the redirected stream | ubelt/util_stream.py | 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 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... | [
"Write",
"to",
"this",
"and",
"the",
"redirected",
"stream"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L57-L66 | [
"def",
"write",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"redirect",
"is",
"not",
"None",
":",
"self",
".",
"redirect",
".",
"write",
"(",
"msg",
")",
"if",
"six",
".",
"PY2",
":",
"from",
"xdoctest",
".",
"utils",
".",
"util_str",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | TeeStringIO.flush | Flush to this and the redirected stream | ubelt/util_stream.py | 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 flush(self): # nocover
"""
Flush to this and the redirected stream
"""
if self.redirect is not None:
self.redirect.flush()
super(TeeStringIO, self).flush() | [
"Flush",
"to",
"this",
"and",
"the",
"redirected",
"stream"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L68-L74 | [
"def",
"flush",
"(",
"self",
")",
":",
"# nocover",
"if",
"self",
".",
"redirect",
"is",
"not",
"None",
":",
"self",
".",
"redirect",
".",
"flush",
"(",
")",
"super",
"(",
"TeeStringIO",
",",
"self",
")",
".",
"flush",
"(",
")"
] | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | CaptureStdout.log_part | Log what has been captured so far | ubelt/util_stream.py | 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 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 | [
"Log",
"what",
"has",
"been",
"captured",
"so",
"far"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L130-L136 | [
"def",
"log_part",
"(",
"self",
")",
":",
"self",
".",
"cap_stdout",
".",
"seek",
"(",
"self",
".",
"_pos",
")",
"text",
"=",
"self",
".",
"cap_stdout",
".",
"read",
"(",
")",
"self",
".",
"_pos",
"=",
"self",
".",
"cap_stdout",
".",
"tell",
"(",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | CaptureStdout.stop | Doctest:
>>> CaptureStdout(enabled=False).stop()
>>> CaptureStdout(enabled=True).stop() | ubelt/util_stream.py | def stop(self):
"""
Doctest:
>>> CaptureStdout(enabled=False).stop()
>>> CaptureStdout(enabled=True).stop()
"""
if self.enabled:
self.started = False
sys.stdout = self.orig_stdout | def stop(self):
"""
Doctest:
>>> CaptureStdout(enabled=False).stop()
>>> CaptureStdout(enabled=True).stop()
"""
if self.enabled:
self.started = False
sys.stdout = self.orig_stdout | [
"Doctest",
":",
">>>",
"CaptureStdout",
"(",
"enabled",
"=",
"False",
")",
".",
"stop",
"()",
">>>",
"CaptureStdout",
"(",
"enabled",
"=",
"True",
")",
".",
"stop",
"()"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_stream.py#L144-L152 | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"enabled",
":",
"self",
".",
"started",
"=",
"False",
"sys",
".",
"stdout",
"=",
"self",
".",
"orig_stdout"
] | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | platform_data_dir | Returns path for user-specific data files
Returns:
PathLike : path to the data dir used by the current operating system | ubelt/util_platform.py | 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_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... | [
"Returns",
"path",
"for",
"user",
"-",
"specific",
"data",
"files"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L47-L63 | [
"def",
"platform_data_dir",
"(",
")",
":",
"if",
"LINUX",
":",
"# nocover",
"dpath_",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_DATA_HOME'",
",",
"'~/.local/share'",
")",
"elif",
"DARWIN",
":",
"# nocover",
"dpath_",
"=",
"'~/Library/Application Support'... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | 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 | ubelt/util_platform.py | 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 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... | [
"Returns",
"a",
"directory",
"which",
"should",
"be",
"writable",
"for",
"any",
"application",
"This",
"should",
"be",
"used",
"for",
"persistent",
"configuration",
"files",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L66-L83 | [
"def",
"platform_config_dir",
"(",
")",
":",
"if",
"LINUX",
":",
"# nocover",
"dpath_",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
",",
"'~/.config'",
")",
"elif",
"DARWIN",
":",
"# nocover",
"dpath_",
"=",
"'~/Library/Application Support'"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | ensure_app_data_dir | 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
>>> dpath = ub.ensure_app_data_dir('ubelt')
... | ubelt/util_platform.py | 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_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
... | [
"Calls",
"get_app_data_dir",
"but",
"ensures",
"the",
"directory",
"exists",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L127-L146 | [
"def",
"ensure_app_data_dir",
"(",
"appname",
",",
"*",
"args",
")",
":",
"from",
"ubelt",
"import",
"util_path",
"dpath",
"=",
"get_app_data_dir",
"(",
"appname",
",",
"*",
"args",
")",
"util_path",
".",
"ensuredir",
"(",
"dpath",
")",
"return",
"dpath"
] | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | ensure_app_config_dir | 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
>>> dpath = ub.ensure_app_config_dir('ubelt')
... | ubelt/util_platform.py | 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_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... | [
"Calls",
"get_app_config_dir",
"but",
"ensures",
"the",
"directory",
"exists",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L168-L187 | [
"def",
"ensure_app_config_dir",
"(",
"appname",
",",
"*",
"args",
")",
":",
"from",
"ubelt",
"import",
"util_path",
"dpath",
"=",
"get_app_config_dir",
"(",
"appname",
",",
"*",
"args",
")",
"util_path",
".",
"ensuredir",
"(",
"dpath",
")",
"return",
"dpath"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | ensure_app_cache_dir | 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
>>> dpath = ub.ensure_app_cache_dir('ubelt')
... | ubelt/util_platform.py | 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 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
... | [
"Calls",
"get_app_cache_dir",
"but",
"ensures",
"the",
"directory",
"exists",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L209-L228 | [
"def",
"ensure_app_cache_dir",
"(",
"appname",
",",
"*",
"args",
")",
":",
"from",
"ubelt",
"import",
"util_path",
"dpath",
"=",
"get_app_cache_dir",
"(",
"appname",
",",
"*",
"args",
")",
"util_path",
".",
"ensuredir",
"(",
"dpath",
")",
"return",
"dpath"
] | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | startfile | 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 extension type.
verbose (int): verbosity
Referen... | ubelt/util_platform.py | 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 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... | [
"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",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L231-L273 | [
"def",
"startfile",
"(",
"fpath",
",",
"verbose",
"=",
"True",
")",
":",
"# nocover",
"from",
"ubelt",
"import",
"util_cmd",
"if",
"verbose",
":",
"print",
"(",
"'[ubelt] startfile(\"{}\")'",
".",
"format",
"(",
"fpath",
")",
")",
"fpath",
"=",
"normpath",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | find_exe | 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 the first.
Defaults to False.
path (... | ubelt/util_platform.py | 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_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... | [
"Locate",
"a",
"command",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L276-L339 | [
"def",
"find_exe",
"(",
"name",
",",
"multi",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"candidates",
"=",
"find_path",
"(",
"name",
",",
"path",
"=",
"path",
",",
"exact",
"=",
"True",
")",
"mode",
"=",
"os",
".",
"X_OK",
"|",
"os",
".",... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | find_path | 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
path (str or Iterable[PathLike]): list of directori... | ubelt/util_platform.py | 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 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
... | [
"Search",
"for",
"a",
"file",
"or",
"directory",
"on",
"your",
"local",
"filesystem",
"by",
"name",
"(",
"file",
"must",
"be",
"in",
"a",
"directory",
"specified",
"in",
"a",
"PATH",
"environment",
"variable",
")"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L342-L390 | [
"def",
"find_path",
"(",
"name",
",",
"path",
"=",
"None",
",",
"exact",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"os",
".",
"defpath",
")",
"if",
"path",
"is",
"None",
"else",
"path",
"dpaths",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | editfile | 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 is determined by the `VISUAL` environment variable. If
... | ubelt/util_platform.py | 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 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... | [
"DEPRICATED",
":",
"This",
"has",
"been",
"ported",
"to",
"xdev",
"please",
"use",
"that",
"version",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_platform.py#L396-L438 | [
"def",
"editfile",
"(",
"fpath",
",",
"verbose",
"=",
"True",
")",
":",
"# nocover",
"from",
"six",
"import",
"types",
"from",
"ubelt",
"import",
"util_cmd",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"'Please use xdev.editfile instead'",
",",
"Deprecat... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | augpath | 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 with a new one.
Args:
path (PathLike): string representation of a path
... | ubelt/util_path.py | 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 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... | [
"Augments",
"a",
"path",
"with",
"a",
"new",
"basename",
"extension",
"prefix",
"and",
"/",
"or",
"suffix",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L26-L89 | [
"def",
"augpath",
"(",
"path",
",",
"suffix",
"=",
"''",
",",
"prefix",
"=",
"''",
",",
"ext",
"=",
"None",
",",
"base",
"=",
"None",
",",
"multidot",
"=",
"False",
")",
":",
"# Breakup path",
"dpath",
",",
"fname",
"=",
"split",
"(",
"path",
")",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | userhome | 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 getpass
>>> username = getpass.get... | ubelt/util_path.py | 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 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... | [
"Returns",
"the",
"user",
"s",
"home",
"directory",
".",
"If",
"username",
"is",
"None",
"this",
"is",
"the",
"directory",
"for",
"the",
"current",
"user",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L92-L142 | [
"def",
"userhome",
"(",
"username",
"=",
"None",
")",
":",
"if",
"username",
"is",
"None",
":",
"# get home directory for the current user",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"userhome_dpath",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"el... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | compressuser | 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:
PathLike: path: shortened path replacing the home d... | ubelt/util_path.py | 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 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... | [
"Inverse",
"of",
"os",
".",
"path",
".",
"expanduser"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L145-L175 | [
"def",
"compressuser",
"(",
"path",
",",
"home",
"=",
"'~'",
")",
":",
"path",
"=",
"normpath",
"(",
"path",
")",
"userhome_dpath",
"=",
"userhome",
"(",
")",
"if",
"path",
".",
"startswith",
"(",
"userhome_dpath",
")",
":",
"if",
"len",
"(",
"path",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | truepath | 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
Note:
This function is similar to ... | ubelt/util_path.py | 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 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
... | [
"Normalizes",
"a",
"string",
"representation",
"of",
"a",
"path",
"and",
"does",
"shell",
"-",
"like",
"expansion",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L201-L237 | [
"def",
"truepath",
"(",
"path",
",",
"real",
"=",
"False",
")",
":",
"path",
"=",
"expanduser",
"(",
"path",
")",
"path",
"=",
"expandvars",
"(",
"path",
")",
"if",
"real",
":",
"path",
"=",
"realpath",
"(",
"path",
")",
"else",
":",
"path",
"=",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | ensuredir | 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): verbosity (default 0)
Returns:
PathLike: pa... | ubelt/util_path.py | 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 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... | [
"r",
"Ensures",
"that",
"directory",
"will",
"exist",
".",
"Creates",
"new",
"dir",
"with",
"sticky",
"bits",
"by",
"default"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L240-L282 | [
"def",
"ensuredir",
"(",
"dpath",
",",
"mode",
"=",
"0o1777",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"is",
"None",
":",
"# nocover",
"verbose",
"=",
"0",
"if",
"isinstance",
"(",
"dpath",
",",
"(",
"list",
",",
"tuple",
")",
")",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | parse_version | Statically parse the version number from __init__.py
CommandLine:
python -c "import setup; print(setup.parse_version('ubelt'))" | setup.py | 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_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
... | [
"Statically",
"parse",
"the",
"version",
"number",
"from",
"__init__",
".",
"py"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/setup.py#L54-L87 | [
"def",
"parse_version",
"(",
"package",
")",
":",
"from",
"os",
".",
"path",
"import",
"dirname",
",",
"join",
",",
"exists",
"import",
"ast",
"# Check if the package is a single-file or multi-file package",
"_candiates",
"=",
"[",
"join",
"(",
"dirname",
"(",
"__... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | 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())" | setup.py | 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_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(_... | [
"Parse",
"the",
"description",
"in",
"the",
"README",
"file"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/setup.py#L90-L105 | [
"def",
"parse_description",
"(",
")",
":",
"from",
"os",
".",
"path",
"import",
"dirname",
",",
"join",
",",
"exists",
"readme_fpath",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"'README.rst'",
")",
"# This breaks on pip install, so check that it exis... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | parse_requirements_alt | pip install requirements-parser
fname='requirements.txt' | setup.py | 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_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... | [
"pip",
"install",
"requirements",
"-",
"parser",
"fname",
"=",
"requirements",
".",
"txt"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/setup.py#L108-L122 | [
"def",
"parse_requirements_alt",
"(",
"fname",
"=",
"'requirements.txt'",
")",
":",
"import",
"requirements",
"from",
"os",
".",
"path",
"import",
"dirname",
",",
"join",
",",
"exists",
"require_fpath",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | parse_requirements | 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(setup.parse_requirements())" | setup.py | 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 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... | [
"Parse",
"the",
"package",
"dependencies",
"listed",
"in",
"a",
"requirements",
"file",
"but",
"strips",
"specific",
"versioning",
"information",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/setup.py#L125-L182 | [
"def",
"parse_requirements",
"(",
"fname",
"=",
"'requirements.txt'",
")",
":",
"from",
"os",
".",
"path",
"import",
"dirname",
",",
"join",
",",
"exists",
"import",
"re",
"require_fpath",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"fname",
")... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | inject_method | 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 a better way.
Args:
self (object): insta... | ubelt/util_func.py | 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 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... | [
"Injects",
"a",
"function",
"into",
"an",
"object",
"instance",
"as",
"a",
"bound",
"method"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_func.py#L25-L58 | [
"def",
"inject_method",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
")",
":",
"# TODO: if func is a bound method we should probably unbind it",
"new_method",
"=",
"func",
".",
"__get__",
"(",
"self",
",",
"self",
".",
"__class__",
")",
"if",
"name",
"is"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | writeto | 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 flag
CommandLine:
python -m ubelt.util_io writeto --... | ubelt/util_io.py | 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 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... | [
"r",
"Writes",
"(",
"utf8",
")",
"text",
"to",
"a",
"file",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_io.py#L24-L73 | [
"def",
"writeto",
"(",
"fpath",
",",
"to_write",
",",
"aslines",
"=",
"False",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"'Writing to text file: %r '",
"%",
"(",
"fpath",
",",
")",
")",
"with",
"open",
"(",
"fpath",
","... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | readfrom | 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) | ubelt/util_io.py | 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 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)
"""
... | [
"Reads",
"(",
"utf8",
")",
"text",
"from",
"a",
"file",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_io.py#L87-L115 | [
"def",
"readfrom",
"(",
"fpath",
",",
"aslines",
"=",
"False",
",",
"errors",
"=",
"'replace'",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"'Reading text file: %r '",
"%",
"(",
"fpath",
",",
")",
")",
"if",
"not",
"exist... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | touch | 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 specified, fpath
is interpreted as relative to this descriptor (pytho... | ubelt/util_io.py | 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 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... | [
"change",
"file",
"timestamps"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_io.py#L118-L157 | [
"def",
"touch",
"(",
"fpath",
",",
"mode",
"=",
"0o666",
",",
"dir_fd",
"=",
"None",
",",
"verbose",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"'Touching file {}'",
".",
"format",
"(",
"fpath",
")",
")",
"if",... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | delete | 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-platform Python package for sending files
... | ubelt/util_io.py | 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 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... | [
"Removes",
"a",
"file",
"or",
"recursively",
"removes",
"a",
"directory",
".",
"If",
"a",
"path",
"does",
"not",
"exist",
"then",
"this",
"is",
"does",
"nothing",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_io.py#L160-L238 | [
"def",
"delete",
"(",
"path",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"# if the file does exists and is not a broken link",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
":... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | repr2 | 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 arguments that can be used to customiz... | ubelt/util_format.py | 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 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... | [
"Makes",
"a",
"pretty",
"and",
"easy",
"-",
"to",
"-",
"doctest",
"string",
"representation!"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L11-L167 | [
"def",
"repr2",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"custom_extensions",
"=",
"kwargs",
".",
"get",
"(",
"'extensions'",
",",
"None",
")",
"_return_info",
"=",
"kwargs",
".",
"get",
"(",
"'_return_info'",
",",
"False",
")",
"kwargs",
"[",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _format_list | 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 indent_, precision, use_numpy, with_dtype, force_dt... | ubelt/util_format.py | 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_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... | [
"Makes",
"a",
"pretty",
"printable",
"/",
"human",
"-",
"readable",
"string",
"representation",
"of",
"a",
"sequence",
".",
"In",
"most",
"cases",
"this",
"string",
"could",
"be",
"evaled",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L416-L480 | [
"def",
"_format_list",
"(",
"list_",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_root_info'",
"]",
"=",
"_rectify_root_info",
"(",
"kwargs",
".",
"get",
"(",
"'_root_info'",
",",
"None",
")",
")",
"kwargs",
"[",
"'_root_info'",
"]",
"[",
"'depth... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _format_dict | 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,
nobraces, cbr, compact_brace, trailing_sep,
... | ubelt/util_format.py | 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 _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... | [
"Makes",
"a",
"pretty",
"printable",
"/",
"human",
"-",
"readable",
"string",
"representation",
"of",
"a",
"dictionary",
".",
"In",
"most",
"cases",
"this",
"string",
"could",
"be",
"evaled",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L483-L544 | [
"def",
"_format_dict",
"(",
"dict_",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_root_info'",
"]",
"=",
"_rectify_root_info",
"(",
"kwargs",
".",
"get",
"(",
"'_root_info'",
",",
"None",
")",
")",
"kwargs",
"[",
"'_root_info'",
"]",
"[",
"'depth... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _join_itemstrs | Joins string-ified items with separators newlines and container-braces. | ubelt/util_format.py | 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 _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... | [
"Joins",
"string",
"-",
"ified",
"items",
"with",
"separators",
"newlines",
"and",
"container",
"-",
"braces",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L547-L595 | [
"def",
"_join_itemstrs",
"(",
"itemstrs",
",",
"itemsep",
",",
"newlines",
",",
"_leaf_info",
",",
"nobraces",
",",
"trailing_sep",
",",
"compact_brace",
",",
"lbr",
",",
"rbr",
")",
":",
"# positive newlines means start counting from the root",
"use_newline",
"=",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _dict_itemstrs | 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_itemstrs(dict_, **kwargs)
>>> char_order = [p[0... | ubelt/util_format.py | 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 _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... | [
"Create",
"a",
"string",
"representation",
"for",
"each",
"item",
"in",
"a",
"dict",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L598-L665 | [
"def",
"_dict_itemstrs",
"(",
"dict_",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"ubelt",
"as",
"ub",
"explicit",
"=",
"kwargs",
".",
"get",
"(",
"'explicit'",
",",
"False",
")",
"kwargs",
"[",
"'explicit'",
"]",
"=",
"_rectify_countdown_or_bool",
"(",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _list_itemstrs | Create a string representation for each item in a list. | ubelt/util_format.py | 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 _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]) ... | [
"Create",
"a",
"string",
"representation",
"for",
"each",
"item",
"in",
"a",
"list",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L668-L687 | [
"def",
"_list_itemstrs",
"(",
"list_",
",",
"*",
"*",
"kwargs",
")",
":",
"items",
"=",
"list",
"(",
"list_",
")",
"kwargs",
"[",
"'_return_info'",
"]",
"=",
"True",
"_tups",
"=",
"[",
"repr2",
"(",
"item",
",",
"*",
"*",
"kwargs",
")",
"for",
"ite... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _sort_itemstrs | Equivalent to `sorted(items)` except if `items` are unorderable, then
string values are used to define an ordering. | ubelt/util_format.py | 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 _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... | [
"Equivalent",
"to",
"sorted",
"(",
"items",
")",
"except",
"if",
"items",
"are",
"unorderable",
"then",
"string",
"values",
"are",
"used",
"to",
"define",
"an",
"ordering",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L690-L706 | [
"def",
"_sort_itemstrs",
"(",
"items",
",",
"itemstrs",
")",
":",
"# First try to sort items by their normal values",
"# If that doesnt work, then sort by their string values",
"import",
"ubelt",
"as",
"ub",
"try",
":",
"# Set ordering is not unique. Sort by strings values instead.",... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _rectify_countdown_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 count
down, otherwise it will remain the same.
... | ubelt/util_format.py | 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 _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... | [
"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"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L713-L756 | [
"def",
"_rectify_countdown_or_bool",
"(",
"count_or_bool",
")",
":",
"if",
"count_or_bool",
"is",
"True",
"or",
"count_or_bool",
"is",
"False",
":",
"count_or_bool_",
"=",
"count_or_bool",
"elif",
"isinstance",
"(",
"count_or_bool",
",",
"int",
")",
":",
"if",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | FormatterExtensions.register | Registers a custom formatting function with ub.repr2 | ubelt/util_format.py | 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 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] ... | [
"Registers",
"a",
"custom",
"formatting",
"function",
"with",
"ub",
".",
"repr2"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L244-L255 | [
"def",
"register",
"(",
"self",
",",
"type",
")",
":",
"def",
"_decorator",
"(",
"func",
")",
":",
"if",
"isinstance",
"(",
"type",
",",
"tuple",
")",
":",
"for",
"t",
"in",
"type",
":",
"self",
".",
"func_registry",
"[",
"t",
"]",
"=",
"func",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | FormatterExtensions.lookup | Returns an appropriate function to format `data` if one has been
registered. | ubelt/util_format.py | 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 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 | [
"Returns",
"an",
"appropriate",
"function",
"to",
"format",
"data",
"if",
"one",
"has",
"been",
"registered",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L257-L267 | [
"def",
"lookup",
"(",
"self",
",",
"data",
")",
":",
"for",
"func",
"in",
"self",
".",
"lazy_init",
":",
"func",
"(",
")",
"for",
"type",
",",
"func",
"in",
"self",
".",
"func_registry",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"data",... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | FormatterExtensions._register_numpy_extensions | 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'):
... raise pytest.skip()
>>>... | ubelt/util_format.py | 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 _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'... | [
"CommandLine",
":",
"python",
"-",
"m",
"ubelt",
".",
"util_format",
"FormatterExtensions",
".",
"_register_numpy_extensions"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L279-L368 | [
"def",
"_register_numpy_extensions",
"(",
"self",
")",
":",
"import",
"numpy",
"as",
"np",
"@",
"self",
".",
"register",
"(",
"np",
".",
"ndarray",
")",
"def",
"format_ndarray",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"re",
"strvals",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _rectify_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:
>>> assert _rectify_hasher(NoParam) is DEFA... | ubelt/util_hash.py | 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_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:
>>... | [
"Convert",
"a",
"string",
"-",
"based",
"key",
"into",
"a",
"hasher",
"class"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L181-L223 | [
"def",
"_rectify_hasher",
"(",
"hasher",
")",
":",
"if",
"xxhash",
"is",
"not",
"None",
":",
"# pragma: nobranch",
"if",
"hasher",
"in",
"{",
"'xxh32'",
",",
"'xx32'",
",",
"'xxhash'",
"}",
":",
"return",
"xxhash",
".",
"xxh32",
"if",
"hasher",
"in",
"{"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _rectify_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) is _ALPHABET_10
>>> assert ... | ubelt/util_hash.py | 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 _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... | [
"transforms",
"base",
"shorthand",
"into",
"the",
"full",
"list",
"representation"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L226-L252 | [
"def",
"_rectify_base",
"(",
"base",
")",
":",
"if",
"base",
"is",
"NoParam",
"or",
"base",
"==",
"'default'",
":",
"return",
"DEFAULT_ALPHABET",
"elif",
"base",
"in",
"[",
"26",
",",
"'abc'",
",",
"'alpha'",
"]",
":",
"return",
"_ALPHABET_26",
"elif",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _hashable_sequence | 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)))
>>> assert result1 == b'_[_\x02_,__[_\x03_,_\x04_,... | ubelt/util_hash.py | 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 _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)))
>>> ... | [
"r",
"Extracts",
"the",
"sequence",
"of",
"bytes",
"that",
"would",
"be",
"hashed",
"by",
"hash_data"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L512-L525 | [
"def",
"_hashable_sequence",
"(",
"data",
",",
"types",
"=",
"True",
")",
":",
"hasher",
"=",
"_HashTracer",
"(",
")",
"_update_hasher",
"(",
"hasher",
",",
"data",
",",
"types",
"=",
"types",
")",
"return",
"hasher",
".",
"sequence"
] | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _convert_to_hashable | 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): prefix, hashable:
a prefix hinting th... | ubelt/util_hash.py | 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 _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... | [
"r",
"Converts",
"data",
"into",
"a",
"hashable",
"byte",
"representation",
"if",
"an",
"appropriate",
"hashing",
"function",
"is",
"known",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L528-L579 | [
"def",
"_convert_to_hashable",
"(",
"data",
",",
"types",
"=",
"True",
")",
":",
"# HANDLE MOST COMMON TYPES FIRST",
"if",
"data",
"is",
"None",
":",
"hashable",
"=",
"b'NONE'",
"prefix",
"=",
"b'NULL'",
"elif",
"isinstance",
"(",
"data",
",",
"six",
".",
"b... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _update_hasher | 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 prefixes in the hash
Example:
>>> hasher = hashlib.... | ubelt/util_hash.py | 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 _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... | [
"Converts",
"data",
"into",
"a",
"byte",
"representation",
"and",
"calls",
"update",
"on",
"the",
"hasher",
"hashlib",
".",
"HASH",
"algorithm",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L582-L636 | [
"def",
"_update_hasher",
"(",
"hasher",
",",
"data",
",",
"types",
"=",
"True",
")",
":",
"# Determine if the data should be hashed directly or iterated through",
"if",
"isinstance",
"(",
"data",
",",
"(",
"tuple",
",",
"list",
",",
"zip",
")",
")",
":",
"needs_... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _convert_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', _ALPHABET_26))
nxmrlxv
>>> print(_c... | ubelt/util_hash.py | 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 _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... | [
"r",
"Packs",
"a",
"long",
"hexstr",
"into",
"a",
"shorter",
"length",
"string",
"with",
"a",
"larger",
"base",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L639-L695 | [
"def",
"_convert_hexstr_base",
"(",
"hexstr",
",",
"base",
")",
":",
"if",
"base",
"is",
"_ALPHABET_16",
":",
"# already in hex, no conversion needed",
"return",
"hexstr",
"baselen",
"=",
"len",
"(",
"base",
")",
"x",
"=",
"int",
"(",
"hexstr",
",",
"16",
")... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _digest_hasher | counterpart to _update_hasher | ubelt/util_hash.py | 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 _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... | [
"counterpart",
"to",
"_update_hasher"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L698-L706 | [
"def",
"_digest_hasher",
"(",
"hasher",
",",
"hashlen",
",",
"base",
")",
":",
"# Get a 128 character hex string",
"hex_text",
"=",
"hasher",
".",
"hexdigest",
"(",
")",
"# Shorten length of string (by increasing base)",
"base_text",
"=",
"_convert_hexstr_base",
"(",
"h... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | hash_data | 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 from hashlib, defaults to `sha512`.
base (str or List[str]):
Shorthand key or a list of symbols. Valid ... | ubelt/util_hash.py | 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_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... | [
"Get",
"a",
"unique",
"hash",
"depending",
"on",
"the",
"state",
"of",
"the",
"data",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L709-L769 | [
"def",
"hash_data",
"(",
"data",
",",
"hasher",
"=",
"NoParam",
",",
"base",
"=",
"NoParam",
",",
"types",
"=",
"False",
",",
"hashlen",
"=",
"NoParam",
",",
"convert",
"=",
"False",
")",
":",
"if",
"convert",
"and",
"isinstance",
"(",
"data",
",",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | hash_file | 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 data to hash, useful for faster
hashing, but less accurate, also makes hash dependant on
... | ubelt/util_hash.py | 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 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... | [
"Hashes",
"the",
"data",
"in",
"a",
"file",
"on",
"disk",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L772-L854 | [
"def",
"hash_file",
"(",
"fpath",
",",
"blocksize",
"=",
"65536",
",",
"stride",
"=",
"1",
",",
"hasher",
"=",
"NoParam",
",",
"hashlen",
"=",
"NoParam",
",",
"base",
"=",
"NoParam",
")",
":",
"base",
"=",
"_rectify_base",
"(",
"base",
")",
"hashlen",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | HashableExtensions.register | 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 return a tuple of bytes. First a small
prefix... | ubelt/util_hash.py | 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 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... | [
"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",
... | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L275-L323 | [
"def",
"register",
"(",
"self",
",",
"hash_types",
")",
":",
"# ensure iterable",
"if",
"not",
"isinstance",
"(",
"hash_types",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"hash_types",
"=",
"[",
"hash_types",
"]",
"def",
"_decor_closure",
"(",
"hash_fu... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | HashableExtensions.lookup | 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.modname_to_modpath('numpy'):
... ... | ubelt/util_hash.py | 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 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... | [
"Returns",
"an",
"appropriate",
"function",
"to",
"hash",
"data",
"if",
"one",
"has",
"been",
"registered",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L332-L379 | [
"def",
"lookup",
"(",
"self",
",",
"data",
")",
":",
"# Maybe try using functools.singledispatch instead?",
"# First try O(1) lookup",
"query_hash_type",
"=",
"data",
".",
"__class__",
"key",
"=",
"(",
"query_hash_type",
".",
"__module__",
",",
"query_hash_type",
".",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | HashableExtensions._register_numpy_extensions | Numpy extensions are builtin | ubelt/util_hash.py | 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_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... | [
"Numpy",
"extensions",
"are",
"builtin"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L381-L447 | [
"def",
"_register_numpy_extensions",
"(",
"self",
")",
":",
"# system checks",
"import",
"numpy",
"as",
"np",
"numpy_floating_types",
"=",
"(",
"np",
".",
"float16",
",",
"np",
".",
"float32",
",",
"np",
".",
"float64",
")",
"if",
"hasattr",
"(",
"np",
","... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | HashableExtensions._register_builtin_class_extensions | 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=True)[0:8])
cryarepd
>>> data = OrderedDic... | ubelt/util_hash.py | 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 _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=... | [
"Register",
"hashing",
"extensions",
"for",
"a",
"selection",
"of",
"classes",
"included",
"in",
"python",
"stdlib",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L449-L478 | [
"def",
"_register_builtin_class_extensions",
"(",
"self",
")",
":",
"@",
"self",
".",
"register",
"(",
"uuid",
".",
"UUID",
")",
"def",
"_hash_uuid",
"(",
"data",
")",
":",
"hashable",
"=",
"data",
".",
"bytes",
"prefix",
"=",
"b'UUID'",
"return",
"prefix"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _textio_iterlines | Iterates over lines in a TextIO stream until an EOF is encountered.
This is the iterator version of stream.readlines() | ubelt/util_cmd.py | 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 _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() | [
"Iterates",
"over",
"lines",
"in",
"a",
"TextIO",
"stream",
"until",
"an",
"EOF",
"is",
"encountered",
".",
"This",
"is",
"the",
"iterator",
"version",
"of",
"stream",
".",
"readlines",
"()"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cmd.py#L53-L61 | [
"def",
"_textio_iterlines",
"(",
"stream",
")",
":",
"line",
"=",
"stream",
".",
"readline",
"(",
")",
"while",
"line",
"!=",
"''",
":",
"yield",
"line",
"line",
"=",
"stream",
".",
"readline",
"(",
")"
] | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _proc_async_iter_stream | Reads output from a process in a separate thread | ubelt/util_cmd.py | 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_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()
... | [
"Reads",
"output",
"from",
"a",
"process",
"in",
"a",
"separate",
"thread"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cmd.py#L64-L87 | [
"def",
"_proc_async_iter_stream",
"(",
"proc",
",",
"stream",
",",
"buffersize",
"=",
"1",
")",
":",
"from",
"six",
".",
"moves",
"import",
"queue",
"from",
"threading",
"import",
"Thread",
"def",
"enqueue_output",
"(",
"proc",
",",
"stream",
",",
"stream_qu... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _proc_iteroutput_thread | 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 tqdm fix this,
but I cannot guarantee ... | ubelt/util_cmd.py | 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_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... | [
"Iterates",
"over",
"output",
"from",
"a",
"process",
"line",
"by",
"line"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cmd.py#L90-L130 | [
"def",
"_proc_iteroutput_thread",
"(",
"proc",
")",
":",
"from",
"six",
".",
"moves",
"import",
"queue",
"# Create threads that read stdout / stderr and queue up the output",
"stdout_queue",
"=",
"_proc_async_iter_stream",
"(",
"proc",
",",
"proc",
".",
"stdout",
")",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _proc_iteroutput_select | 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 | ubelt/util_cmd.py | 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 _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... | [
"Iterates",
"over",
"output",
"from",
"a",
"process",
"line",
"by",
"line"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cmd.py#L133-L160 | [
"def",
"_proc_iteroutput_select",
"(",
"proc",
")",
":",
"from",
"six",
".",
"moves",
"import",
"zip_longest",
"# Read output while the external program is running",
"while",
"proc",
".",
"poll",
"(",
")",
"is",
"None",
":",
"reads",
"=",
"[",
"proc",
".",
"stdo... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _tee_output | Simultaneously reports and captures stdout and stderr from a process
subprocess must be created using (stdout=subprocess.PIPE,
stderr=subprocess.PIPE) | ubelt/util_cmd.py | 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 _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':
... | [
"Simultaneously",
"reports",
"and",
"captures",
"stdout",
"and",
"stderr",
"from",
"a",
"process"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cmd.py#L163-L199 | [
"def",
"_tee_output",
"(",
"make_proc",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"backend",
"=",
"'auto'",
")",
":",
"logged_out",
"=",
"[",
"]",
"logged_err",
"=",
"[",
"]",
"if",
"backend",
"==",
"'auto'",
":",
"# backend = 'select'... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | cmd | 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 written to stdout and stderr is returned for parsing,
(3) cross platform behavior that lets you specify the command as a string
or tuple regar... | ubelt/util_cmd.py | 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 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 ... | [
"Executes",
"a",
"command",
"in",
"a",
"subprocess",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_cmd.py#L202-L410 | [
"def",
"cmd",
"(",
"command",
",",
"shell",
"=",
"False",
",",
"detach",
"=",
"False",
",",
"verbose",
"=",
"0",
",",
"tee",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"tee_backend",
"=",
"'auto'",
",",
"verbout",
"=",
"N... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | timestamp | make an iso8601 timestamp
Args:
method (str): type of timestamp
Example:
>>> stamp = timestamp()
>>> print('stamp = {!r}'.format(stamp))
stamp = ...-...-...T... | ubelt/util_time.py | 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 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... | [
"make",
"an",
"iso8601",
"timestamp"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_time.py#L14-L36 | [
"def",
"timestamp",
"(",
"method",
"=",
"'iso8601'",
")",
":",
"if",
"method",
"==",
"'iso8601'",
":",
"# ISO 8601",
"# datetime.datetime.utcnow().isoformat()",
"# datetime.datetime.now().isoformat()",
"# utcnow",
"tz_hour",
"=",
"time",
".",
"timezone",
"//",
"3600",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | benchmark_hash_data | CommandLine:
python ~/code/ubelt/dev/bench_hash.py --convert=True --show
python ~/code/ubelt/dev/bench_hash.py --convert=False --show | dev/bench_hash.py | 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 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 = [... | [
"CommandLine",
":",
"python",
"~",
"/",
"code",
"/",
"ubelt",
"/",
"dev",
"/",
"bench_hash",
".",
"py",
"--",
"convert",
"=",
"True",
"--",
"show",
"python",
"~",
"/",
"code",
"/",
"ubelt",
"/",
"dev",
"/",
"bench_hash",
".",
"py",
"--",
"convert",
... | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/dev/bench_hash.py#L2-L64 | [
"def",
"benchmark_hash_data",
"(",
")",
":",
"import",
"ubelt",
"as",
"ub",
"#ITEM = 'JUST A STRING' * 100",
"ITEM",
"=",
"[",
"0",
",",
"1",
",",
"'a'",
",",
"'b'",
",",
"[",
"'JUST A STRING'",
"]",
"*",
"4",
"]",
"HASHERS",
"=",
"[",
"'sha1'",
",",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | import_module_from_path | 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
Notes:
If the module is part of a package, the p... | ubelt/util_import.py | 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_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
... | [
"Imports",
"a",
"module",
"via",
"its",
"path"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L106-L211 | [
"def",
"import_module_from_path",
"(",
"modpath",
",",
"index",
"=",
"-",
"1",
")",
":",
"import",
"os",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"modpath",
")",
":",
"import",
"re",
"import",
"zipimport",
"# We allow (if not prefer or force) the co... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | import_module_from_name | 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 gaurentee this
>>> modname_list = [
>>... | ubelt/util_import.py | 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 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... | [
"Imports",
"a",
"module",
"from",
"its",
"string",
"name",
"(",
"__name__",
")"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L214-L251 | [
"def",
"import_module_from_name",
"(",
"modname",
")",
":",
"if",
"True",
":",
"# See if this fixes the Docker issue we saw but were unable to",
"# reproduce on another environment. Either way its better to use the",
"# standard importlib implementation than the one I wrote a long time",
"# ... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _extension_module_tags | Returns valid tags an extension module might have | ubelt/util_import.py | 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 _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:
... | [
"Returns",
"valid",
"tags",
"an",
"extension",
"module",
"might",
"have"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L254-L271 | [
"def",
"_extension_module_tags",
"(",
")",
":",
"import",
"sysconfig",
"tags",
"=",
"[",
"]",
"if",
"six",
".",
"PY2",
":",
"# see also 'SHLIB_EXT'",
"multiarch",
"=",
"sysconfig",
".",
"get_config_var",
"(",
"'MULTIARCH'",
")",
"if",
"multiarch",
"is",
"not",... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _platform_pylib_exts | 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. | ubelt/util_import.py | 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 _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 = []
... | [
"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... | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L274-L293 | [
"def",
"_platform_pylib_exts",
"(",
")",
":",
"# nocover",
"import",
"sysconfig",
"valid_exts",
"=",
"[",
"]",
"if",
"six",
".",
"PY2",
":",
"# see also 'SHLIB_EXT'",
"base_ext",
"=",
"'.'",
"+",
"sysconfig",
".",
"get_config_var",
"(",
"'SO'",
")",
".",
"sp... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _syspath_modname_to_modpath | 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):
list of directory paths. if specified prevents these directories
... | ubelt/util_import.py | 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 _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):... | [
"syspath",
"version",
"of",
"modname_to_modpath"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L296-L384 | [
"def",
"_syspath_modname_to_modpath",
"(",
"modname",
",",
"sys_path",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"def",
"_isvalid",
"(",
"modpath",
",",
"base",
")",
":",
"# every directory up to the module, should have an init",
"subdir",
"=",
"dirname",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | modname_to_modpath | 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 importing the module. Returns None if the module does not
exist.
Args:
modname (st... | ubelt/util_import.py | 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 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... | [
"Finds",
"the",
"path",
"to",
"a",
"python",
"module",
"from",
"its",
"name",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L387-L427 | [
"def",
"modname_to_modpath",
"(",
"modname",
",",
"hide_init",
"=",
"True",
",",
"hide_main",
"=",
"False",
",",
"sys_path",
"=",
"None",
")",
":",
"modpath",
"=",
"_syspath_modname_to_modpath",
"(",
"modname",
",",
"sys_path",
")",
"if",
"modpath",
"is",
"N... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | normalize_modpath | 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 always return the dpath.
hide_init (bool): if True, always strip awa... | ubelt/util_import.py | 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 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... | [
"Normalizes",
"__init__",
"and",
"__main__",
"paths",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L430-L479 | [
"def",
"normalize_modpath",
"(",
"modpath",
",",
"hide_init",
"=",
"True",
",",
"hide_main",
"=",
"False",
")",
":",
"if",
"six",
".",
"PY2",
":",
"if",
"modpath",
".",
"endswith",
"(",
"'.pyc'",
")",
":",
"modpath",
"=",
"modpath",
"[",
":",
"-",
"1... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | modpath_to_modname | 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 converted to a module name, and parent directories are
recursively included until a directory without an __init__.py file is
enc... | ubelt/util_import.py | 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 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... | [
"Determines",
"importable",
"name",
"from",
"file",
"path"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L482-L547 | [
"def",
"modpath_to_modname",
"(",
"modpath",
",",
"hide_init",
"=",
"True",
",",
"hide_main",
"=",
"False",
",",
"check",
"=",
"True",
",",
"relativeto",
"=",
"None",
")",
":",
"if",
"check",
"and",
"relativeto",
"is",
"None",
":",
"if",
"not",
"exists",... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | split_modpath | 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
directory and does not contain an `__init__.py... | ubelt/util_import.py | 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 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
... | [
"Splits",
"the",
"modpath",
"into",
"the",
"dir",
"that",
"must",
"be",
"in",
"PYTHONPATH",
"for",
"the",
"module",
"to",
"be",
"imported",
"and",
"the",
"modulepath",
"relative",
"to",
"this",
"directory",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L550-L596 | [
"def",
"split_modpath",
"(",
"modpath",
",",
"check",
"=",
"True",
")",
":",
"if",
"six",
".",
"PY2",
":",
"if",
"modpath",
".",
"endswith",
"(",
"'.pyc'",
")",
":",
"modpath",
"=",
"modpath",
"[",
":",
"-",
"1",
"]",
"modpath_",
"=",
"abspath",
"(... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | argval | 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 hyphens (i.e. `--`)
default (Optional[object]): value to retur... | ubelt/util_arg.py | 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 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... | [
"Get",
"the",
"value",
"of",
"a",
"keyword",
"argument",
"specified",
"on",
"the",
"command",
"line",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_arg.py#L11-L61 | [
"def",
"argval",
"(",
"key",
",",
"default",
"=",
"util_const",
".",
"NoParam",
",",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"# nocover",
"argv",
"=",
"sys",
".",
"argv",
"keys",
"=",
"[",
"key",
"]",
"if",
"isinstance",
"("... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | argflag | 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:
bool: flag : True if the key (or any of the ... | ubelt/util_arg.py | 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 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... | [
"Determines",
"if",
"a",
"key",
"is",
"specified",
"on",
"the",
"command",
"line"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_arg.py#L64-L88 | [
"def",
"argflag",
"(",
"key",
",",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"# nocover",
"argv",
"=",
"sys",
".",
"argv",
"keys",
"=",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | hzcat | 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 (defaults to '')
CommandLine:
... | ubelt/util_str.py | 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 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... | [
"Horizontally",
"concatenates",
"strings",
"preserving",
"indentation"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_str.py#L81-L145 | [
"def",
"hzcat",
"(",
"args",
",",
"sep",
"=",
"''",
")",
":",
"import",
"unicodedata",
"if",
"'\\n'",
"in",
"sep",
"or",
"'\\r'",
"in",
"sep",
":",
"raise",
"ValueError",
"(",
"'`sep` cannot contain newline characters'",
")",
"# TODO: ensure unicode data works cor... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | ensure_unicode | 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ôdé strįng') == 'my ünicôdé str... | ubelt/util_str.py | 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 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ô... | [
"r",
"Casts",
"bytes",
"into",
"utf8",
"(",
"mostly",
"for",
"python2",
"compatibility",
")"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_str.py#L148-L169 | [
"def",
"ensure_unicode",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
":",
"return",
"text",
"elif",
"isinstance",
"(",
"text",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"text",
".",
"decode",
"("... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | symlink | 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_path (PathLike): path to desired location for symlink
overwrite (b... | ubelt/util_links.py | 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 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... | [
"Create",
"a",
"symbolic",
"link",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_links.py#L44-L155 | [
"def",
"symlink",
"(",
"real_path",
",",
"link_path",
",",
"overwrite",
"=",
"False",
",",
"verbose",
"=",
"0",
")",
":",
"path",
"=",
"normpath",
"(",
"real_path",
")",
"link",
"=",
"normpath",
"(",
"link_path",
")",
"if",
"not",
"os",
".",
"path",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _dirstats | Testing helper for printing directory information
(mostly for investigating windows weirdness)
CommandLine:
python -m ubelt.util_links _dirstats | ubelt/util_links.py | 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 _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('=====... | [
"Testing",
"helper",
"for",
"printing",
"directory",
"information",
"(",
"mostly",
"for",
"investigating",
"windows",
"weirdness",
")"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_links.py#L189-L258 | [
"def",
"_dirstats",
"(",
"dpath",
"=",
"None",
")",
":",
"# nocover",
"from",
"ubelt",
"import",
"util_colors",
"if",
"dpath",
"is",
"None",
":",
"dpath",
"=",
"os",
".",
"getcwd",
"(",
")",
"print",
"(",
"'==============='",
")",
"print",
"(",
"'Listing... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | _make_signature_key | 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, kwargs)
>>> print('key = {!r}'.format(key))
... | ubelt/util_memoize.py | 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 _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... | [
"Transforms",
"function",
"args",
"into",
"a",
"key",
"that",
"can",
"be",
"used",
"by",
"the",
"cache"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_memoize.py#L58-L100 | [
"def",
"_make_signature_key",
"(",
"args",
",",
"kwargs",
")",
":",
"kwitems",
"=",
"kwargs",
".",
"items",
"(",
")",
"# TODO: we should check if Python is at least 3.7 and sort by kwargs",
"# keys otherwise. Should we use hash_data for key generation",
"if",
"(",
"sys",
".",... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | memoize | 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_memoize memoize
Example:
... | ubelt/util_memoize.py | 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(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... | [
"memoization",
"decorator",
"that",
"respects",
"args",
"and",
"kwargs"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_memoize.py#L103-L150 | [
"def",
"memoize",
"(",
"func",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"memoizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"_make_signature_key",
"(",
"args",
",",
"kwargs"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | memoize_property | 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 decorating another
property. In either case t... | ubelt/util_memoize.py | 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 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... | [
"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",
"preventin... | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_memoize.py#L229-L286 | [
"def",
"memoize_property",
"(",
"fget",
")",
":",
"# Unwrap any existing property decorator",
"while",
"hasattr",
"(",
"fget",
",",
"'fget'",
")",
":",
"fget",
"=",
"fget",
".",
"fget",
"attr_name",
"=",
"'_'",
"+",
"fget",
".",
"__name__",
"@",
"functools",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | highlight_code | 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:
str: text : highlighted text
If pygments is not installed... | ubelt/util_colors.py | 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 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:
... | [
"Highlights",
"a",
"block",
"of",
"text",
"using",
"ANSI",
"tags",
"based",
"on",
"language",
"syntax",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_colors.py#L17-L66 | [
"def",
"highlight_code",
"(",
"text",
",",
"lexer_name",
"=",
"'python'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Resolve extensions to languages",
"lexer_name",
"=",
"{",
"'py'",
":",
"'python'",
",",
"'h'",
":",
"'cpp'",
",",
"'cpp'",
":",
"'cpp'",
",",
"'... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | color_text | 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, turquoise, bold, darkred, darkgree... | ubelt/util_colors.py | 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 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... | [
"r",
"Colorizes",
"text",
"a",
"single",
"color",
"using",
"ansii",
"tags",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_colors.py#L69-L117 | [
"def",
"color_text",
"(",
"text",
",",
"color",
")",
":",
"if",
"color",
"is",
"None",
":",
"return",
"text",
"try",
":",
"import",
"pygments",
"import",
"pygments",
".",
"console",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win32'",
")",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | iterable | 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
Returns:
bool: True if the input is i... | ubelt/util_list.py | 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 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... | [
"Checks",
"if",
"the",
"input",
"implements",
"the",
"iterator",
"interface",
".",
"An",
"exception",
"is",
"made",
"for",
"strings",
"which",
"return",
"False",
"unless",
"strok",
"is",
"True"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L155-L180 | [
"def",
"iterable",
"(",
"obj",
",",
"strok",
"=",
"False",
")",
":",
"try",
":",
"iter",
"(",
"obj",
")",
"except",
"Exception",
":",
"return",
"False",
"else",
":",
"return",
"strok",
"or",
"not",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_t... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | unique | 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 from the input sequence
CommandLine:
... | ubelt/util_list.py | 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 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... | [
"Generates",
"unique",
"items",
"in",
"the",
"order",
"they",
"appear",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L253-L294 | [
"def",
"unique",
"(",
"items",
",",
"key",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"if",
"key",
"is",
"None",
":",
"for",
"item",
"in",
"items",
":",
"if",
"item",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"item",
")",
"... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | argunique | 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.
Yields:
int : indices of the uniq... | ubelt/util_list.py | 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 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.
... | [
"Returns",
"indices",
"corresponding",
"to",
"the",
"first",
"instance",
"of",
"each",
"unique",
"item",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L297-L321 | [
"def",
"argunique",
"(",
"items",
",",
"key",
"=",
"None",
")",
":",
"# yield from unique(range(len(items)), key=lambda i: items[i])",
"if",
"key",
"is",
"None",
":",
"return",
"unique",
"(",
"range",
"(",
"len",
"(",
"items",
")",
")",
",",
"key",
"=",
"lam... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | unique_flags | 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(item)` is unique.
Returns:
List[bool... | ubelt/util_list.py | 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 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... | [
"Returns",
"a",
"list",
"of",
"booleans",
"corresponding",
"to",
"the",
"first",
"instance",
"of",
"each",
"unique",
"item",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L324-L353 | [
"def",
"unique_flags",
"(",
"items",
",",
"key",
"=",
"None",
")",
":",
"len_",
"=",
"len",
"(",
"items",
")",
"if",
"key",
"is",
"None",
":",
"item_to_index",
"=",
"dict",
"(",
"zip",
"(",
"reversed",
"(",
"items",
")",
",",
"reversed",
"(",
"rang... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | boolmask | 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 `indices`
Note:
In the future the ... | ubelt/util_list.py | 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 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... | [
"Constructs",
"a",
"list",
"of",
"booleans",
"where",
"an",
"item",
"is",
"True",
"if",
"its",
"position",
"is",
"in",
"indices",
"otherwise",
"it",
"is",
"False",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L356-L387 | [
"def",
"boolmask",
"(",
"indices",
",",
"maxval",
"=",
"None",
")",
":",
"if",
"maxval",
"is",
"None",
":",
"indices",
"=",
"list",
"(",
"indices",
")",
"maxval",
"=",
"max",
"(",
"indices",
")",
"+",
"1",
"mask",
"=",
"[",
"False",
"]",
"*",
"ma... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | allsame | 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([1, 1, 1, 1])
True
>>> allsame([])
... | ubelt/util_list.py | 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 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([... | [
"Determine",
"if",
"all",
"items",
"in",
"a",
"sequence",
"are",
"the",
"same"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L458-L489 | [
"def",
"allsame",
"(",
"iterable",
",",
"eq",
"=",
"operator",
".",
"eq",
")",
":",
"iter_",
"=",
"iter",
"(",
"iterable",
")",
"try",
":",
"first",
"=",
"next",
"(",
"iter_",
")",
"except",
"StopIteration",
":",
"return",
"True",
"return",
"all",
"(... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | argsort | 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
key (Callable, optional): customizes the ordering of the index... | ubelt/util_list.py | 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 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... | [
"Returns",
"the",
"indices",
"that",
"would",
"sort",
"a",
"indexable",
"object",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L492-L544 | [
"def",
"argsort",
"(",
"indexable",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"# Create an iterator of value/key pairs",
"if",
"isinstance",
"(",
"indexable",
",",
"collections_abc",
".",
"Mapping",
")",
":",
"vk_iter",
"=",
"(",
"(",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | argmax | 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, optional): customizes the ordering of the indexa... | ubelt/util_list.py | 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 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... | [
"Returns",
"index",
"/",
"key",
"of",
"the",
"item",
"with",
"the",
"largest",
"value",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L547-L578 | [
"def",
"argmax",
"(",
"indexable",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
"and",
"isinstance",
"(",
"indexable",
",",
"collections_abc",
".",
"Mapping",
")",
":",
"return",
"max",
"(",
"indexable",
".",
"items",
"(",
")",
",",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | argmin | 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, optional): customizes the ordering of the index... | ubelt/util_list.py | 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 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... | [
"Returns",
"index",
"/",
"key",
"of",
"the",
"item",
"with",
"the",
"smallest",
"value",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L581-L609 | [
"def",
"argmin",
"(",
"indexable",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
"and",
"isinstance",
"(",
"indexable",
",",
"collections_abc",
".",
"Mapping",
")",
":",
"return",
"min",
"(",
"indexable",
".",
"items",
"(",
")",
",",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | dzip | 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 length to `items1`
cls (Type[dict]): dic... | ubelt/util_dict.py | 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 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 ... | [
"Zips",
"elementwise",
"pairs",
"between",
"items1",
"and",
"items2",
"into",
"a",
"dictionary",
".",
"Values",
"from",
"items2",
"can",
"be",
"broadcast",
"onto",
"items1",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L107-L147 | [
"def",
"dzip",
"(",
"items1",
",",
"items2",
",",
"cls",
"=",
"dict",
")",
":",
"try",
":",
"len",
"(",
"items1",
")",
"except",
"TypeError",
":",
"items1",
"=",
"list",
"(",
"items1",
")",
"try",
":",
"len",
"(",
"items2",
")",
"except",
"TypeErro... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | group_items | 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_items: maps a groupid to a list of item... | ubelt/util_dict.py | 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 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... | [
"r",
"Groups",
"a",
"list",
"of",
"items",
"by",
"group",
"id",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L150-L184 | [
"def",
"group_items",
"(",
"items",
",",
"groupids",
")",
":",
"if",
"callable",
"(",
"groupids",
")",
":",
"keyfunc",
"=",
"groupids",
"pair_list",
"=",
"(",
"(",
"keyfunc",
"(",
"item",
")",
",",
"item",
")",
"for",
"item",
"in",
"items",
")",
"els... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | dict_hist | 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 for each item
ordered (bool): if True the result is ordered by frequency
... | ubelt/util_dict.py | 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 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... | [
"Builds",
"a",
"histogram",
"of",
"items",
"counting",
"the",
"number",
"of",
"time",
"each",
"item",
"appears",
"in",
"the",
"input",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L187-L253 | [
"def",
"dict_hist",
"(",
"item_list",
",",
"weight_list",
"=",
"None",
",",
"ordered",
"=",
"False",
",",
"labels",
"=",
"None",
")",
":",
"if",
"labels",
"is",
"None",
":",
"hist_",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"else",
":",
"his... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | find_duplicates | 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
k (int): only return items that appear at least ... | ubelt/util_dict.py | 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 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
... | [
"Find",
"all",
"duplicate",
"items",
"in",
"a",
"list",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L256-L314 | [
"def",
"find_duplicates",
"(",
"items",
",",
"k",
"=",
"2",
",",
"key",
"=",
"None",
")",
":",
"# Build mapping from items to the indices at which they appear",
"# if key is not None:",
"# items = map(key, items)",
"duplicates",
"=",
"defaultdict",
"(",
"list",
")",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | dict_take | 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:
python -m ubelt.util_dict dict_take_gen
Example:
>>... | ubelt/util_dict.py | 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_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... | [
"r",
"Generates",
"values",
"from",
"a",
"dictionary"
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L346-L380 | [
"def",
"dict_take",
"(",
"dict_",
",",
"keys",
",",
"default",
"=",
"util_const",
".",
"NoParam",
")",
":",
"if",
"default",
"is",
"util_const",
".",
"NoParam",
":",
"for",
"key",
"in",
"keys",
":",
"yield",
"dict_",
"[",
"key",
"]",
"else",
":",
"fo... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | dict_union | 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 argument is an OrderedDict, otherwise d... | ubelt/util_dict.py | 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_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... | [
"Combines",
"the",
"disjoint",
"keys",
"in",
"multiple",
"dictionaries",
".",
"For",
"intersecting",
"keys",
"dictionaries",
"towards",
"the",
"end",
"of",
"the",
"sequence",
"are",
"given",
"precedence",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L383-L412 | [
"def",
"dict_union",
"(",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"{",
"}",
"else",
":",
"dictclass",
"=",
"OrderedDict",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"OrderedDict",
")",
"else",
"dict",
"return",
"dictclass",... | db802f3ad8abba025db74b54f86e6892b8927325 |
valid | dict_isect | 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 first argument is an OrderedDict, othe... | ubelt/util_dict.py | 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... | 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... | [
"Constructs",
"a",
"dictionary",
"that",
"contains",
"keys",
"common",
"between",
"all",
"inputs",
".",
"The",
"returned",
"values",
"will",
"only",
"belong",
"to",
"the",
"first",
"dictionary",
"."
] | Erotemic/ubelt | python | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L415-L448 | [
"def",
"dict_isect",
"(",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"{",
"}",
"else",
":",
"dictclass",
"=",
"OrderedDict",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"OrderedDict",
")",
"else",
"dict",
"common_keys",
"=",
... | db802f3ad8abba025db74b54f86e6892b8927325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.