repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
RudolfCardinal/pythonlib
cardinal_pythonlib/modules.py
import_submodules
def import_submodules(package: Union[str, ModuleType], base_package_for_relative_import: str = None, recursive: bool = True) -> Dict[str, ModuleType]: """ Import all submodules of a module, recursively, including subpackages. Args: package: package (name ...
python
def import_submodules(package: Union[str, ModuleType], base_package_for_relative_import: str = None, recursive: bool = True) -> Dict[str, ModuleType]: """ Import all submodules of a module, recursively, including subpackages. Args: package: package (name ...
[ "def", "import_submodules", "(", "package", ":", "Union", "[", "str", ",", "ModuleType", "]", ",", "base_package_for_relative_import", ":", "str", "=", "None", ",", "recursive", ":", "bool", "=", "True", ")", "->", "Dict", "[", "str", ",", "ModuleType", "]...
Import all submodules of a module, recursively, including subpackages. Args: package: package (name or actual module) base_package_for_relative_import: path to prepend? recursive: import submodules too? Returns: dict: mapping from full module name to module
[ "Import", "all", "submodules", "of", "a", "module", "recursively", "including", "subpackages", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/modules.py#L48-L74
RudolfCardinal/pythonlib
cardinal_pythonlib/modules.py
is_c_extension
def is_c_extension(module: ModuleType) -> bool: """ Modified from https://stackoverflow.com/questions/20339053/in-python-how-can-one-tell-if-a-module-comes-from-a-c-extension. ``True`` only if the passed module is a C extension implemented as a dynamically linked shared library specific to the ...
python
def is_c_extension(module: ModuleType) -> bool: """ Modified from https://stackoverflow.com/questions/20339053/in-python-how-can-one-tell-if-a-module-comes-from-a-c-extension. ``True`` only if the passed module is a C extension implemented as a dynamically linked shared library specific to the ...
[ "def", "is_c_extension", "(", "module", ":", "ModuleType", ")", "->", "bool", ":", "# noqa", "assert", "inspect", ".", "ismodule", "(", "module", ")", ",", "'\"{}\" not a module.'", ".", "format", "(", "module", ")", "# If this module was loaded by a PEP 302-complia...
Modified from https://stackoverflow.com/questions/20339053/in-python-how-can-one-tell-if-a-module-comes-from-a-c-extension. ``True`` only if the passed module is a C extension implemented as a dynamically linked shared library specific to the current platform. Args: module: Previously impo...
[ "Modified", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "20339053", "/", "in", "-", "python", "-", "how", "-", "can", "-", "one", "-", "tell", "-", "if", "-", "a", "-", "module", "-", "comes", "-", "from", "-", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/modules.py#L102-L154
RudolfCardinal/pythonlib
cardinal_pythonlib/modules.py
contains_c_extension
def contains_c_extension(module: ModuleType, import_all_submodules: bool = True, include_external_imports: bool = False, seen: List[ModuleType] = None) -> bool: """ Extends :func:`is_c_extension` by asking: is this module, or any of its ...
python
def contains_c_extension(module: ModuleType, import_all_submodules: bool = True, include_external_imports: bool = False, seen: List[ModuleType] = None) -> bool: """ Extends :func:`is_c_extension` by asking: is this module, or any of its ...
[ "def", "contains_c_extension", "(", "module", ":", "ModuleType", ",", "import_all_submodules", ":", "bool", "=", "True", ",", "include_external_imports", ":", "bool", "=", "False", ",", "seen", ":", "List", "[", "ModuleType", "]", "=", "None", ")", "->", "bo...
Extends :func:`is_c_extension` by asking: is this module, or any of its submodules, a C extension? Args: module: Previously imported module object to be tested. import_all_submodules: explicitly import all submodules of this module? include_external_imports: check modules in other packa...
[ "Extends", ":", "func", ":", "is_c_extension", "by", "asking", ":", "is", "this", "module", "or", "any", "of", "its", "submodules", "a", "C", "extension?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/modules.py#L157-L308
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
which_with_envpath
def which_with_envpath(executable: str, env: Dict[str, str]) -> str: """ Performs a :func:`shutil.which` command using the PATH from the specified environment. Reason: when you use ``run([executable, ...], env)`` and therefore ``subprocess.run([executable, ...], env=env)``, the PATH that's searched...
python
def which_with_envpath(executable: str, env: Dict[str, str]) -> str: """ Performs a :func:`shutil.which` command using the PATH from the specified environment. Reason: when you use ``run([executable, ...], env)`` and therefore ``subprocess.run([executable, ...], env=env)``, the PATH that's searched...
[ "def", "which_with_envpath", "(", "executable", ":", "str", ",", "env", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "str", ":", "oldpath", "=", "os", ".", "environ", ".", "get", "(", "\"PATH\"", ",", "\"\"", ")", "os", ".", "environ", "[",...
Performs a :func:`shutil.which` command using the PATH from the specified environment. Reason: when you use ``run([executable, ...], env)`` and therefore ``subprocess.run([executable, ...], env=env)``, the PATH that's searched for ``executable`` is the parent's, not the new child's -- so you have to ...
[ "Performs", "a", ":", "func", ":", "shutil", ".", "which", "command", "using", "the", "PATH", "from", "the", "specified", "environment", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L47-L65
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
require_executable
def require_executable(executable: str) -> None: """ If ``executable`` is not found by :func:`shutil.which`, raise :exc:`FileNotFoundError`. """ if shutil.which(executable): return errmsg = "Missing command (must be on the PATH): " + executable log.critical(errmsg) raise FileNotF...
python
def require_executable(executable: str) -> None: """ If ``executable`` is not found by :func:`shutil.which`, raise :exc:`FileNotFoundError`. """ if shutil.which(executable): return errmsg = "Missing command (must be on the PATH): " + executable log.critical(errmsg) raise FileNotF...
[ "def", "require_executable", "(", "executable", ":", "str", ")", "->", "None", ":", "if", "shutil", ".", "which", "(", "executable", ")", ":", "return", "errmsg", "=", "\"Missing command (must be on the PATH): \"", "+", "executable", "log", ".", "critical", "(",...
If ``executable`` is not found by :func:`shutil.which`, raise :exc:`FileNotFoundError`.
[ "If", "executable", "is", "not", "found", "by", ":", "func", ":", "shutil", ".", "which", "raise", ":", "exc", ":", "FileNotFoundError", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L68-L77
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
mkdir_p
def mkdir_p(path: str) -> None: """ Makes a directory, and any intermediate (parent) directories if required. This is the UNIX ``mkdir -p DIRECTORY`` command; of course, we use :func:`os.makedirs` instead, for portability. """ log.debug("mkdir -p " + path) os.makedirs(path, exist_ok=True)
python
def mkdir_p(path: str) -> None: """ Makes a directory, and any intermediate (parent) directories if required. This is the UNIX ``mkdir -p DIRECTORY`` command; of course, we use :func:`os.makedirs` instead, for portability. """ log.debug("mkdir -p " + path) os.makedirs(path, exist_ok=True)
[ "def", "mkdir_p", "(", "path", ":", "str", ")", "->", "None", ":", "log", ".", "debug", "(", "\"mkdir -p \"", "+", "path", ")", "os", ".", "makedirs", "(", "path", ",", "exist_ok", "=", "True", ")" ]
Makes a directory, and any intermediate (parent) directories if required. This is the UNIX ``mkdir -p DIRECTORY`` command; of course, we use :func:`os.makedirs` instead, for portability.
[ "Makes", "a", "directory", "and", "any", "intermediate", "(", "parent", ")", "directories", "if", "required", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L84-L92
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
pushd
def pushd(directory: str) -> None: """ Context manager: changes directory and preserves the original on exit. Example: .. code-block:: python with pushd(new_directory): # do things """ previous_dir = os.getcwd() os.chdir(directory) yield os.chdir(previous_dir)
python
def pushd(directory: str) -> None: """ Context manager: changes directory and preserves the original on exit. Example: .. code-block:: python with pushd(new_directory): # do things """ previous_dir = os.getcwd() os.chdir(directory) yield os.chdir(previous_dir)
[ "def", "pushd", "(", "directory", ":", "str", ")", "->", "None", ":", "previous_dir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "directory", ")", "yield", "os", ".", "chdir", "(", "previous_dir", ")" ]
Context manager: changes directory and preserves the original on exit. Example: .. code-block:: python with pushd(new_directory): # do things
[ "Context", "manager", ":", "changes", "directory", "and", "preserves", "the", "original", "on", "exit", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L100-L114
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
preserve_cwd
def preserve_cwd(func: Callable) -> Callable: """ Decorator to preserve the current working directory in calls to the decorated function. Example: .. code-block:: python @preserve_cwd def myfunc(): os.chdir("/faraway") os.chdir("/home") myfunc() ...
python
def preserve_cwd(func: Callable) -> Callable: """ Decorator to preserve the current working directory in calls to the decorated function. Example: .. code-block:: python @preserve_cwd def myfunc(): os.chdir("/faraway") os.chdir("/home") myfunc() ...
[ "def", "preserve_cwd", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "# http://stackoverflow.com/questions/169070/python-how-do-i-write-a-decorator-that-restores-the-cwd # noqa", "def", "decorator", "(", "*", "args_", ",", "*", "*", "kwargs", ")", "->", "Any"...
Decorator to preserve the current working directory in calls to the decorated function. Example: .. code-block:: python @preserve_cwd def myfunc(): os.chdir("/faraway") os.chdir("/home") myfunc() assert os.getcwd() == "/home"
[ "Decorator", "to", "preserve", "the", "current", "working", "directory", "in", "calls", "to", "the", "decorated", "function", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L117-L140
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
copyglob
def copyglob(src: str, dest: str, allow_nothing: bool = False, allow_nonfiles: bool = False) -> None: """ Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e....
python
def copyglob(src: str, dest: str, allow_nothing: bool = False, allow_nonfiles: bool = False) -> None: """ Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e....
[ "def", "copyglob", "(", "src", ":", "str", ",", "dest", ":", "str", ",", "allow_nothing", ":", "bool", "=", "False", ",", "allow_nonfiles", ":", "bool", "=", "False", ")", "->", "None", ":", "something", "=", "False", "for", "filename", "in", "glob", ...
Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e.g. ``/somewhere/*.txt``) dest: destination directory allow_nothing: don't raise an exception if no files are fo...
[ "Copies", "files", "whose", "filenames", "match", "the", "glob", "src", "into", "the", "directory", "dest", ".", "Raises", "an", "error", "if", "no", "files", "are", "copied", "unless", "allow_nothing", "is", "True", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L155-L179
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
copy_tree_root
def copy_tree_root(src_dir: str, dest_parent: str) -> None: """ Copies a directory ``src_dir`` into the directory ``dest_parent``. That is, with a file structure like: .. code-block:: none /source/thing/a.txt /source/thing/b.txt /source/thing/somedir/c.txt the command ...
python
def copy_tree_root(src_dir: str, dest_parent: str) -> None: """ Copies a directory ``src_dir`` into the directory ``dest_parent``. That is, with a file structure like: .. code-block:: none /source/thing/a.txt /source/thing/b.txt /source/thing/somedir/c.txt the command ...
[ "def", "copy_tree_root", "(", "src_dir", ":", "str", ",", "dest_parent", ":", "str", ")", "->", "None", ":", "dirname", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "path", ".", "normpath", "(", "src_dir", ")", ")", "dest_dir", "=", "os",...
Copies a directory ``src_dir`` into the directory ``dest_parent``. That is, with a file structure like: .. code-block:: none /source/thing/a.txt /source/thing/b.txt /source/thing/somedir/c.txt the command .. code-block:: python copy_tree_root("/source/thing", "/dest"...
[ "Copies", "a", "directory", "src_dir", "into", "the", "directory", "dest_parent", ".", "That", "is", "with", "a", "file", "structure", "like", ":" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L197-L224
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
copy_tree_contents
def copy_tree_contents(srcdir: str, destdir: str, destroy: bool = False) -> None: """ Recursive copy. Unlike :func:`copy_tree_root`, :func:`copy_tree_contents` works as follows. With the file structure: .. code-block:: none /source/thing/a.txt /source/thing/b.txt...
python
def copy_tree_contents(srcdir: str, destdir: str, destroy: bool = False) -> None: """ Recursive copy. Unlike :func:`copy_tree_root`, :func:`copy_tree_contents` works as follows. With the file structure: .. code-block:: none /source/thing/a.txt /source/thing/b.txt...
[ "def", "copy_tree_contents", "(", "srcdir", ":", "str", ",", "destdir", ":", "str", ",", "destroy", ":", "bool", "=", "False", ")", "->", "None", ":", "log", ".", "info", "(", "\"Copying directory {} -> {}\"", ",", "srcdir", ",", "destdir", ")", "if", "o...
Recursive copy. Unlike :func:`copy_tree_root`, :func:`copy_tree_contents` works as follows. With the file structure: .. code-block:: none /source/thing/a.txt /source/thing/b.txt /source/thing/somedir/c.txt the command .. code-block:: python copy_tree_contents("/sourc...
[ "Recursive", "copy", ".", "Unlike", ":", "func", ":", "copy_tree_root", ":", "func", ":", "copy_tree_contents", "works", "as", "follows", ".", "With", "the", "file", "structure", ":" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L227-L263
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
rmglob
def rmglob(pattern: str) -> None: """ Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`). """ for f in glob.glob(pattern): os.remove(f)
python
def rmglob(pattern: str) -> None: """ Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`). """ for f in glob.glob(pattern): os.remove(f)
[ "def", "rmglob", "(", "pattern", ":", "str", ")", "->", "None", ":", "for", "f", "in", "glob", ".", "glob", "(", "pattern", ")", ":", "os", ".", "remove", "(", "f", ")" ]
Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`).
[ "Deletes", "all", "files", "whose", "filename", "matches", "the", "glob", "pattern", "(", "via", ":", "func", ":", "glob", ".", "glob", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L270-L276
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
purge
def purge(path: str, pattern: str) -> None: """ Deletes all files in ``path`` matching ``pattern`` (via :func:`fnmatch.fnmatch`). """ for f in find(pattern, path): log.info("Deleting {}", f) os.remove(f)
python
def purge(path: str, pattern: str) -> None: """ Deletes all files in ``path`` matching ``pattern`` (via :func:`fnmatch.fnmatch`). """ for f in find(pattern, path): log.info("Deleting {}", f) os.remove(f)
[ "def", "purge", "(", "path", ":", "str", ",", "pattern", ":", "str", ")", "->", "None", ":", "for", "f", "in", "find", "(", "pattern", ",", "path", ")", ":", "log", ".", "info", "(", "\"Deleting {}\"", ",", "f", ")", "os", ".", "remove", "(", "...
Deletes all files in ``path`` matching ``pattern`` (via :func:`fnmatch.fnmatch`).
[ "Deletes", "all", "files", "in", "path", "matching", "pattern", "(", "via", ":", "func", ":", "fnmatch", ".", "fnmatch", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L279-L286
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
delete_files_within_dir
def delete_files_within_dir(directory: str, filenames: List[str]) -> None: """ Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``. """ for dirpath, dirnames, fnames in os.walk(directory): for f in fnames: if f in filenames: ful...
python
def delete_files_within_dir(directory: str, filenames: List[str]) -> None: """ Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``. """ for dirpath, dirnames, fnames in os.walk(directory): for f in fnames: if f in filenames: ful...
[ "def", "delete_files_within_dir", "(", "directory", ":", "str", ",", "filenames", ":", "List", "[", "str", "]", ")", "->", "None", ":", "for", "dirpath", ",", "dirnames", ",", "fnames", "in", "os", ".", "walk", "(", "directory", ")", ":", "for", "f", ...
Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``.
[ "Delete", "files", "within", "directory", "whose", "filename", "*", "exactly", "*", "matches", "one", "of", "filenames", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L289-L299
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
shutil_rmtree_onerror
def shutil_rmtree_onerror(func: Callable[[str], None], path: str, exc_info: EXC_INFO_TYPE) -> None: """ Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. ...
python
def shutil_rmtree_onerror(func: Callable[[str], None], path: str, exc_info: EXC_INFO_TYPE) -> None: """ Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. ...
[ "def", "shutil_rmtree_onerror", "(", "func", ":", "Callable", "[", "[", "str", "]", ",", "None", "]", ",", "path", ":", "str", ",", "exc_info", ":", "EXC_INFO_TYPE", ")", "->", "None", ":", "# noqa", "if", "not", "os", ".", "access", "(", "path", ","...
Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. If the error is for another reason it re-raises the error. Usage: ``shutil.rmtree(path, onerror=shutil_rmtree_onerror)`` See https://stackove...
[ "Error", "handler", "for", "shutil", ".", "rmtree", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L310-L332
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
rmtree
def rmtree(directory: str) -> None: """ Deletes a directory tree. """ log.debug("Deleting directory {!r}", directory) shutil.rmtree(directory, onerror=shutil_rmtree_onerror)
python
def rmtree(directory: str) -> None: """ Deletes a directory tree. """ log.debug("Deleting directory {!r}", directory) shutil.rmtree(directory, onerror=shutil_rmtree_onerror)
[ "def", "rmtree", "(", "directory", ":", "str", ")", "->", "None", ":", "log", ".", "debug", "(", "\"Deleting directory {!r}\"", ",", "directory", ")", "shutil", ".", "rmtree", "(", "directory", ",", "onerror", "=", "shutil_rmtree_onerror", ")" ]
Deletes a directory tree.
[ "Deletes", "a", "directory", "tree", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L335-L340
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
chown_r
def chown_r(path: str, user: str, group: str) -> None: """ Performs a recursive ``chown``. Args: path: path to walk down user: user name or ID group: group name or ID As per http://stackoverflow.com/questions/2853723 """ for root, dirs, files in os.walk(path): f...
python
def chown_r(path: str, user: str, group: str) -> None: """ Performs a recursive ``chown``. Args: path: path to walk down user: user name or ID group: group name or ID As per http://stackoverflow.com/questions/2853723 """ for root, dirs, files in os.walk(path): f...
[ "def", "chown_r", "(", "path", ":", "str", ",", "user", ":", "str", ",", "group", ":", "str", ")", "->", "None", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "x", "in", "dirs", ":", "sh...
Performs a recursive ``chown``. Args: path: path to walk down user: user name or ID group: group name or ID As per http://stackoverflow.com/questions/2853723
[ "Performs", "a", "recursive", "chown", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L347-L362
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
chmod_r
def chmod_r(root: str, permission: int) -> None: """ Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR`` """ os.chmod(root, permission) for dirpath, dirnames, filenames in os.walk(root): for d in dirnames: os.chmod(o...
python
def chmod_r(root: str, permission: int) -> None: """ Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR`` """ os.chmod(root, permission) for dirpath, dirnames, filenames in os.walk(root): for d in dirnames: os.chmod(o...
[ "def", "chmod_r", "(", "root", ":", "str", ",", "permission", ":", "int", ")", "->", "None", ":", "os", ".", "chmod", "(", "root", ",", "permission", ")", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "root", ")...
Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR``
[ "Recursive", "chmod", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L365-L378
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
find
def find(pattern: str, path: str) -> List[str]: """ Finds files in ``path`` whose filenames match ``pattern`` (via :func:`fnmatch.fnmatch`). """ result = [] for root, dirs, files in os.walk(path): for name in files: if fnmatch.fnmatch(name, pattern): result.ap...
python
def find(pattern: str, path: str) -> List[str]: """ Finds files in ``path`` whose filenames match ``pattern`` (via :func:`fnmatch.fnmatch`). """ result = [] for root, dirs, files in os.walk(path): for name in files: if fnmatch.fnmatch(name, pattern): result.ap...
[ "def", "find", "(", "pattern", ":", "str", ",", "path", ":", "str", ")", "->", "List", "[", "str", "]", ":", "result", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "name", "in...
Finds files in ``path`` whose filenames match ``pattern`` (via :func:`fnmatch.fnmatch`).
[ "Finds", "files", "in", "path", "whose", "filenames", "match", "pattern", "(", "via", ":", "func", ":", "fnmatch", ".", "fnmatch", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L385-L395
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
find_first
def find_first(pattern: str, path: str) -> str: """ Finds first file in ``path`` whose filename matches ``pattern`` (via :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`. """ try: return find(pattern, path)[0] except IndexError: log.critical('''Couldn't find "{}" in "{}"''',...
python
def find_first(pattern: str, path: str) -> str: """ Finds first file in ``path`` whose filename matches ``pattern`` (via :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`. """ try: return find(pattern, path)[0] except IndexError: log.critical('''Couldn't find "{}" in "{}"''',...
[ "def", "find_first", "(", "pattern", ":", "str", ",", "path", ":", "str", ")", "->", "str", ":", "try", ":", "return", "find", "(", "pattern", ",", "path", ")", "[", "0", "]", "except", "IndexError", ":", "log", ".", "critical", "(", "'''Couldn't fin...
Finds first file in ``path`` whose filename matches ``pattern`` (via :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`.
[ "Finds", "first", "file", "in", "path", "whose", "filename", "matches", "pattern", "(", "via", ":", "func", ":", "fnmatch", ".", "fnmatch", ")", "or", "raises", ":", "exc", ":", "IndexError", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L398-L407
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
gen_filenames
def gen_filenames(starting_filenames: List[str], recursive: bool) -> Generator[str, None, None]: """ From a starting list of files and/or directories, generates filenames of all files in the list, and (if ``recursive`` is set) all files within directories in the list. Args: ...
python
def gen_filenames(starting_filenames: List[str], recursive: bool) -> Generator[str, None, None]: """ From a starting list of files and/or directories, generates filenames of all files in the list, and (if ``recursive`` is set) all files within directories in the list. Args: ...
[ "def", "gen_filenames", "(", "starting_filenames", ":", "List", "[", "str", "]", ",", "recursive", ":", "bool", ")", "->", "Generator", "[", "str", ",", "None", ",", "None", "]", ":", "for", "base_filename", "in", "starting_filenames", ":", "if", "os", "...
From a starting list of files and/or directories, generates filenames of all files in the list, and (if ``recursive`` is set) all files within directories in the list. Args: starting_filenames: files and/or directories recursive: walk down any directories in the starting list, recursively? ...
[ "From", "a", "starting", "list", "of", "files", "and", "/", "or", "directories", "generates", "filenames", "of", "all", "files", "in", "the", "list", "and", "(", "if", "recursive", "is", "set", ")", "all", "files", "within", "directories", "in", "the", "...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L410-L431
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
exists_locked
def exists_locked(filepath: str) -> Tuple[bool, bool]: """ Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www.ca...
python
def exists_locked(filepath: str) -> Tuple[bool, bool]: """ Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www.ca...
[ "def", "exists_locked", "(", "filepath", ":", "str", ")", "->", "Tuple", "[", "bool", ",", "bool", "]", ":", "exists", "=", "False", "locked", "=", "None", "file_object", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":",...
Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www.calazan.com/how-to-check-if-a-file-is-locked-in-python/.
[ "Checks", "if", "a", "file", "is", "locked", "by", "opening", "it", "in", "append", "mode", ".", "(", "If", "no", "exception", "is", "thrown", "in", "that", "situation", "then", "the", "file", "is", "not", "locked", ".", ")" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L438-L468
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
relative_filename_within_dir
def relative_filename_within_dir(filename: str, directory: str) -> str: """ Starting with a (typically absolute) ``filename``, returns the part of the filename that is relative to the directory ``directory``. If the file is *not* within the directory, returns an empty string. """ filename = os.p...
python
def relative_filename_within_dir(filename: str, directory: str) -> str: """ Starting with a (typically absolute) ``filename``, returns the part of the filename that is relative to the directory ``directory``. If the file is *not* within the directory, returns an empty string. """ filename = os.p...
[ "def", "relative_filename_within_dir", "(", "filename", ":", "str", ",", "directory", ":", "str", ")", "->", "str", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "directory", "=", "os", ".", "path", ".", "abspath", "(", ...
Starting with a (typically absolute) ``filename``, returns the part of the filename that is relative to the directory ``directory``. If the file is *not* within the directory, returns an empty string.
[ "Starting", "with", "a", "(", "typically", "absolute", ")", "filename", "returns", "the", "part", "of", "the", "filename", "that", "is", "relative", "to", "the", "directory", "directory", ".", "If", "the", "file", "is", "*", "not", "*", "within", "the", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L475-L486
smtp2go-oss/smtp2go-python
smtp2go/core.py
Smtp2goResponse._get_errors
def _get_errors(self): """ Gets errors from HTTP response """ errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
python
def _get_errors(self): """ Gets errors from HTTP response """ errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
[ "def", "_get_errors", "(", "self", ")", ":", "errors", "=", "self", ".", "json", ".", "get", "(", "'data'", ")", ".", "get", "(", "'failures'", ")", "if", "errors", ":", "logger", ".", "error", "(", "errors", ")", "return", "errors" ]
Gets errors from HTTP response
[ "Gets", "errors", "from", "HTTP", "response" ]
train
https://github.com/smtp2go-oss/smtp2go-python/blob/581cc33b1c6f4ca2882535a51a787c33e5cfcce7/smtp2go/core.py#L120-L127
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
page_sequence
def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: """ Generates the final page sequence from the starting number of sheets. """ n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_pages = n_pages // 2 firsthalf = list(range(half_n_pages)) secondha...
python
def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: """ Generates the final page sequence from the starting number of sheets. """ n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_pages = n_pages // 2 firsthalf = list(range(half_n_pages)) secondha...
[ "def", "page_sequence", "(", "n_sheets", ":", "int", ",", "one_based", ":", "bool", "=", "True", ")", "->", "List", "[", "int", "]", ":", "n_pages", "=", "calc_n_virtual_pages", "(", "n_sheets", ")", "assert", "n_pages", "%", "4", "==", "0", "half_n_page...
Generates the final page sequence from the starting number of sheets.
[ "Generates", "the", "final", "page", "sequence", "from", "the", "starting", "number", "of", "sheets", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L161-L185
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
require
def require(executable: str, explanation: str = "") -> None: """ Ensures that the external tool is available. Asserts upon failure. """ assert shutil.which(executable), "Need {!r} on the PATH.{}".format( executable, "\n" + explanation if explanation else "")
python
def require(executable: str, explanation: str = "") -> None: """ Ensures that the external tool is available. Asserts upon failure. """ assert shutil.which(executable), "Need {!r} on the PATH.{}".format( executable, "\n" + explanation if explanation else "")
[ "def", "require", "(", "executable", ":", "str", ",", "explanation", ":", "str", "=", "\"\"", ")", "->", "None", ":", "assert", "shutil", ".", "which", "(", "executable", ")", ",", "\"Need {!r} on the PATH.{}\"", ".", "format", "(", "executable", ",", "\"\...
Ensures that the external tool is available. Asserts upon failure.
[ "Ensures", "that", "the", "external", "tool", "is", "available", ".", "Asserts", "upon", "failure", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L192-L198
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
run
def run(args: List[str], get_output: bool = False, encoding: str = sys.getdefaultencoding()) -> Tuple[str, str]: """ Run an external command +/- return the results. Returns a ``(stdout, stderr)`` tuple (both are blank strings if the output wasn't wanted). """ printable = " ".join...
python
def run(args: List[str], get_output: bool = False, encoding: str = sys.getdefaultencoding()) -> Tuple[str, str]: """ Run an external command +/- return the results. Returns a ``(stdout, stderr)`` tuple (both are blank strings if the output wasn't wanted). """ printable = " ".join...
[ "def", "run", "(", "args", ":", "List", "[", "str", "]", ",", "get_output", ":", "bool", "=", "False", ",", "encoding", ":", "str", "=", "sys", ".", "getdefaultencoding", "(", ")", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "printable", ...
Run an external command +/- return the results. Returns a ``(stdout, stderr)`` tuple (both are blank strings if the output wasn't wanted).
[ "Run", "an", "external", "command", "+", "/", "-", "return", "the", "results", ".", "Returns", "a", "(", "stdout", "stderr", ")", "tuple", "(", "both", "are", "blank", "strings", "if", "the", "output", "wasn", "t", "wanted", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L201-L218
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
get_page_count
def get_page_count(filename: str) -> int: """ How many pages are in a PDF? """ log.debug("Getting page count for {!r}", filename) require(PDFTK, HELP_MISSING_PDFTK) stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True) regex = re.compile(r"^NumberOfPages: (\d+)$", re.MULTILINE) ...
python
def get_page_count(filename: str) -> int: """ How many pages are in a PDF? """ log.debug("Getting page count for {!r}", filename) require(PDFTK, HELP_MISSING_PDFTK) stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True) regex = re.compile(r"^NumberOfPages: (\d+)$", re.MULTILINE) ...
[ "def", "get_page_count", "(", "filename", ":", "str", ")", "->", "int", ":", "log", ".", "debug", "(", "\"Getting page count for {!r}\"", ",", "filename", ")", "require", "(", "PDFTK", ",", "HELP_MISSING_PDFTK", ")", "stdout", ",", "_", "=", "run", "(", "[...
How many pages are in a PDF?
[ "How", "many", "pages", "are", "in", "a", "PDF?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L221-L232
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
make_blank_pdf
def make_blank_pdf(filename: str, paper: str = "A4") -> None: """ NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``. """ # https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line # noqa require(CONVERT, HELP_MISSING_IMAGEMAGICK) ...
python
def make_blank_pdf(filename: str, paper: str = "A4") -> None: """ NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``. """ # https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line # noqa require(CONVERT, HELP_MISSING_IMAGEMAGICK) ...
[ "def", "make_blank_pdf", "(", "filename", ":", "str", ",", "paper", ":", "str", "=", "\"A4\"", ")", "->", "None", ":", "# https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line # noqa", "require", "(", "CONVERT", ",", "HELP_MISSIN...
NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``.
[ "NOT", "USED", ".", "Makes", "a", "blank", "single", "-", "page", "PDF", "using", "ImageMagick", "s", "convert", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L235-L242
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
slice_pdf
def slice_pdf(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int) -> str: """ Slice each page of the original, to convert to "one real page per PDF page". Return the output filename. """ if slice_horiz == 1 and slice_vert == 1: log.debug("No slicing re...
python
def slice_pdf(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int) -> str: """ Slice each page of the original, to convert to "one real page per PDF page". Return the output filename. """ if slice_horiz == 1 and slice_vert == 1: log.debug("No slicing re...
[ "def", "slice_pdf", "(", "input_filename", ":", "str", ",", "output_filename", ":", "str", ",", "slice_horiz", ":", "int", ",", "slice_vert", ":", "int", ")", "->", "str", ":", "if", "slice_horiz", "==", "1", "and", "slice_vert", "==", "1", ":", "log", ...
Slice each page of the original, to convert to "one real page per PDF page". Return the output filename.
[ "Slice", "each", "page", "of", "the", "original", "to", "convert", "to", "one", "real", "page", "per", "PDF", "page", ".", "Return", "the", "output", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L245-L266
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
booklet_nup_pdf
def booklet_nup_pdf(input_filename: str, output_filename: str, latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> str: """ Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4). The booklet can be folded like a book and the final pages will be in order. Returns the output fil...
python
def booklet_nup_pdf(input_filename: str, output_filename: str, latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> str: """ Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4). The booklet can be folded like a book and the final pages will be in order. Returns the output fil...
[ "def", "booklet_nup_pdf", "(", "input_filename", ":", "str", ",", "output_filename", ":", "str", ",", "latex_paper_size", ":", "str", "=", "LATEX_PAPER_SIZE_A4", ")", "->", "str", ":", "log", ".", "info", "(", "\"Creating booklet\"", ")", "log", ".", "debug", ...
Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4). The booklet can be folded like a book and the final pages will be in order. Returns the output filename.
[ "Takes", "a", "PDF", "(", "e", ".", "g", ".", "A4", ")", "and", "makes", "a", "2x1", "booklet", "(", "e", ".", "g", ".", "2xA5", "per", "A4", ")", ".", "The", "booklet", "can", "be", "folded", "like", "a", "book", "and", "the", "final", "pages"...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L269-L301
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
rotate_even_pages_180
def rotate_even_pages_180(input_filename: str, output_filename: str) -> str: """ Rotates even-numbered pages 180 degrees. Returns the output filename. """ log.info("Rotating even-numbered pages 180 degrees for long-edge " "duplex printing") log.debug("... {!r} -> {!r}", input_filena...
python
def rotate_even_pages_180(input_filename: str, output_filename: str) -> str: """ Rotates even-numbered pages 180 degrees. Returns the output filename. """ log.info("Rotating even-numbered pages 180 degrees for long-edge " "duplex printing") log.debug("... {!r} -> {!r}", input_filena...
[ "def", "rotate_even_pages_180", "(", "input_filename", ":", "str", ",", "output_filename", ":", "str", ")", "->", "str", ":", "log", ".", "info", "(", "\"Rotating even-numbered pages 180 degrees for long-edge \"", "\"duplex printing\"", ")", "log", ".", "debug", "(", ...
Rotates even-numbered pages 180 degrees. Returns the output filename.
[ "Rotates", "even", "-", "numbered", "pages", "180", "degrees", ".", "Returns", "the", "output", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L304-L323
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
convert_to_foldable
def convert_to_foldable(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int, overwrite: bool = False, longedge: bool = False, latex_paper_size: str = L...
python
def convert_to_foldable(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int, overwrite: bool = False, longedge: bool = False, latex_paper_size: str = L...
[ "def", "convert_to_foldable", "(", "input_filename", ":", "str", ",", "output_filename", ":", "str", ",", "slice_horiz", ":", "int", ",", "slice_vert", ":", "int", ",", "overwrite", ":", "bool", "=", "False", ",", "longedge", ":", "bool", "=", "False", ","...
Runs a chain of tasks to convert a PDF to a useful booklet PDF.
[ "Runs", "a", "chain", "of", "tasks", "to", "convert", "a", "PDF", "to", "a", "useful", "booklet", "PDF", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L326-L377
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
main
def main() -> None: """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "input_file", help="Inp...
python
def main() -> None: """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "input_file", help="Inp...
[ "def", "main", "(", ")", "->", "None", ":", "main_only_quicksetup_rootlogger", "(", "level", "=", "logging", ".", "DEBUG", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", ...
Command-line processor. See ``--help`` for details.
[ "Command", "-", "line", "processor", ".", "See", "--", "help", "for", "details", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L397-L448
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/estimate_mysql_memory_usage.py
get_mysql_vars
def get_mysql_vars(mysql: str, host: str, port: int, user: str) -> Dict[str, str]: """ Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name port: TCP/IP port number user: ...
python
def get_mysql_vars(mysql: str, host: str, port: int, user: str) -> Dict[str, str]: """ Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name port: TCP/IP port number user: ...
[ "def", "get_mysql_vars", "(", "mysql", ":", "str", ",", "host", ":", "str", ",", "port", ":", "int", ",", "user", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "cmdargs", "=", "[", "mysql", ",", "\"-h\"", ",", "host", ",", "\...
Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name port: TCP/IP port number user: username Returns: dictionary of MySQL variables/values
[ "Asks", "MySQL", "for", "its", "variables", "and", "status", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/estimate_mysql_memory_usage.py#L54-L88
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/estimate_mysql_memory_usage.py
val_mb
def val_mb(valstr: Union[int, str]) -> str: """ Converts a value in bytes (in string format) to megabytes. """ try: return "{:.3f}".format(int(valstr) / (1024 * 1024)) except (TypeError, ValueError): return '?'
python
def val_mb(valstr: Union[int, str]) -> str: """ Converts a value in bytes (in string format) to megabytes. """ try: return "{:.3f}".format(int(valstr) / (1024 * 1024)) except (TypeError, ValueError): return '?'
[ "def", "val_mb", "(", "valstr", ":", "Union", "[", "int", ",", "str", "]", ")", "->", "str", ":", "try", ":", "return", "\"{:.3f}\"", ".", "format", "(", "int", "(", "valstr", ")", "/", "(", "1024", "*", "1024", ")", ")", "except", "(", "TypeErro...
Converts a value in bytes (in string format) to megabytes.
[ "Converts", "a", "value", "in", "bytes", "(", "in", "string", "format", ")", "to", "megabytes", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/estimate_mysql_memory_usage.py#L91-L98
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/estimate_mysql_memory_usage.py
add_var_mb
def add_var_mb(table: PrettyTable, vardict: Dict[str, str], varname: str) -> None: """ Adds a row to ``table`` for ``varname``, in megabytes. """ valstr = vardict.get(varname, None) table.add_row([varname, val_mb(valstr), UNITS_MB])
python
def add_var_mb(table: PrettyTable, vardict: Dict[str, str], varname: str) -> None: """ Adds a row to ``table`` for ``varname``, in megabytes. """ valstr = vardict.get(varname, None) table.add_row([varname, val_mb(valstr), UNITS_MB])
[ "def", "add_var_mb", "(", "table", ":", "PrettyTable", ",", "vardict", ":", "Dict", "[", "str", ",", "str", "]", ",", "varname", ":", "str", ")", "->", "None", ":", "valstr", "=", "vardict", ".", "get", "(", "varname", ",", "None", ")", "table", "....
Adds a row to ``table`` for ``varname``, in megabytes.
[ "Adds", "a", "row", "to", "table", "for", "varname", "in", "megabytes", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/estimate_mysql_memory_usage.py#L108-L115
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/estimate_mysql_memory_usage.py
main
def main(): """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument( "--mysql", default="mysql", help="MySQL program (default=mysql)") parser.add_argument( ...
python
def main(): """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument( "--mysql", default="mysql", help="MySQL program (default=mysql)") parser.add_argument( ...
[ "def", "main", "(", ")", ":", "main_only_quicksetup_rootlogger", "(", "level", "=", "logging", ".", "DEBUG", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--mysql\"", ",", "default", "=", "\"mysql\"", ...
Command-line processor. See ``--help`` for details.
[ "Command", "-", "line", "processor", ".", "See", "--", "help", "for", "details", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/estimate_mysql_memory_usage.py#L125-L201
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/grep_in_openxml.py
report_hit_filename
def report_hit_filename(zipfilename: str, contentsfilename: str, show_inner_file: bool) -> None: """ For "hits": prints either the ``.zip`` filename, or the ``.zip`` filename and the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilenam...
python
def report_hit_filename(zipfilename: str, contentsfilename: str, show_inner_file: bool) -> None: """ For "hits": prints either the ``.zip`` filename, or the ``.zip`` filename and the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilenam...
[ "def", "report_hit_filename", "(", "zipfilename", ":", "str", ",", "contentsfilename", ":", "str", ",", "show_inner_file", ":", "bool", ")", "->", "None", ":", "if", "show_inner_file", ":", "print", "(", "\"{} [{}]\"", ".", "format", "(", "zipfilename", ",", ...
For "hits": prints either the ``.zip`` filename, or the ``.zip`` filename and the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file show_inner_file: if ``True``, show both; if ``False``, show just the ``.zip`` filen...
[ "For", "hits", ":", "prints", "either", "the", ".", "zip", "filename", "or", "the", ".", "zip", "filename", "and", "the", "inner", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/grep_in_openxml.py#L57-L75
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/grep_in_openxml.py
report_line
def report_line(zipfilename: str, contentsfilename: str, line: str, show_inner_file: bool) -> None: """ Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filena...
python
def report_line(zipfilename: str, contentsfilename: str, line: str, show_inner_file: bool) -> None: """ Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filena...
[ "def", "report_line", "(", "zipfilename", ":", "str", ",", "contentsfilename", ":", "str", ",", "line", ":", "str", ",", "show_inner_file", ":", "bool", ")", "->", "None", ":", "if", "show_inner_file", ":", "print", "(", "\"{} [{}]: {}\"", ".", "format", "...
Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file line: the line from the inner file show_inner_file: if ``True``, show both filenames; if ``...
[ "Prints", "a", "line", "from", "a", "file", "with", "the", ".", "zip", "filename", "and", "optionally", "also", "the", "inner", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/grep_in_openxml.py#L85-L101
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/grep_in_openxml.py
parse_zip
def parse_zip(zipfilename: str, regex: Pattern, invert_match: bool, files_with_matches: bool, files_without_match: bool, grep_inner_file_name: bool, show_inner_file: bool) -> None: """ Implement a "grep within an OpenXML file" f...
python
def parse_zip(zipfilename: str, regex: Pattern, invert_match: bool, files_with_matches: bool, files_without_match: bool, grep_inner_file_name: bool, show_inner_file: bool) -> None: """ Implement a "grep within an OpenXML file" f...
[ "def", "parse_zip", "(", "zipfilename", ":", "str", ",", "regex", ":", "Pattern", ",", "invert_match", ":", "bool", ",", "files_with_matches", ":", "bool", ",", "files_without_match", ":", "bool", ",", "grep_inner_file_name", ":", "bool", ",", "show_inner_file",...
Implement a "grep within an OpenXML file" for a single OpenXML file, which is by definition a ``.zip`` file. Args: zipfilename: name of the OpenXML (zip) file regex: regular expression to match invert_match: find files that do NOT match, instead of ones that do? files_with_match...
[ "Implement", "a", "grep", "within", "an", "OpenXML", "file", "for", "a", "single", "OpenXML", "file", "which", "is", "by", "definition", "a", ".", "zip", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/grep_in_openxml.py#L104-L176
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/grep_in_openxml.py
main
def main() -> None: """ Command-line handler for the ``grep_in_openxml`` tool. Use the ``--help`` option for help. """ parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, description=""" Performs a grep (global-regular-expression-print) search of files in OpenXML fo...
python
def main() -> None: """ Command-line handler for the ``grep_in_openxml`` tool. Use the ``--help`` option for help. """ parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, description=""" Performs a grep (global-regular-expression-print) search of files in OpenXML fo...
[ "def", "main", "(", ")", "->", "None", ":", "parser", "=", "ArgumentParser", "(", "formatter_class", "=", "RawDescriptionHelpFormatter", ",", "description", "=", "\"\"\"\nPerforms a grep (global-regular-expression-print) search of files in OpenXML\nformat, which is to say inside ZI...
Command-line handler for the ``grep_in_openxml`` tool. Use the ``--help`` option for help.
[ "Command", "-", "line", "handler", "for", "the", "grep_in_openxml", "tool", ".", "Use", "the", "--", "help", "option", "for", "help", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/grep_in_openxml.py#L179-L297
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/timeline.py
drug_timelines
def drug_timelines( drug_events_df: DataFrame, event_lasts_for: datetime.timedelta, patient_colname: str = DEFAULT_PATIENT_COLNAME, event_datetime_colname: str = DEFAULT_DRUG_EVENT_DATETIME_COLNAME) \ -> Dict[Any, IntervalList]: """ Takes a set of drug event start ...
python
def drug_timelines( drug_events_df: DataFrame, event_lasts_for: datetime.timedelta, patient_colname: str = DEFAULT_PATIENT_COLNAME, event_datetime_colname: str = DEFAULT_DRUG_EVENT_DATETIME_COLNAME) \ -> Dict[Any, IntervalList]: """ Takes a set of drug event start ...
[ "def", "drug_timelines", "(", "drug_events_df", ":", "DataFrame", ",", "event_lasts_for", ":", "datetime", ".", "timedelta", ",", "patient_colname", ":", "str", "=", "DEFAULT_PATIENT_COLNAME", ",", "event_datetime_colname", ":", "str", "=", "DEFAULT_DRUG_EVENT_DATETIME_...
Takes a set of drug event start times (one or more per patient), plus a fixed time that each event is presumed to last for, and returns an :class:`IntervalList` for each patient representing the set of events (which may overlap, in which case they will be amalgamated). Args: drug_events_d...
[ "Takes", "a", "set", "of", "drug", "event", "start", "times", "(", "one", "or", "more", "per", "patient", ")", "plus", "a", "fixed", "time", "that", "each", "event", "is", "presumed", "to", "last", "for", "and", "returns", "an", ":", "class", ":", "I...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/timeline.py#L252-L293
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/timeline.py
cumulative_time_on_drug
def cumulative_time_on_drug( drug_events_df: DataFrame, query_times_df: DataFrame, event_lasts_for_timedelta: datetime.timedelta = None, event_lasts_for_quantity: float = None, event_lasts_for_units: str = None, patient_colname: str = DEFAULT_PATIENT_COLNAME, ...
python
def cumulative_time_on_drug( drug_events_df: DataFrame, query_times_df: DataFrame, event_lasts_for_timedelta: datetime.timedelta = None, event_lasts_for_quantity: float = None, event_lasts_for_units: str = None, patient_colname: str = DEFAULT_PATIENT_COLNAME, ...
[ "def", "cumulative_time_on_drug", "(", "drug_events_df", ":", "DataFrame", ",", "query_times_df", ":", "DataFrame", ",", "event_lasts_for_timedelta", ":", "datetime", ".", "timedelta", "=", "None", ",", "event_lasts_for_quantity", ":", "float", "=", "None", ",", "ev...
Args: drug_events_df: pandas :class:`DataFrame` containing the event data, with columns named according to ``patient_colname``, ``event_datetime_colname`` event_lasts_for_timedelta: when an event occurs, how long is it assumed to last for? For exampl...
[ "Args", ":", "drug_events_df", ":", "pandas", ":", "class", ":", "DataFrame", "containing", "the", "event", "data", "with", "columns", "named", "according", "to", "patient_colname", "event_datetime_colname", "event_lasts_for_timedelta", ":", "when", "an", "event", "...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/timeline.py#L315-L451
ivanprjcts/sdklib
sdklib/html/base.py
HTMLLxmlMixin.find_element_by_xpath
def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ """ elems = self.find_elements_by_xp...
python
def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ """ elems = self.find_elements_by_xp...
[ "def", "find_element_by_xpath", "(", "self", ",", "xpath", ")", ":", "elems", "=", "self", ".", "find_elements_by_xpath", "(", "xpath", ")", "if", "isinstance", "(", "elems", ",", "list", ")", "and", "len", "(", "elems", ")", ">", "0", ":", "return", "...
Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_
[ "Finds", "an", "element", "by", "xpath", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/html/base.py#L88-L99
ivanprjcts/sdklib
sdklib/html/base.py
HTMLLxmlMixin.find_elements_by_xpath
def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: list of ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ """ from sdklib...
python
def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: list of ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ """ from sdklib...
[ "def", "find_elements_by_xpath", "(", "self", ",", "xpath", ")", ":", "from", "sdklib", ".", "html", ".", "elem", "import", "ElemLxml", "elements", "=", "self", ".", "html_obj", ".", "xpath", "(", "xpath", ")", "return", "[", "ElemLxml", "(", "e", ")", ...
Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: list of ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_
[ "Finds", "multiple", "elements", "by", "xpath", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/html/base.py#L101-L113
ivanprjcts/sdklib
sdklib/html/base.py
HTML5libMixin.find_element_by_xpath
def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ """ ...
python
def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ """ ...
[ "def", "find_element_by_xpath", "(", "self", ",", "xpath", ")", ":", "from", "sdklib", ".", "html", ".", "elem", "import", "Elem5lib", "return", "Elem5lib", "(", "self", ".", "html_obj", ".", "find", "(", "self", ".", "_convert_xpath", "(", "xpath", ")", ...
Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_
[ "Finds", "an", "element", "by", "xpath", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/html/base.py#L121-L132
ivanprjcts/sdklib
sdklib/html/base.py
HTML5libMixin.find_elements_by_xpath
def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ ...
python
def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ ...
[ "def", "find_elements_by_xpath", "(", "self", ",", "xpath", ")", ":", "from", "sdklib", ".", "html", ".", "elem", "import", "Elem5lib", "return", "[", "Elem5lib", "(", "e", ")", "for", "e", "in", "self", ".", "html_obj", ".", "findall", "(", "self", "....
Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_
[ "Finds", "multiple", "elements", "by", "xpath", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/html/base.py#L134-L145
ivanprjcts/sdklib
sdklib/behave/response.py
http_response_body_should_be_this_json
def http_response_body_should_be_this_json(context): """ Parameters: .. code-block:: json { "param1": "value1", "param2": "value2", "param3": { "param31": "value31" } } """ body_params =...
python
def http_response_body_should_be_this_json(context): """ Parameters: .. code-block:: json { "param1": "value1", "param2": "value2", "param3": { "param31": "value31" } } """ body_params =...
[ "def", "http_response_body_should_be_this_json", "(", "context", ")", ":", "body_params", "=", "json", ".", "loads", "(", "context", ".", "text", ")", "assert", "body_params", "==", "context", ".", "api_response", ".", "data", ",", "\"Expected: {}; Message: {}\"", ...
Parameters: .. code-block:: json { "param1": "value1", "param2": "value2", "param3": { "param31": "value31" } }
[ "Parameters", ":" ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/response.py#L63-L79
calston/rhumba
rhumba/backends/zk.py
Backend.queue
def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } ser = json.dumps(d) if uids: ...
python
def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } ser = json.dumps(d) if uids: ...
[ "def", "queue", "(", "self", ",", "queue", ",", "message", ",", "params", "=", "{", "}", ",", "uids", "=", "[", "]", ")", ":", "d", "=", "{", "'id'", ":", "uuid", ".", "uuid1", "(", ")", ".", "get_hex", "(", ")", ",", "'version'", ":", "1", ...
Queue a job in Rhumba
[ "Queue", "a", "job", "in", "Rhumba" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/backends/zk.py#L168-L191
calston/rhumba
rhumba/backends/zk.py
Backend.clusterStatus
def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ servers = yield self.getClusterServers() d = { 'workers': {}, 'crons': {}, 'queues': {} } now = time.time() reverse_map = {...
python
def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ servers = yield self.getClusterServers() d = { 'workers': {}, 'crons': {}, 'queues': {} } now = time.time() reverse_map = {...
[ "def", "clusterStatus", "(", "self", ")", ":", "servers", "=", "yield", "self", ".", "getClusterServers", "(", ")", "d", "=", "{", "'workers'", ":", "{", "}", ",", "'crons'", ":", "{", "}", ",", "'queues'", ":", "{", "}", "}", "now", "=", "time", ...
Returns a dict of cluster nodes and their status information
[ "Returns", "a", "dict", "of", "cluster", "nodes", "and", "their", "status", "information" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/backends/zk.py#L382-L454
RudolfCardinal/pythonlib
cardinal_pythonlib/deform_utils.py
get_head_form_html
def get_head_form_html(req: "Request", forms: List[Form]) -> str: """ Returns the extra HTML that needs to be injected into the ``<head>`` section for a Deform form to work properly. """ # https://docs.pylonsproject.org/projects/deform/en/latest/widget.html#widget-requirements js_resources = [] ...
python
def get_head_form_html(req: "Request", forms: List[Form]) -> str: """ Returns the extra HTML that needs to be injected into the ``<head>`` section for a Deform form to work properly. """ # https://docs.pylonsproject.org/projects/deform/en/latest/widget.html#widget-requirements js_resources = [] ...
[ "def", "get_head_form_html", "(", "req", ":", "\"Request\"", ",", "forms", ":", "List", "[", "Form", "]", ")", "->", "str", ":", "# https://docs.pylonsproject.org/projects/deform/en/latest/widget.html#widget-requirements", "js_resources", "=", "[", "]", "# type: List[str]...
Returns the extra HTML that needs to be injected into the ``<head>`` section for a Deform form to work properly.
[ "Returns", "the", "extra", "HTML", "that", "needs", "to", "be", "injected", "into", "the", "<head", ">", "section", "for", "a", "Deform", "form", "to", "work", "properly", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/deform_utils.py#L58-L81
RudolfCardinal/pythonlib
cardinal_pythonlib/deform_utils.py
debug_validator
def debug_validator(validator: ValidatorType) -> ValidatorType: """ Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, a...
python
def debug_validator(validator: ValidatorType) -> ValidatorType: """ Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, a...
[ "def", "debug_validator", "(", "validator", ":", "ValidatorType", ")", "->", "ValidatorType", ":", "def", "_validate", "(", "node", ":", "SchemaNode", ",", "value", ":", "Any", ")", "->", "None", ":", "log", ".", "debug", "(", "\"Validating: {!r}\"", ",", ...
Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, and whether it accepted or rejected the value).
[ "Use", "as", "a", "wrapper", "around", "a", "validator", "e", ".", "g", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/deform_utils.py#L178-L198
RudolfCardinal/pythonlib
cardinal_pythonlib/deform_utils.py
gen_fields
def gen_fields(field: Field) -> Generator[Field, None, None]: """ Starting with a Deform :class:`Field`, yield the field itself and any children. """ yield field for c in field.children: for f in gen_fields(c): yield f
python
def gen_fields(field: Field) -> Generator[Field, None, None]: """ Starting with a Deform :class:`Field`, yield the field itself and any children. """ yield field for c in field.children: for f in gen_fields(c): yield f
[ "def", "gen_fields", "(", "field", ":", "Field", ")", "->", "Generator", "[", "Field", ",", "None", ",", "None", "]", ":", "yield", "field", "for", "c", "in", "field", ".", "children", ":", "for", "f", "in", "gen_fields", "(", "c", ")", ":", "yield...
Starting with a Deform :class:`Field`, yield the field itself and any children.
[ "Starting", "with", "a", "Deform", ":", "class", ":", "Field", "yield", "the", "field", "itself", "and", "any", "children", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/deform_utils.py#L205-L213
RudolfCardinal/pythonlib
cardinal_pythonlib/deform_utils.py
InformativeForm.validate
def validate(self, controls: Iterable[Tuple[str, str]], subcontrol: str = None) -> Any: """ Validates the form. Args: controls: an iterable of ``(key, value)`` tuples subcontrol: Returns: a Colander ``appstruct`` ...
python
def validate(self, controls: Iterable[Tuple[str, str]], subcontrol: str = None) -> Any: """ Validates the form. Args: controls: an iterable of ``(key, value)`` tuples subcontrol: Returns: a Colander ``appstruct`` ...
[ "def", "validate", "(", "self", ",", "controls", ":", "Iterable", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "subcontrol", ":", "str", "=", "None", ")", "->", "Any", ":", "try", ":", "return", "super", "(", ")", ".", "validate", "(", "c...
Validates the form. Args: controls: an iterable of ``(key, value)`` tuples subcontrol: Returns: a Colander ``appstruct`` Raises: ValidationFailure: on failure
[ "Validates", "the", "form", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/deform_utils.py#L112-L135
The-Politico/politico-civic-geography
geography/models/division_level.py
DivisionLevel.save
def save(self, *args, **kwargs): """ **uid**: :code:`{levelcode}` """ self.slug = slugify(self.name) self.uid = self.slug super(DivisionLevel, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ **uid**: :code:`{levelcode}` """ self.slug = slugify(self.name) self.uid = self.slug super(DivisionLevel, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "slug", "=", "slugify", "(", "self", ".", "name", ")", "self", ".", "uid", "=", "self", ".", "slug", "super", "(", "DivisionLevel", ",", "self", ")", ...
**uid**: :code:`{levelcode}`
[ "**", "uid", "**", ":", ":", "code", ":", "{", "levelcode", "}" ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division_level.py#L47-L53
Vauxoo/pstats-print2list
pstats_print2list/pstats_print2list.py
get_pstats_print2list
def get_pstats_print2list(fnames, filter_fnames=None, exclude_fnames=None, sort=None, sort_reverse=None, limit=None): """Print stats with a filter or exclude filenames, sort index and limit. :param list fnames: cProfile standard files to process. :param list filter_fnames: Relative...
python
def get_pstats_print2list(fnames, filter_fnames=None, exclude_fnames=None, sort=None, sort_reverse=None, limit=None): """Print stats with a filter or exclude filenames, sort index and limit. :param list fnames: cProfile standard files to process. :param list filter_fnames: Relative...
[ "def", "get_pstats_print2list", "(", "fnames", ",", "filter_fnames", "=", "None", ",", "exclude_fnames", "=", "None", ",", "sort", "=", "None", ",", "sort_reverse", "=", "None", ",", "limit", "=", "None", ")", ":", "if", "isinstance", "(", "fnames", ",", ...
Print stats with a filter or exclude filenames, sort index and limit. :param list fnames: cProfile standard files to process. :param list filter_fnames: Relative paths to filter and show them. :param list exclude_fnames: Relative paths to avoid show them. :param str sort: Standard `pstats` key of value ...
[ "Print", "stats", "with", "a", "filter", "or", "exclude", "filenames", "sort", "index", "and", "limit", ".", ":", "param", "list", "fnames", ":", "cProfile", "standard", "files", "to", "process", ".", ":", "param", "list", "filter_fnames", ":", "Relative", ...
train
https://github.com/Vauxoo/pstats-print2list/blob/a5ebf1790ed450c12103a665b7f49eb1982a8428/pstats_print2list/pstats_print2list.py#L51-L124
Vauxoo/pstats-print2list
pstats_print2list/pstats_print2list.py
print_pstats_list
def print_pstats_list(pstats, pformat=None): """Print list of pstats dict formatted :param list pstats: pstats dicts to print :param str format: String.format style to show fields with keys: ncalls, tottime, tt_percall, cumtime, ct_percall, file, lineno, method rcalls, calls :return: Dir...
python
def print_pstats_list(pstats, pformat=None): """Print list of pstats dict formatted :param list pstats: pstats dicts to print :param str format: String.format style to show fields with keys: ncalls, tottime, tt_percall, cumtime, ct_percall, file, lineno, method rcalls, calls :return: Dir...
[ "def", "print_pstats_list", "(", "pstats", ",", "pformat", "=", "None", ")", ":", "if", "not", "pstats", ":", "return", "False", "if", "pformat", "is", "None", ":", "pformat", "=", "(", "\"{method:<40s} {factor:>16s} {cumtime:>10s} \"", "\"{calls:>10s} {rcalls:>10s}...
Print list of pstats dict formatted :param list pstats: pstats dicts to print :param str format: String.format style to show fields with keys: ncalls, tottime, tt_percall, cumtime, ct_percall, file, lineno, method rcalls, calls :return: Directly print of result formatted and return True
[ "Print", "list", "of", "pstats", "dict", "formatted", ":", "param", "list", "pstats", ":", "pstats", "dicts", "to", "print", ":", "param", "str", "format", ":", "String", ".", "format", "style", "to", "show", "fields", "with", "keys", ":", "ncalls", "tot...
train
https://github.com/Vauxoo/pstats-print2list/blob/a5ebf1790ed450c12103a665b7f49eb1982a8428/pstats_print2list/pstats_print2list.py#L127-L143
Netuitive/netuitive-client-python
netuitive/element.py
Element.merge_metrics
def merge_metrics(self): """ Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics """ self.metrics.extend(self._metrics.values()) del self._metrics
python
def merge_metrics(self): """ Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics """ self.metrics.extend(self._metrics.values()) del self._metrics
[ "def", "merge_metrics", "(", "self", ")", ":", "self", ".", "metrics", ".", "extend", "(", "self", ".", "_metrics", ".", "values", "(", ")", ")", "del", "self", ".", "_metrics" ]
Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics
[ "Merge", "metrics", "in", "the", "internal", "_metrics", "dict", "to", "metrics", "list", "and", "delete", "the", "internal", "_metrics" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/element.py#L43-L50
Netuitive/netuitive-client-python
netuitive/element.py
Element.add_attribute
def add_attribute(self, name, value): """ :param name: Name of the attribute :type name: string :param value: Value of the attribute :type value: string """ self.attributes.append(Attribute(name, value))
python
def add_attribute(self, name, value): """ :param name: Name of the attribute :type name: string :param value: Value of the attribute :type value: string """ self.attributes.append(Attribute(name, value))
[ "def", "add_attribute", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "attributes", ".", "append", "(", "Attribute", "(", "name", ",", "value", ")", ")" ]
:param name: Name of the attribute :type name: string :param value: Value of the attribute :type value: string
[ ":", "param", "name", ":", "Name", "of", "the", "attribute", ":", "type", "name", ":", "string", ":", "param", "value", ":", "Value", "of", "the", "attribute", ":", "type", "value", ":", "string" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/element.py#L52-L60
Netuitive/netuitive-client-python
netuitive/element.py
Element.add_tag
def add_tag(self, name, value): """ :param name: Name of the tag :type name: string :param value: Value of the tag :type value: string """ self.tags.append(Tag(name, value))
python
def add_tag(self, name, value): """ :param name: Name of the tag :type name: string :param value: Value of the tag :type value: string """ self.tags.append(Tag(name, value))
[ "def", "add_tag", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "tags", ".", "append", "(", "Tag", "(", "name", ",", "value", ")", ")" ]
:param name: Name of the tag :type name: string :param value: Value of the tag :type value: string
[ ":", "param", "name", ":", "Name", "of", "the", "tag", ":", "type", "name", ":", "string", ":", "param", "value", ":", "Value", "of", "the", "tag", ":", "type", "value", ":", "string" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/element.py#L70-L78
Netuitive/netuitive-client-python
netuitive/element.py
Element.add_sample
def add_sample(self, metricId, timestamp, value, metricType=None, host=None, sparseDataStrategy='None', unit='', tags=None, min=None, ...
python
def add_sample(self, metricId, timestamp, value, metricType=None, host=None, sparseDataStrategy='None', unit='', tags=None, min=None, ...
[ "def", "add_sample", "(", "self", ",", "metricId", ",", "timestamp", ",", "value", ",", "metricType", "=", "None", ",", "host", "=", "None", ",", "sparseDataStrategy", "=", "'None'", ",", "unit", "=", "''", ",", "tags", "=", "None", ",", "min", "=", ...
:param metricId: Metric FQN :type metricId: string :param timestamp: Timestamp for the sample :type timestamp: int :param value: Value of the sample :type value: float :param metricType: Metric Type :type metricType: string ...
[ ":", "param", "metricId", ":", "Metric", "FQN", ":", "type", "metricId", ":", "string", ":", "param", "timestamp", ":", "Timestamp", "for", "the", "sample", ":", "type", "timestamp", ":", "int", ":", "param", "value", ":", "Value", "of", "the", "sample",...
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/element.py#L80-L172
nxdevel/nx_itertools
nx_itertools/extra.py
pairwise
def pairwise(iterable): """Pair each element with its neighbors. Arguments --------- iterable : iterable Returns ------- The generator produces a tuple containing a pairing of each element with its neighbor. """ iterable = iter(iterable) left = next(iterable) for right ...
python
def pairwise(iterable): """Pair each element with its neighbors. Arguments --------- iterable : iterable Returns ------- The generator produces a tuple containing a pairing of each element with its neighbor. """ iterable = iter(iterable) left = next(iterable) for right ...
[ "def", "pairwise", "(", "iterable", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "left", "=", "next", "(", "iterable", ")", "for", "right", "in", "iterable", ":", "yield", "left", ",", "right", "left", "=", "right" ]
Pair each element with its neighbors. Arguments --------- iterable : iterable Returns ------- The generator produces a tuple containing a pairing of each element with its neighbor.
[ "Pair", "each", "element", "with", "its", "neighbors", "." ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L21-L37
nxdevel/nx_itertools
nx_itertools/extra.py
partition
def partition(pred, iterable): """Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple ...
python
def partition(pred, iterable): """Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple ...
[ "def", "partition", "(", "pred", ",", "iterable", ")", ":", "pos", ",", "neg", "=", "[", "]", ",", "[", "]", "pos_append", ",", "neg_append", "=", "pos", ".", "append", ",", "neg", ".", "append", "for", "elem", "in", "iterable", ":", "if", "pred", ...
Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple of lists with the first list containin...
[ "Partition", "an", "iterable", "." ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L40-L66
nxdevel/nx_itertools
nx_itertools/extra.py
powerset
def powerset(iterable, *, reverse=False): """Return the powerset. Arguments --------- iterable : iterable reverse : boolean Indicates whether the powerset should be returned descending by size Returns ------- A generator producing each element of the powe...
python
def powerset(iterable, *, reverse=False): """Return the powerset. Arguments --------- iterable : iterable reverse : boolean Indicates whether the powerset should be returned descending by size Returns ------- A generator producing each element of the powe...
[ "def", "powerset", "(", "iterable", ",", "*", ",", "reverse", "=", "False", ")", ":", "lst", "=", "list", "(", "iterable", ")", "if", "reverse", ":", "rng", "=", "range", "(", "len", "(", "lst", ")", ",", "-", "1", ",", "-", "1", ")", "else", ...
Return the powerset. Arguments --------- iterable : iterable reverse : boolean Indicates whether the powerset should be returned descending by size Returns ------- A generator producing each element of the powerset.
[ "Return", "the", "powerset", "." ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L69-L88
nxdevel/nx_itertools
nx_itertools/extra.py
multi_map
def multi_map(key, iterable, *, default_dict=False): """Collect data into a multi-map. Arguments ---------- key : function A function that accepts an element retrieved from the iterable and returns the key to be used in the multi-map iterable : ite...
python
def multi_map(key, iterable, *, default_dict=False): """Collect data into a multi-map. Arguments ---------- key : function A function that accepts an element retrieved from the iterable and returns the key to be used in the multi-map iterable : ite...
[ "def", "multi_map", "(", "key", ",", "iterable", ",", "*", ",", "default_dict", "=", "False", ")", ":", "result", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "rec", "in", "iterable", ":", "result", "[", "key", "(", "rec", ")", "]...
Collect data into a multi-map. Arguments ---------- key : function A function that accepts an element retrieved from the iterable and returns the key to be used in the multi-map iterable : iterable default_dict : boolean Indicate...
[ "Collect", "data", "into", "a", "multi", "-", "map", "." ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L91-L114
nxdevel/nx_itertools
nx_itertools/extra.py
split
def split(pred, iterable, *, trailing=True): """Split the iterable. Arguments ---------- pred : function A function that accepts an element retrieved from the iterable and returns a boolean indicating if it is the element on which to split iterable :...
python
def split(pred, iterable, *, trailing=True): """Split the iterable. Arguments ---------- pred : function A function that accepts an element retrieved from the iterable and returns a boolean indicating if it is the element on which to split iterable :...
[ "def", "split", "(", "pred", ",", "iterable", ",", "*", ",", "trailing", "=", "True", ")", ":", "result", "=", "[", "]", "result_append", "=", "result", ".", "append", "if", "trailing", ":", "for", "elem", "in", "iterable", ":", "result_append", "(", ...
Split the iterable. Arguments ---------- pred : function A function that accepts an element retrieved from the iterable and returns a boolean indicating if it is the element on which to split iterable : iterable trailing : boolean Indi...
[ "Split", "the", "iterable", "." ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L117-L161
nxdevel/nx_itertools
nx_itertools/extra.py
chunk
def chunk(iterable, length): """Collect data into chunks. Arguments --------- iterable : iterable length : integer Maximum size of each chunk to return Returns ------- The generator produces a tuple of elements whose size is at least one but no more than *length*. ...
python
def chunk(iterable, length): """Collect data into chunks. Arguments --------- iterable : iterable length : integer Maximum size of each chunk to return Returns ------- The generator produces a tuple of elements whose size is at least one but no more than *length*. ...
[ "def", "chunk", "(", "iterable", ",", "length", ")", ":", "if", "length", "<", "0", ":", "return", "(", ")", "iterable", "=", "iter", "(", "iterable", ")", "result", "=", "tuple", "(", "islice", "(", "iterable", ",", "length", ")", ")", "while", "r...
Collect data into chunks. Arguments --------- iterable : iterable length : integer Maximum size of each chunk to return Returns ------- The generator produces a tuple of elements whose size is at least one but no more than *length*. If the number of elements in th...
[ "Collect", "data", "into", "chunks", "." ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L164-L191
nxdevel/nx_itertools
nx_itertools/extra.py
divide
def divide(iterable, n): # pylint: disable=invalid-name """Evenly divide elements. Arguments --------- iterable : iterable n : integer The number of buckets in which to divide the elements Returns ------- The generator produces *n* tuples, each cont...
python
def divide(iterable, n): # pylint: disable=invalid-name """Evenly divide elements. Arguments --------- iterable : iterable n : integer The number of buckets in which to divide the elements Returns ------- The generator produces *n* tuples, each cont...
[ "def", "divide", "(", "iterable", ",", "n", ")", ":", "# pylint: disable=invalid-name", "if", "n", "<=", "0", ":", "return", "[", "]", "data", "=", "list", "(", "iterable", ")", "base", ",", "rem", "=", "divmod", "(", "len", "(", "data", ")", ",", ...
Evenly divide elements. Arguments --------- iterable : iterable n : integer The number of buckets in which to divide the elements Returns ------- The generator produces *n* tuples, each containing a number of elements where the number is calculated to be evenly di...
[ "Evenly", "divide", "elements", "." ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L194-L222
nxdevel/nx_itertools
nx_itertools/extra.py
divide_sizes
def divide_sizes(count, n): # pylint: disable=invalid-name """Evenly divide a count. Arguments --------- count : integer The number to be evenly divided n : integer The number of buckets in which to divide the number Returns ------- A list of int...
python
def divide_sizes(count, n): # pylint: disable=invalid-name """Evenly divide a count. Arguments --------- count : integer The number to be evenly divided n : integer The number of buckets in which to divide the number Returns ------- A list of int...
[ "def", "divide_sizes", "(", "count", ",", "n", ")", ":", "# pylint: disable=invalid-name", "if", "n", "<=", "0", ":", "return", "[", "]", "if", "count", "<", "0", ":", "return", "[", "0", "]", "*", "n", "base", ",", "rem", "=", "divmod", "(", "coun...
Evenly divide a count. Arguments --------- count : integer The number to be evenly divided n : integer The number of buckets in which to divide the number Returns ------- A list of integers indicating what size each bucket should be for an even distribution ...
[ "Evenly", "divide", "a", "count", "." ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L225-L250
AndrewWalker/glud
glud/display.py
dump
def dump(cursor): """ Display the AST represented by the cursor """ def node_children(node): return list(node.get_children()) def print_node(node): text = node.spelling or node.displayname kind = str(node.kind).split('.')[1] return '{} {}'.format(kind, text) return...
python
def dump(cursor): """ Display the AST represented by the cursor """ def node_children(node): return list(node.get_children()) def print_node(node): text = node.spelling or node.displayname kind = str(node.kind).split('.')[1] return '{} {}'.format(kind, text) return...
[ "def", "dump", "(", "cursor", ")", ":", "def", "node_children", "(", "node", ")", ":", "return", "list", "(", "node", ".", "get_children", "(", ")", ")", "def", "print_node", "(", "node", ")", ":", "text", "=", "node", ".", "spelling", "or", "node", ...
Display the AST represented by the cursor
[ "Display", "the", "AST", "represented", "by", "the", "cursor" ]
train
https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/display.py#L4-L16
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
coerce_to_pendulum
def coerce_to_pendulum(x: PotentialDatetimeType, assume_local: bool = False) -> Optional[DateTime]: """ Converts something to a :class:`pendulum.DateTime`. Args: x: something that may be coercible to a datetime assume_local: if ``True``, assume local timezone; if ``Fa...
python
def coerce_to_pendulum(x: PotentialDatetimeType, assume_local: bool = False) -> Optional[DateTime]: """ Converts something to a :class:`pendulum.DateTime`. Args: x: something that may be coercible to a datetime assume_local: if ``True``, assume local timezone; if ``Fa...
[ "def", "coerce_to_pendulum", "(", "x", ":", "PotentialDatetimeType", ",", "assume_local", ":", "bool", "=", "False", ")", "->", "Optional", "[", "DateTime", "]", ":", "if", "not", "x", ":", "# None and blank string", "return", "None", "if", "isinstance", "(", ...
Converts something to a :class:`pendulum.DateTime`. Args: x: something that may be coercible to a datetime assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.DateTime`, or ``None``. Raises: pendulum.parsing.ex...
[ "Converts", "something", "to", "a", ":", "class", ":", "pendulum", ".", "DateTime", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L57-L92
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
coerce_to_pendulum_date
def coerce_to_pendulum_date(x: PotentialDatetimeType, assume_local: bool = False) -> Optional[Date]: """ Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``Fals...
python
def coerce_to_pendulum_date(x: PotentialDatetimeType, assume_local: bool = False) -> Optional[Date]: """ Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``Fals...
[ "def", "coerce_to_pendulum_date", "(", "x", ":", "PotentialDatetimeType", ",", "assume_local", ":", "bool", "=", "False", ")", "->", "Optional", "[", "Date", "]", ":", "p", "=", "coerce_to_pendulum", "(", "x", ",", "assume_local", "=", "assume_local", ")", "...
Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.Date`, or ``None``. Raises: pendulum.parsing.exceptions.Par...
[ "Converts", "something", "to", "a", ":", "class", ":", "pendulum", ".", "Date", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L97-L115
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
pendulum_to_datetime
def pendulum_to_datetime(x: DateTime) -> datetime.datetime: """ Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`. """ return datetime.datetime( x.year, x.month, x.day, x.hour, x.minute, x.secon...
python
def pendulum_to_datetime(x: DateTime) -> datetime.datetime: """ Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`. """ return datetime.datetime( x.year, x.month, x.day, x.hour, x.minute, x.secon...
[ "def", "pendulum_to_datetime", "(", "x", ":", "DateTime", ")", "->", "datetime", ".", "datetime", ":", "return", "datetime", ".", "datetime", "(", "x", ".", "year", ",", "x", ".", "month", ",", "x", ".", "day", ",", "x", ".", "hour", ",", "x", ".",...
Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`.
[ "Used", "for", "example", "where", "a", "database", "backend", "insists", "on", "datetime", ".", "datetime", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L118-L128
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
pendulum_to_utc_datetime_without_tz
def pendulum_to_utc_datetime_without_tz(x: DateTime) -> datetime.datetime: """ Converts a Pendulum ``DateTime`` (which will have timezone information) to a ``datetime.datetime`` that (a) has no timezone information, and (b) is in UTC. Example: .. code-block:: python import pendulum ...
python
def pendulum_to_utc_datetime_without_tz(x: DateTime) -> datetime.datetime: """ Converts a Pendulum ``DateTime`` (which will have timezone information) to a ``datetime.datetime`` that (a) has no timezone information, and (b) is in UTC. Example: .. code-block:: python import pendulum ...
[ "def", "pendulum_to_utc_datetime_without_tz", "(", "x", ":", "DateTime", ")", "->", "datetime", ".", "datetime", ":", "# noqa", "pendulum_in_utc", "=", "pendulum", ".", "UTC", ".", "convert", "(", "x", ")", "return", "pendulum_to_datetime_stripping_tz", "(", "pend...
Converts a Pendulum ``DateTime`` (which will have timezone information) to a ``datetime.datetime`` that (a) has no timezone information, and (b) is in UTC. Example: .. code-block:: python import pendulum from cardinal_pythonlib.datetimefunc import * in_moscow = pendulum.parse(...
[ "Converts", "a", "Pendulum", "DateTime", "(", "which", "will", "have", "timezone", "information", ")", "to", "a", "datetime", ".", "datetime", "that", "(", "a", ")", "has", "no", "timezone", "information", "and", "(", "b", ")", "is", "in", "UTC", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L143-L162
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
pendulum_date_to_datetime_date
def pendulum_date_to_datetime_date(x: Date) -> datetime.date: """ Takes a :class:`pendulum.Date` and returns a :class:`datetime.date`. Used, for example, where a database backend insists on :class:`datetime.date`. """ return datetime.date(year=x.year, month=x.month, day=x.day)
python
def pendulum_date_to_datetime_date(x: Date) -> datetime.date: """ Takes a :class:`pendulum.Date` and returns a :class:`datetime.date`. Used, for example, where a database backend insists on :class:`datetime.date`. """ return datetime.date(year=x.year, month=x.month, day=x.day)
[ "def", "pendulum_date_to_datetime_date", "(", "x", ":", "Date", ")", "->", "datetime", ".", "date", ":", "return", "datetime", ".", "date", "(", "year", "=", "x", ".", "year", ",", "month", "=", "x", ".", "month", ",", "day", "=", "x", ".", "day", ...
Takes a :class:`pendulum.Date` and returns a :class:`datetime.date`. Used, for example, where a database backend insists on :class:`datetime.date`.
[ "Takes", "a", ":", "class", ":", "pendulum", ".", "Date", "and", "returns", "a", ":", "class", ":", "datetime", ".", "date", ".", "Used", "for", "example", "where", "a", "database", "backend", "insists", "on", ":", "class", ":", "datetime", ".", "date"...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L165-L171
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
pendulum_time_to_datetime_time
def pendulum_time_to_datetime_time(x: Time) -> datetime.time: """ Takes a :class:`pendulum.Time` and returns a :class:`datetime.time`. Used, for example, where a database backend insists on :class:`datetime.time`. """ return datetime.time( hour=x.hour, minute=x.minute, second=x.second, ...
python
def pendulum_time_to_datetime_time(x: Time) -> datetime.time: """ Takes a :class:`pendulum.Time` and returns a :class:`datetime.time`. Used, for example, where a database backend insists on :class:`datetime.time`. """ return datetime.time( hour=x.hour, minute=x.minute, second=x.second, ...
[ "def", "pendulum_time_to_datetime_time", "(", "x", ":", "Time", ")", "->", "datetime", ".", "time", ":", "return", "datetime", ".", "time", "(", "hour", "=", "x", ".", "hour", ",", "minute", "=", "x", ".", "minute", ",", "second", "=", "x", ".", "sec...
Takes a :class:`pendulum.Time` and returns a :class:`datetime.time`. Used, for example, where a database backend insists on :class:`datetime.time`.
[ "Takes", "a", ":", "class", ":", "pendulum", ".", "Time", "and", "returns", "a", ":", "class", ":", "datetime", ".", "time", ".", "Used", "for", "example", "where", "a", "database", "backend", "insists", "on", ":", "class", ":", "datetime", ".", "time"...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L174-L184
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
format_datetime
def format_datetime(d: PotentialDatetimeType, fmt: str, default: str = None) -> Optional[str]: """ Format a datetime with a ``strftime`` format specification string, or return ``default`` if the input is ``None``. """ d = coerce_to_pendulum(d) if d is None...
python
def format_datetime(d: PotentialDatetimeType, fmt: str, default: str = None) -> Optional[str]: """ Format a datetime with a ``strftime`` format specification string, or return ``default`` if the input is ``None``. """ d = coerce_to_pendulum(d) if d is None...
[ "def", "format_datetime", "(", "d", ":", "PotentialDatetimeType", ",", "fmt", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "d", "=", "coerce_to_pendulum", "(", "d", ")", "if", "d", "is", "None", ":...
Format a datetime with a ``strftime`` format specification string, or return ``default`` if the input is ``None``.
[ "Format", "a", "datetime", "with", "a", "strftime", "format", "specification", "string", "or", "return", "default", "if", "the", "input", "is", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L191-L201
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
strfdelta
def strfdelta(tdelta: Union[datetime.timedelta, int, float, str], fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'): """ Convert a ``datetime.timedelta`` object or a regular number to a custom- formatted string, just like the ``strftime()`` method does for ``datet...
python
def strfdelta(tdelta: Union[datetime.timedelta, int, float, str], fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'): """ Convert a ``datetime.timedelta`` object or a regular number to a custom- formatted string, just like the ``strftime()`` method does for ``datet...
[ "def", "strfdelta", "(", "tdelta", ":", "Union", "[", "datetime", ".", "timedelta", ",", "int", ",", "float", ",", "str", "]", ",", "fmt", "=", "'{D:02}d {H:02}h {M:02}m {S:02}s'", ",", "inputtype", "=", "'timedelta'", ")", ":", "# noqa", "# Convert tdelta to ...
Convert a ``datetime.timedelta`` object or a regular number to a custom- formatted string, just like the ``strftime()`` method does for ``datetime.datetime`` objects. The ``fmt`` argument allows custom formatting to be specified. Fields can include ``seconds``, ``minutes``, ``hours``, ``days``, and ``w...
[ "Convert", "a", "datetime", ".", "timedelta", "object", "or", "a", "regular", "number", "to", "a", "custom", "-", "formatted", "string", "just", "like", "the", "strftime", "()", "method", "does", "for", "datetime", ".", "datetime", "objects", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L204-L266
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
convert_datetime_to_utc
def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to UTC (with UTC timezone). """ dt = coerce_to_pendulum(dt) tz = get_tz_utc() return dt.in_tz(tz)
python
def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to UTC (with UTC timezone). """ dt = coerce_to_pendulum(dt) tz = get_tz_utc() return dt.in_tz(tz)
[ "def", "convert_datetime_to_utc", "(", "dt", ":", "PotentialDatetimeType", ")", "->", "DateTime", ":", "dt", "=", "coerce_to_pendulum", "(", "dt", ")", "tz", "=", "get_tz_utc", "(", ")", "return", "dt", ".", "in_tz", "(", "tz", ")" ]
Convert date/time with timezone to UTC (with UTC timezone).
[ "Convert", "date", "/", "time", "with", "timezone", "to", "UTC", "(", "with", "UTC", "timezone", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L320-L326
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
convert_datetime_to_local
def convert_datetime_to_local(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to local timezone. """ dt = coerce_to_pendulum(dt) tz = get_tz_local() return dt.in_tz(tz)
python
def convert_datetime_to_local(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to local timezone. """ dt = coerce_to_pendulum(dt) tz = get_tz_local() return dt.in_tz(tz)
[ "def", "convert_datetime_to_local", "(", "dt", ":", "PotentialDatetimeType", ")", "->", "DateTime", ":", "dt", "=", "coerce_to_pendulum", "(", "dt", ")", "tz", "=", "get_tz_local", "(", ")", "return", "dt", ".", "in_tz", "(", "tz", ")" ]
Convert date/time with timezone to local timezone.
[ "Convert", "date", "/", "time", "with", "timezone", "to", "local", "timezone", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L329-L335
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
get_duration_h_m
def get_duration_h_m(start: Union[str, DateTime], end: Union[str, DateTime], default: str = "N/A") -> str: """ Calculate the time between two dates/times expressed as strings. Args: start: start date/time end: end date/time default: string v...
python
def get_duration_h_m(start: Union[str, DateTime], end: Union[str, DateTime], default: str = "N/A") -> str: """ Calculate the time between two dates/times expressed as strings. Args: start: start date/time end: end date/time default: string v...
[ "def", "get_duration_h_m", "(", "start", ":", "Union", "[", "str", ",", "DateTime", "]", ",", "end", ":", "Union", "[", "str", ",", "DateTime", "]", ",", "default", ":", "str", "=", "\"N/A\"", ")", "->", "str", ":", "start", "=", "coerce_to_pendulum", ...
Calculate the time between two dates/times expressed as strings. Args: start: start date/time end: end date/time default: string value to return in case either of the inputs is ``None`` Returns: a string that is one of .. code-block: 'hh:mm' ...
[ "Calculate", "the", "time", "between", "two", "dates", "/", "times", "expressed", "as", "strings", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L342-L379
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
get_age
def get_age(dob: PotentialDatetimeType, when: PotentialDatetimeType, default: str = "") -> Union[int, str]: """ Age (in whole years) at a particular date, or ``default``. Args: dob: date of birth when: date/time at which to calculate age default: value to ret...
python
def get_age(dob: PotentialDatetimeType, when: PotentialDatetimeType, default: str = "") -> Union[int, str]: """ Age (in whole years) at a particular date, or ``default``. Args: dob: date of birth when: date/time at which to calculate age default: value to ret...
[ "def", "get_age", "(", "dob", ":", "PotentialDatetimeType", ",", "when", ":", "PotentialDatetimeType", ",", "default", ":", "str", "=", "\"\"", ")", "->", "Union", "[", "int", ",", "str", "]", ":", "dob", "=", "coerce_to_pendulum_date", "(", "dob", ")", ...
Age (in whole years) at a particular date, or ``default``. Args: dob: date of birth when: date/time at which to calculate age default: value to return if either input is ``None`` Returns: age in whole years (rounded down), or ``default``
[ "Age", "(", "in", "whole", "years", ")", "at", "a", "particular", "date", "or", "default", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L382-L401
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
truncate_date_to_first_of_month
def truncate_date_to_first_of_month( dt: Optional[DateLikeType]) -> Optional[DateLikeType]: """ Change the day to the first of the month. """ if dt is None: return None return dt.replace(day=1)
python
def truncate_date_to_first_of_month( dt: Optional[DateLikeType]) -> Optional[DateLikeType]: """ Change the day to the first of the month. """ if dt is None: return None return dt.replace(day=1)
[ "def", "truncate_date_to_first_of_month", "(", "dt", ":", "Optional", "[", "DateLikeType", "]", ")", "->", "Optional", "[", "DateLikeType", "]", ":", "if", "dt", "is", "None", ":", "return", "None", "return", "dt", ".", "replace", "(", "day", "=", "1", "...
Change the day to the first of the month.
[ "Change", "the", "day", "to", "the", "first", "of", "the", "month", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L408-L415
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
get_now_utc_notz_datetime
def get_now_utc_notz_datetime() -> datetime.datetime: """ Get the UTC time now, but with no timezone information, in :class:`datetime.datetime` format. """ now = datetime.datetime.utcnow() return now.replace(tzinfo=None)
python
def get_now_utc_notz_datetime() -> datetime.datetime: """ Get the UTC time now, but with no timezone information, in :class:`datetime.datetime` format. """ now = datetime.datetime.utcnow() return now.replace(tzinfo=None)
[ "def", "get_now_utc_notz_datetime", "(", ")", "->", "datetime", ".", "datetime", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "return", "now", ".", "replace", "(", "tzinfo", "=", "None", ")" ]
Get the UTC time now, but with no timezone information, in :class:`datetime.datetime` format.
[ "Get", "the", "UTC", "time", "now", "but", "with", "no", "timezone", "information", "in", ":", "class", ":", "datetime", ".", "datetime", "format", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L422-L428
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
coerce_to_datetime
def coerce_to_datetime(x: Any) -> Optional[datetime.datetime]: """ Ensure an object is a :class:`datetime.datetime`, or coerce to one, or raise :exc:`ValueError` or :exc:`OverflowError` (as per http://dateutil.readthedocs.org/en/latest/parser.html). """ if x is None: return None elif...
python
def coerce_to_datetime(x: Any) -> Optional[datetime.datetime]: """ Ensure an object is a :class:`datetime.datetime`, or coerce to one, or raise :exc:`ValueError` or :exc:`OverflowError` (as per http://dateutil.readthedocs.org/en/latest/parser.html). """ if x is None: return None elif...
[ "def", "coerce_to_datetime", "(", "x", ":", "Any", ")", "->", "Optional", "[", "datetime", ".", "datetime", "]", ":", "if", "x", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "x", ",", "DateTime", ")", ":", "return", "pendulum_to_dateti...
Ensure an object is a :class:`datetime.datetime`, or coerce to one, or raise :exc:`ValueError` or :exc:`OverflowError` (as per http://dateutil.readthedocs.org/en/latest/parser.html).
[ "Ensure", "an", "object", "is", "a", ":", "class", ":", "datetime", ".", "datetime", "or", "coerce", "to", "one", "or", "raise", ":", "exc", ":", "ValueError", "or", ":", "exc", ":", "OverflowError", "(", "as", "per", "http", ":", "//", "dateutil", "...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L431-L446
ivanprjcts/sdklib
sdklib/http/base.py
request_from_context
def request_from_context(context): """ Do http requests from context. :param context: request context. """ new_context = copy.deepcopy(context) assert new_context.method in ALLOWED_METHODS new_context.url_path = generate_url_path( new_context.url_path, prefix=new_context.pr...
python
def request_from_context(context): """ Do http requests from context. :param context: request context. """ new_context = copy.deepcopy(context) assert new_context.method in ALLOWED_METHODS new_context.url_path = generate_url_path( new_context.url_path, prefix=new_context.pr...
[ "def", "request_from_context", "(", "context", ")", ":", "new_context", "=", "copy", ".", "deepcopy", "(", "context", ")", "assert", "new_context", ".", "method", "in", "ALLOWED_METHODS", "new_context", ".", "url_path", "=", "generate_url_path", "(", "new_context"...
Do http requests from context. :param context: request context.
[ "Do", "http", "requests", "from", "context", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L33-L79
ivanprjcts/sdklib
sdklib/http/base.py
HttpRequestContext.clear
def clear(self, *args): """ Set default values to **self.fields_to_clear**. In addition, it is possible to pass extra fields to clear. :param args: extra fields to clear. """ for field in self.fields_to_clear + list(args): setattr(self, field, None)
python
def clear(self, *args): """ Set default values to **self.fields_to_clear**. In addition, it is possible to pass extra fields to clear. :param args: extra fields to clear. """ for field in self.fields_to_clear + list(args): setattr(self, field, None)
[ "def", "clear", "(", "self", ",", "*", "args", ")", ":", "for", "field", "in", "self", ".", "fields_to_clear", "+", "list", "(", "args", ")", ":", "setattr", "(", "self", ",", "field", ",", "None", ")" ]
Set default values to **self.fields_to_clear**. In addition, it is possible to pass extra fields to clear. :param args: extra fields to clear.
[ "Set", "default", "values", "to", "**", "self", ".", "fields_to_clear", "**", ".", "In", "addition", "it", "is", "possible", "to", "pass", "extra", "fields", "to", "clear", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L232-L239
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk.host
def host(self, value): """ A string that will be automatically included at the beginning of the url generated for doing each http request. :param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port) """ scheme, host, port = get_hostname_paramete...
python
def host(self, value): """ A string that will be automatically included at the beginning of the url generated for doing each http request. :param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port) """ scheme, host, port = get_hostname_paramete...
[ "def", "host", "(", "self", ",", "value", ")", ":", "scheme", ",", "host", ",", "port", "=", "get_hostname_parameters_from_url", "(", "value", ")", "self", ".", "_host", "=", "\"%s://%s:%s\"", "%", "(", "scheme", ",", "host", ",", "port", ")" ]
A string that will be automatically included at the beginning of the url generated for doing each http request. :param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port)
[ "A", "string", "that", "will", "be", "automatically", "included", "at", "the", "beginning", "of", "the", "url", "generated", "for", "doing", "each", "http", "request", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L281-L288
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk.cookie
def cookie(self, value): """ Set cookie. :param value: """ if value and not value.is_empty(): self._cookie = value else: self._cookie = Cookie()
python
def cookie(self, value): """ Set cookie. :param value: """ if value and not value.is_empty(): self._cookie = value else: self._cookie = Cookie()
[ "def", "cookie", "(", "self", ",", "value", ")", ":", "if", "value", "and", "not", "value", ".", "is_empty", "(", ")", ":", "self", ".", "_cookie", "=", "value", "else", ":", "self", ".", "_cookie", "=", "Cookie", "(", ")" ]
Set cookie. :param value:
[ "Set", "cookie", ".", ":", "param", "value", ":" ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L316-L324
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk.set_default_host
def set_default_host(cls, value): """ Default: "http://127.0.0.1:80" A string that will be automatically included at the beginning of the url generated for doing each http request. """ if value is None: cls.DEFAULT_HOST = "http://127.0.0.1:80" else: ...
python
def set_default_host(cls, value): """ Default: "http://127.0.0.1:80" A string that will be automatically included at the beginning of the url generated for doing each http request. """ if value is None: cls.DEFAULT_HOST = "http://127.0.0.1:80" else: ...
[ "def", "set_default_host", "(", "cls", ",", "value", ")", ":", "if", "value", "is", "None", ":", "cls", ".", "DEFAULT_HOST", "=", "\"http://127.0.0.1:80\"", "else", ":", "scheme", ",", "host", ",", "port", "=", "get_hostname_parameters_from_url", "(", "value",...
Default: "http://127.0.0.1:80" A string that will be automatically included at the beginning of the url generated for doing each http request.
[ "Default", ":", "http", ":", "//", "127", ".", "0", ".", "0", ".", "1", ":", "80" ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L353-L363
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk.set_default_proxy
def set_default_proxy(cls, value): """ Default: None (no proxy) A string that will be used to tell each request must be sent through this proxy server. Use the scheme://hostname:port form. If you need to use a proxy, you can configure individual requests with the proxies argumen...
python
def set_default_proxy(cls, value): """ Default: None (no proxy) A string that will be used to tell each request must be sent through this proxy server. Use the scheme://hostname:port form. If you need to use a proxy, you can configure individual requests with the proxies argumen...
[ "def", "set_default_proxy", "(", "cls", ",", "value", ")", ":", "if", "value", "is", "None", ":", "cls", ".", "DEFAULT_PROXY", "=", "None", "else", ":", "scheme", ",", "host", ",", "port", "=", "get_hostname_parameters_from_url", "(", "value", ")", "cls", ...
Default: None (no proxy) A string that will be used to tell each request must be sent through this proxy server. Use the scheme://hostname:port form. If you need to use a proxy, you can configure individual requests with the proxies argument to any request method.
[ "Default", ":", "None", "(", "no", "proxy", ")" ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L366-L379
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk._http_request
def _http_request(self, method, url_path, headers=None, query_params=None, body_params=None, files=None, **kwargs): """ Method to do http requests. :param method: :param url_path: :param headers: :param body_params: :param query_params: :param files: (opt...
python
def _http_request(self, method, url_path, headers=None, query_params=None, body_params=None, files=None, **kwargs): """ Method to do http requests. :param method: :param url_path: :param headers: :param body_params: :param query_params: :param files: (opt...
[ "def", "_http_request", "(", "self", ",", "method", ",", "url_path", ",", "headers", "=", "None", ",", "query_params", "=", "None", ",", "body_params", "=", "None", ",", "files", "=", "None", ",", "*", "*", "kwargs", ")", ":", "host", "=", "kwargs", ...
Method to do http requests. :param method: :param url_path: :param headers: :param body_params: :param query_params: :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ...
[ "Method", "to", "do", "http", "requests", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L394-L443
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk.login
def login(self, **kwargs): """ Login abstract method with default implementation. :param kwargs: parameters :return: SdkResponse """ assert self.LOGIN_URL_PATH is not None render_name = kwargs.pop("render", "json") render = get_renderer(render_name) ...
python
def login(self, **kwargs): """ Login abstract method with default implementation. :param kwargs: parameters :return: SdkResponse """ assert self.LOGIN_URL_PATH is not None render_name = kwargs.pop("render", "json") render = get_renderer(render_name) ...
[ "def", "login", "(", "self", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "LOGIN_URL_PATH", "is", "not", "None", "render_name", "=", "kwargs", ".", "pop", "(", "\"render\"", ",", "\"json\"", ")", "render", "=", "get_renderer", "(", "render_n...
Login abstract method with default implementation. :param kwargs: parameters :return: SdkResponse
[ "Login", "abstract", "method", "with", "default", "implementation", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L463-L475
RudolfCardinal/pythonlib
cardinal_pythonlib/nhs.py
nhs_check_digit
def nhs_check_digit(ninedigits: Union[str, List[Union[str, int]]]) -> int: """ Calculates an NHS number check digit. Args: ninedigits: string or list Returns: check digit Method: 1. Multiply each of the first nine digits by the corresponding digit weighting (see :const...
python
def nhs_check_digit(ninedigits: Union[str, List[Union[str, int]]]) -> int: """ Calculates an NHS number check digit. Args: ninedigits: string or list Returns: check digit Method: 1. Multiply each of the first nine digits by the corresponding digit weighting (see :const...
[ "def", "nhs_check_digit", "(", "ninedigits", ":", "Union", "[", "str", ",", "List", "[", "Union", "[", "str", ",", "int", "]", "]", "]", ")", "->", "int", ":", "if", "len", "(", "ninedigits", ")", "!=", "9", "or", "not", "all", "(", "str", "(", ...
Calculates an NHS number check digit. Args: ninedigits: string or list Returns: check digit Method: 1. Multiply each of the first nine digits by the corresponding digit weighting (see :const:`NHS_DIGIT_WEIGHTINGS`). 2. Sum the results. 3. Take remainder after division ...
[ "Calculates", "an", "NHS", "number", "check", "digit", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/nhs.py#L45-L77
RudolfCardinal/pythonlib
cardinal_pythonlib/nhs.py
is_valid_nhs_number
def is_valid_nhs_number(n: int) -> bool: """ Validates an integer as an NHS number. Args: n: NHS number Returns: valid? Checksum details are at http://www.datadictionary.nhs.uk/version2/data_dictionary/data_field_notes/n/nhs_number_de.asp """ # noqa if not isinsta...
python
def is_valid_nhs_number(n: int) -> bool: """ Validates an integer as an NHS number. Args: n: NHS number Returns: valid? Checksum details are at http://www.datadictionary.nhs.uk/version2/data_dictionary/data_field_notes/n/nhs_number_de.asp """ # noqa if not isinsta...
[ "def", "is_valid_nhs_number", "(", "n", ":", "int", ")", "->", "bool", ":", "# noqa", "if", "not", "isinstance", "(", "n", ",", "int", ")", ":", "log", ".", "debug", "(", "\"is_valid_nhs_number: parameter was not of integer type\"", ")", "return", "False", "s"...
Validates an integer as an NHS number. Args: n: NHS number Returns: valid? Checksum details are at http://www.datadictionary.nhs.uk/version2/data_dictionary/data_field_notes/n/nhs_number_de.asp
[ "Validates", "an", "integer", "as", "an", "NHS", "number", ".", "Args", ":", "n", ":", "NHS", "number" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/nhs.py#L80-L113
RudolfCardinal/pythonlib
cardinal_pythonlib/nhs.py
generate_random_nhs_number
def generate_random_nhs_number() -> int: """ Returns a random valid NHS number, as an ``int``. """ check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10: digits = [random.randint(1, 9)] # don't start with a zero digits.extend([random.randint(0...
python
def generate_random_nhs_number() -> int: """ Returns a random valid NHS number, as an ``int``. """ check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10: digits = [random.randint(1, 9)] # don't start with a zero digits.extend([random.randint(0...
[ "def", "generate_random_nhs_number", "(", ")", "->", "int", ":", "check_digit", "=", "10", "# NHS numbers with this check digit are all invalid", "while", "check_digit", "==", "10", ":", "digits", "=", "[", "random", ".", "randint", "(", "1", ",", "9", ")", "]",...
Returns a random valid NHS number, as an ``int``.
[ "Returns", "a", "random", "valid", "NHS", "number", "as", "an", "int", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/nhs.py#L116-L128
RudolfCardinal/pythonlib
cardinal_pythonlib/nhs.py
generate_nhs_number_from_first_9_digits
def generate_nhs_number_from_first_9_digits(first9digits: str) -> Optional[int]: """ Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might accidentally be real). For examp...
python
def generate_nhs_number_from_first_9_digits(first9digits: str) -> Optional[int]: """ Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might accidentally be real). For examp...
[ "def", "generate_nhs_number_from_first_9_digits", "(", "first9digits", ":", "str", ")", "->", "Optional", "[", "int", "]", ":", "if", "len", "(", "first9digits", ")", "!=", "9", ":", "log", ".", "warning", "(", "\"Not 9 digits\"", ")", "return", "None", "try...
Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might accidentally be real). For example: .. code-block:: none 123456789_ : no; checksum 10 987654321_ : yes,...
[ "Returns", "a", "valid", "NHS", "number", "as", "an", "int", "given", "the", "first", "9", "digits", ".", "The", "particular", "purpose", "is", "to", "make", "NHS", "numbers", "that", "*", "look", "*", "fake", "(", "rather", "than", "truly", "random", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/nhs.py#L138-L168
RudolfCardinal/pythonlib
cardinal_pythonlib/nhs.py
nhs_number_from_text_or_none
def nhs_number_from_text_or_none(s: str) -> Optional[int]: """ Returns a validated NHS number (as an integer) from a string, or ``None`` if it is not valid. It's a 10-digit number, so note that database 32-bit INT values are insufficient; use BIGINT. Python will handle large integers happily. ...
python
def nhs_number_from_text_or_none(s: str) -> Optional[int]: """ Returns a validated NHS number (as an integer) from a string, or ``None`` if it is not valid. It's a 10-digit number, so note that database 32-bit INT values are insufficient; use BIGINT. Python will handle large integers happily. ...
[ "def", "nhs_number_from_text_or_none", "(", "s", ":", "str", ")", "->", "Optional", "[", "int", "]", ":", "# noqa", "# None in, None out.", "funcname", "=", "\"nhs_number_from_text_or_none: \"", "if", "not", "s", ":", "log", ".", "debug", "(", "funcname", "+", ...
Returns a validated NHS number (as an integer) from a string, or ``None`` if it is not valid. It's a 10-digit number, so note that database 32-bit INT values are insufficient; use BIGINT. Python will handle large integers happily. NHS number rules: http://www.datadictionary.nhs.uk/...
[ "Returns", "a", "validated", "NHS", "number", "(", "as", "an", "integer", ")", "from", "a", "string", "or", "None", "if", "it", "is", "not", "valid", ".", "It", "s", "a", "10", "-", "digit", "number", "so", "note", "that", "database", "32", "-", "b...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/nhs.py#L179-L216
RudolfCardinal/pythonlib
cardinal_pythonlib/email/sendmail.py
make_email
def make_email(from_addr: str, date: str = None, sender: str = "", reply_to: Union[str, List[str]] = "", to: Union[str, List[str]] = "", cc: Union[str, List[str]] = "", bcc: Union[str, List[str]] = "", subject: str ...
python
def make_email(from_addr: str, date: str = None, sender: str = "", reply_to: Union[str, List[str]] = "", to: Union[str, List[str]] = "", cc: Union[str, List[str]] = "", bcc: Union[str, List[str]] = "", subject: str ...
[ "def", "make_email", "(", "from_addr", ":", "str", ",", "date", ":", "str", "=", "None", ",", "sender", ":", "str", "=", "\"\"", ",", "reply_to", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "=", "\"\"", ",", "to", ":", "Union", ...
Makes an e-mail message. Arguments that can be multiple e-mail addresses are (a) a single e-mail address as a string, or (b) a list of strings (each a single e-mail address), or (c) a comma-separated list of multiple e-mail addresses. Args: from_addr: name of the sender for the "From:" field ...
[ "Makes", "an", "e", "-", "mail", "message", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/sendmail.py#L66-L240