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
materialsvirtuallab/monty
monty/io.py
zopen
def zopen(filename, *args, **kwargs): """ This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). ...
python
def zopen(filename, *args, **kwargs): """ This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). ...
[ "def", "zopen", "(", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "Path", "is", "not", "None", "and", "isinstance", "(", "filename", ",", "Path", ")", ":", "filename", "=", "str", "(", "filename", ")", "name", ",", "ext", ...
This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). E.g., 'r' for read, 'w' for write. ...
[ "This", "function", "wraps", "around", "the", "bz2", "gzip", "and", "standard", "python", "s", "open", "function", "to", "deal", "intelligently", "with", "bzipped", "gzipped", "or", "standard", "text", "files", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L38-L72
materialsvirtuallab/monty
monty/io.py
reverse_readfile
def reverse_readfile(filename): """ A much faster reverse read of file by using Python's mmap to generate a memory-mapped file. It is slower for very small files than reverse_readline, but at least 2x faster for large files (the primary use of such a method). Args: filename (str): ...
python
def reverse_readfile(filename): """ A much faster reverse read of file by using Python's mmap to generate a memory-mapped file. It is slower for very small files than reverse_readline, but at least 2x faster for large files (the primary use of such a method). Args: filename (str): ...
[ "def", "reverse_readfile", "(", "filename", ")", ":", "try", ":", "with", "zopen", "(", "filename", ",", "\"rb\"", ")", "as", "f", ":", "if", "isinstance", "(", "f", ",", "gzip", ".", "GzipFile", ")", "or", "isinstance", "(", "f", ",", "bz2", ".", ...
A much faster reverse read of file by using Python's mmap to generate a memory-mapped file. It is slower for very small files than reverse_readline, but at least 2x faster for large files (the primary use of such a method). Args: filename (str): Name of file to read. Yields: ...
[ "A", "much", "faster", "reverse", "read", "of", "file", "by", "using", "Python", "s", "mmap", "to", "generate", "a", "memory", "-", "mapped", "file", ".", "It", "is", "slower", "for", "very", "small", "files", "than", "reverse_readline", "but", "at", "le...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L75-L102
materialsvirtuallab/monty
monty/io.py
reverse_readline
def reverse_readline(m_file, blk_size=4096, max_mem=4000000): """ Generator method to read a file line-by-line, but backwards. This allows one to efficiently get data at the end of a file. Based on code by Peter Astrand <astrand@cendio.se>, using modifications by Raymond Hettinger and Kevin German....
python
def reverse_readline(m_file, blk_size=4096, max_mem=4000000): """ Generator method to read a file line-by-line, but backwards. This allows one to efficiently get data at the end of a file. Based on code by Peter Astrand <astrand@cendio.se>, using modifications by Raymond Hettinger and Kevin German....
[ "def", "reverse_readline", "(", "m_file", ",", "blk_size", "=", "4096", ",", "max_mem", "=", "4000000", ")", ":", "# Check if the file stream is a bit stream or not", "is_text", "=", "isinstance", "(", "m_file", ",", "io", ".", "TextIOWrapper", ")", "try", ":", ...
Generator method to read a file line-by-line, but backwards. This allows one to efficiently get data at the end of a file. Based on code by Peter Astrand <astrand@cendio.se>, using modifications by Raymond Hettinger and Kevin German. http://code.activestate.com/recipes/439045-read-a-text-file-backwards...
[ "Generator", "method", "to", "read", "a", "file", "line", "-", "by", "-", "line", "but", "backwards", ".", "This", "allows", "one", "to", "efficiently", "get", "data", "at", "the", "end", "of", "a", "file", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L105-L187
materialsvirtuallab/monty
monty/io.py
get_open_fds
def get_open_fds(): """ Return the number of open file descriptors for current process .. warning: will only work on UNIX-like OS-es. """ pid = os.getpid() procs = subprocess.check_output(["lsof", '-w', '-Ff', "-p", str(pid)]) procs = procs.decode("utf-8") return len([s for s in procs....
python
def get_open_fds(): """ Return the number of open file descriptors for current process .. warning: will only work on UNIX-like OS-es. """ pid = os.getpid() procs = subprocess.check_output(["lsof", '-w', '-Ff', "-p", str(pid)]) procs = procs.decode("utf-8") return len([s for s in procs....
[ "def", "get_open_fds", "(", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "procs", "=", "subprocess", ".", "check_output", "(", "[", "\"lsof\"", ",", "'-w'", ",", "'-Ff'", ",", "\"-p\"", ",", "str", "(", "pid", ")", "]", ")", "procs", "=", ...
Return the number of open file descriptors for current process .. warning: will only work on UNIX-like OS-es.
[ "Return", "the", "number", "of", "open", "file", "descriptors", "for", "current", "process" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L287-L298
materialsvirtuallab/monty
monty/io.py
FileLock.acquire
def acquire(self): """ Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception. """ start_time = time.time()...
python
def acquire(self): """ Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception. """ start_time = time.time()...
[ "def", "acquire", "(", "self", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "try", ":", "self", ".", "fd", "=", "os", ".", "open", "(", "self", ".", "lockfile", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_...
Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception.
[ "Acquire", "the", "lock", "if", "possible", ".", "If", "the", "lock", "is", "in", "use", "it", "check", "again", "every", "delay", "seconds", ".", "It", "does", "this", "until", "it", "either", "gets", "the", "lock", "or", "exceeds", "timeout", "number",...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L229-L250
materialsvirtuallab/monty
monty/io.py
FileLock.release
def release(self): """ Get rid of the lock by deleting the lockfile. When working in a `with` statement, this gets automatically called at the end. """ if self.is_locked: os.close(self.fd) os.unlink(self.lockfile) self.is_locked = False
python
def release(self): """ Get rid of the lock by deleting the lockfile. When working in a `with` statement, this gets automatically called at the end. """ if self.is_locked: os.close(self.fd) os.unlink(self.lockfile) self.is_locked = False
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "is_locked", ":", "os", ".", "close", "(", "self", ".", "fd", ")", "os", ".", "unlink", "(", "self", ".", "lockfile", ")", "self", ".", "is_locked", "=", "False" ]
Get rid of the lock by deleting the lockfile. When working in a `with` statement, this gets automatically called at the end.
[ "Get", "rid", "of", "the", "lock", "by", "deleting", "the", "lockfile", ".", "When", "working", "in", "a", "with", "statement", "this", "gets", "automatically", "called", "at", "the", "end", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L252-L260
materialsvirtuallab/monty
monty/fnmatch.py
WildCard.filter
def filter(self, names): """ Returns a list with the names matching the pattern. """ names = list_strings(names) fnames = [] for f in names: for pat in self.pats: if fnmatch.fnmatch(f, pat): fnames.append(f) return...
python
def filter(self, names): """ Returns a list with the names matching the pattern. """ names = list_strings(names) fnames = [] for f in names: for pat in self.pats: if fnmatch.fnmatch(f, pat): fnames.append(f) return...
[ "def", "filter", "(", "self", ",", "names", ")", ":", "names", "=", "list_strings", "(", "names", ")", "fnames", "=", "[", "]", "for", "f", "in", "names", ":", "for", "pat", "in", "self", ".", "pats", ":", "if", "fnmatch", ".", "fnmatch", "(", "f...
Returns a list with the names matching the pattern.
[ "Returns", "a", "list", "with", "the", "names", "matching", "the", "pattern", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fnmatch.py#L41-L53
materialsvirtuallab/monty
monty/fnmatch.py
WildCard.match
def match(self, name): """ Returns True if name matches one of the patterns. """ for pat in self.pats: if fnmatch.fnmatch(name, pat): return True return False
python
def match(self, name): """ Returns True if name matches one of the patterns. """ for pat in self.pats: if fnmatch.fnmatch(name, pat): return True return False
[ "def", "match", "(", "self", ",", "name", ")", ":", "for", "pat", "in", "self", ".", "pats", ":", "if", "fnmatch", ".", "fnmatch", "(", "name", ",", "pat", ")", ":", "return", "True", "return", "False" ]
Returns True if name matches one of the patterns.
[ "Returns", "True", "if", "name", "matches", "one", "of", "the", "patterns", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fnmatch.py#L55-L63
materialsvirtuallab/monty
monty/dev.py
deprecated
def deprecated(replacement=None, message=None): """ Decorator to mark classes or functions as deprecated, with a possible replacement. Args: replacement (callable): A replacement class or method. message (str): A warning message to be displayed. Returns: Original function, ...
python
def deprecated(replacement=None, message=None): """ Decorator to mark classes or functions as deprecated, with a possible replacement. Args: replacement (callable): A replacement class or method. message (str): A warning message to be displayed. Returns: Original function, ...
[ "def", "deprecated", "(", "replacement", "=", "None", ",", "message", "=", "None", ")", ":", "def", "wrap", "(", "old", ")", ":", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "\"%s is deprecated\"", "%", "old", ...
Decorator to mark classes or functions as deprecated, with a possible replacement. Args: replacement (callable): A replacement class or method. message (str): A warning message to be displayed. Returns: Original function, but with a warning to use the updated class.
[ "Decorator", "to", "mark", "classes", "or", "functions", "as", "deprecated", "with", "a", "possible", "replacement", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/dev.py#L26-L58
materialsvirtuallab/monty
monty/dev.py
get_ncpus
def get_ncpus(): """ .. note:: If you are using Python >= 2.7, multiprocessing.cpu_count() already provides the number of CPUs. In fact, this is the first method tried. The purpose of this function is to cater to old Python versions that still exist on many Linux style clusters....
python
def get_ncpus(): """ .. note:: If you are using Python >= 2.7, multiprocessing.cpu_count() already provides the number of CPUs. In fact, this is the first method tried. The purpose of this function is to cater to old Python versions that still exist on many Linux style clusters....
[ "def", "get_ncpus", "(", ")", ":", "# Python 2.6+", "# May raise NonImplementedError", "try", ":", "return", "multiprocessing", ".", "cpu_count", "(", ")", "except", "(", "ImportError", ",", "NotImplementedError", ")", ":", "pass", "# POSIX", "try", ":", "res", ...
.. note:: If you are using Python >= 2.7, multiprocessing.cpu_count() already provides the number of CPUs. In fact, this is the first method tried. The purpose of this function is to cater to old Python versions that still exist on many Linux style clusters. Number of virtual or ph...
[ "..", "note", "::" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/dev.py#L97-L195
materialsvirtuallab/monty
monty/dev.py
install_excepthook
def install_excepthook(hook_type="color", **kwargs): """ This function replaces the original python traceback with an improved version from Ipython. Use `color` for colourful traceback formatting, `verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword arguments passed to the construct...
python
def install_excepthook(hook_type="color", **kwargs): """ This function replaces the original python traceback with an improved version from Ipython. Use `color` for colourful traceback formatting, `verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword arguments passed to the construct...
[ "def", "install_excepthook", "(", "hook_type", "=", "\"color\"", ",", "*", "*", "kwargs", ")", ":", "try", ":", "from", "IPython", ".", "core", "import", "ultratb", "except", "ImportError", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"Cannot i...
This function replaces the original python traceback with an improved version from Ipython. Use `color` for colourful traceback formatting, `verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword arguments passed to the constructor. See IPython.core.ultratb.py for more info. Return: ...
[ "This", "function", "replaces", "the", "original", "python", "traceback", "with", "an", "improved", "version", "from", "Ipython", ".", "Use", "color", "for", "colourful", "traceback", "formatting", "verbose", "for", "Ka", "-", "Ping", "Yee", "s", "cgitb", ".",...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/dev.py#L198-L228
materialsvirtuallab/monty
monty/re.py
regrep
def regrep(filename, patterns, reverse=False, terminate_on_match=False, postprocess=str): """ A powerful regular expression version of grep. Args: filename (str): Filename to grep. patterns (dict): A dict of patterns, e.g., {"energy": "energy\(sigma->0\)\s+=\s+([\d\-\...
python
def regrep(filename, patterns, reverse=False, terminate_on_match=False, postprocess=str): """ A powerful regular expression version of grep. Args: filename (str): Filename to grep. patterns (dict): A dict of patterns, e.g., {"energy": "energy\(sigma->0\)\s+=\s+([\d\-\...
[ "def", "regrep", "(", "filename", ",", "patterns", ",", "reverse", "=", "False", ",", "terminate_on_match", "=", "False", ",", "postprocess", "=", "str", ")", ":", "compiled", "=", "{", "k", ":", "re", ".", "compile", "(", "v", ")", "for", "k", ",", ...
A powerful regular expression version of grep. Args: filename (str): Filename to grep. patterns (dict): A dict of patterns, e.g., {"energy": "energy\(sigma->0\)\s+=\s+([\d\-\.]+)"}. reverse (bool): Read files in reverse. Defaults to false. Useful for large files, esp...
[ "A", "powerful", "regular", "expression", "version", "of", "grep", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/re.py#L21-L62
materialsvirtuallab/monty
monty/design_patterns.py
cached_class
def cached_class(klass): """ Decorator to cache class instances by constructor arguments. This results in a class that behaves like a singleton for each set of constructor arguments, ensuring efficiency. Note that this should be used for *immutable classes only*. Having a cached mutable class ...
python
def cached_class(klass): """ Decorator to cache class instances by constructor arguments. This results in a class that behaves like a singleton for each set of constructor arguments, ensuring efficiency. Note that this should be used for *immutable classes only*. Having a cached mutable class ...
[ "def", "cached_class", "(", "klass", ")", ":", "cache", "=", "{", "}", "@", "wraps", "(", "klass", ",", "assigned", "=", "(", "\"__name__\"", ",", "\"__module__\"", ")", ",", "updated", "=", "(", ")", ")", "class", "_decorated", "(", "klass", ")", ":...
Decorator to cache class instances by constructor arguments. This results in a class that behaves like a singleton for each set of constructor arguments, ensuring efficiency. Note that this should be used for *immutable classes only*. Having a cached mutable class makes very little sense. For efficie...
[ "Decorator", "to", "cache", "class", "instances", "by", "constructor", "arguments", ".", "This", "results", "in", "a", "class", "that", "behaves", "like", "a", "singleton", "for", "each", "set", "of", "constructor", "arguments", "ensuring", "efficiency", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/design_patterns.py#L37-L94
materialsvirtuallab/monty
monty/operator.py
operator_from_str
def operator_from_str(op): """ Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2 """ d = {"==": operator.eq, "!=": operator.ne, ">": operator.gt,...
python
def operator_from_str(op): """ Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2 """ d = {"==": operator.eq, "!=": operator.ne, ">": operator.gt,...
[ "def", "operator_from_str", "(", "op", ")", ":", "d", "=", "{", "\"==\"", ":", "operator", ".", "eq", ",", "\"!=\"", ":", "operator", ".", "ne", ",", "\">\"", ":", "operator", ".", "gt", ",", "\">=\"", ":", "operator", ".", "ge", ",", "\"<\"", ":",...
Return the operator associated to the given string `op`. raises: `KeyError` if invalid string. >>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2
[ "Return", "the", "operator", "associated", "to", "the", "given", "string", "op", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/operator.py#L9-L36
materialsvirtuallab/monty
monty/subprocess.py
Command.run
def run(self, timeout=None, **kwargs): """ Run a command in a separated thread and wait timeout seconds. kwargs are keyword arguments passed to Popen. Return: self """ from subprocess import Popen, PIPE def target(**kw): try: # print(...
python
def run(self, timeout=None, **kwargs): """ Run a command in a separated thread and wait timeout seconds. kwargs are keyword arguments passed to Popen. Return: self """ from subprocess import Popen, PIPE def target(**kw): try: # print(...
[ "def", "run", "(", "self", ",", "timeout", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "subprocess", "import", "Popen", ",", "PIPE", "def", "target", "(", "*", "*", "kw", ")", ":", "try", ":", "# print('Thread started')", "self", ".", "pr...
Run a command in a separated thread and wait timeout seconds. kwargs are keyword arguments passed to Popen. Return: self
[ "Run", "a", "command", "in", "a", "separated", "thread", "and", "wait", "timeout", "seconds", ".", "kwargs", "are", "keyword", "arguments", "passed", "to", "Popen", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/subprocess.py#L59-L99
materialsvirtuallab/monty
monty/string.py
marquee
def marquee(text="", width=78, mark='*'): """ Return the input string centered in a 'marquee'. Args: text (str): Input string width (int): Width of final output string. mark (str): Character used to fill string. :Examples: >>> marquee('A test', width=40) '*************...
python
def marquee(text="", width=78, mark='*'): """ Return the input string centered in a 'marquee'. Args: text (str): Input string width (int): Width of final output string. mark (str): Character used to fill string. :Examples: >>> marquee('A test', width=40) '*************...
[ "def", "marquee", "(", "text", "=", "\"\"", ",", "width", "=", "78", ",", "mark", "=", "'*'", ")", ":", "if", "not", "text", ":", "return", "(", "mark", "*", "width", ")", "[", ":", "width", "]", "nmark", "=", "(", "width", "-", "len", "(", "...
Return the input string centered in a 'marquee'. Args: text (str): Input string width (int): Width of final output string. mark (str): Character used to fill string. :Examples: >>> marquee('A test', width=40) '**************** A test ****************' >>> marquee('A test'...
[ "Return", "the", "input", "string", "centered", "in", "a", "marquee", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L90-L118
materialsvirtuallab/monty
monty/string.py
boxed
def boxed(msg, ch="=", pad=5): """ Returns a string in a box Args: msg: Input string. ch: Character used to form the box. pad: Number of characters ch added before and after msg. >>> print(boxed("hello", ch="*", pad=2)) *********** ** hello ** *********** """ ...
python
def boxed(msg, ch="=", pad=5): """ Returns a string in a box Args: msg: Input string. ch: Character used to form the box. pad: Number of characters ch added before and after msg. >>> print(boxed("hello", ch="*", pad=2)) *********** ** hello ** *********** """ ...
[ "def", "boxed", "(", "msg", ",", "ch", "=", "\"=\"", ",", "pad", "=", "5", ")", ":", "if", "pad", ">", "0", ":", "msg", "=", "pad", "*", "ch", "+", "\" \"", "+", "msg", ".", "strip", "(", ")", "+", "\" \"", "+", "pad", "*", "ch", "return", ...
Returns a string in a box Args: msg: Input string. ch: Character used to form the box. pad: Number of characters ch added before and after msg. >>> print(boxed("hello", ch="*", pad=2)) *********** ** hello ** ***********
[ "Returns", "a", "string", "in", "a", "box" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L121-L141
materialsvirtuallab/monty
monty/string.py
indent
def indent(lines, amount, ch=' '): """Indent the lines in a string by padding each one with proper number of pad characters""" padding = amount * ch return padding + ('\n' + padding).join(lines.split('\n'))
python
def indent(lines, amount, ch=' '): """Indent the lines in a string by padding each one with proper number of pad characters""" padding = amount * ch return padding + ('\n' + padding).join(lines.split('\n'))
[ "def", "indent", "(", "lines", ",", "amount", ",", "ch", "=", "' '", ")", ":", "padding", "=", "amount", "*", "ch", "return", "padding", "+", "(", "'\\n'", "+", "padding", ")", ".", "join", "(", "lines", ".", "split", "(", "'\\n'", ")", ")" ]
Indent the lines in a string by padding each one with proper number of pad characters
[ "Indent", "the", "lines", "in", "a", "string", "by", "padding", "each", "one", "with", "proper", "number", "of", "pad", "characters" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L149-L152
materialsvirtuallab/monty
monty/functools.py
lru_cache
def lru_cache(maxsize=128, typed=False): """ Least-recently-used cache decorator, which is a backport of the same function in Python >= 3.2. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be...
python
def lru_cache(maxsize=128, typed=False): """ Least-recently-used cache decorator, which is a backport of the same function in Python >= 3.2. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be...
[ "def", "lru_cache", "(", "maxsize", "=", "128", ",", "typed", "=", "False", ")", ":", "# Users should only access the lru_cache through its public API:", "# cache_info, cache_clear, and f.__wrapped__", "# The internals of the lru_cache are encapsulated for thread safety and", "# ...
Least-recently-used cache decorator, which is a backport of the same function in Python >= 3.2. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) ...
[ "Least", "-", "recently", "-", "used", "cache", "decorator", "which", "is", "a", "backport", "of", "the", "same", "function", "in", "Python", ">", "=", "3", ".", "2", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L81-L225
materialsvirtuallab/monty
monty/functools.py
return_if_raise
def return_if_raise(exception_tuple, retval_if_exc, disabled=False): """ Decorator for functions, methods or properties. Execute the callable in a try block, and return retval_if_exc if one of the exceptions listed in exception_tuple is raised (se also ``return_node_if_raise``). Setting disabled to...
python
def return_if_raise(exception_tuple, retval_if_exc, disabled=False): """ Decorator for functions, methods or properties. Execute the callable in a try block, and return retval_if_exc if one of the exceptions listed in exception_tuple is raised (se also ``return_node_if_raise``). Setting disabled to...
[ "def", "return_if_raise", "(", "exception_tuple", ",", "retval_if_exc", ",", "disabled", "=", "False", ")", ":", "# we need a tuple of exceptions.", "if", "isinstance", "(", "exception_tuple", ",", "list", ")", ":", "exception_tuple", "=", "tuple", "(", "exception_t...
Decorator for functions, methods or properties. Execute the callable in a try block, and return retval_if_exc if one of the exceptions listed in exception_tuple is raised (se also ``return_node_if_raise``). Setting disabled to True disables the try except block (useful for debugging purposes). One can ...
[ "Decorator", "for", "functions", "methods", "or", "properties", ".", "Execute", "the", "callable", "in", "a", "try", "block", "and", "return", "retval_if_exc", "if", "one", "of", "the", "exceptions", "listed", "in", "exception_tuple", "is", "raised", "(", "se"...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L280-L326
materialsvirtuallab/monty
monty/functools.py
prof_main
def prof_main(main): """ Decorator for profiling main programs. Profiling is activated by prepending the command line options supported by the original main program with the keyword `prof`. Example: $ script.py arg --foo=1 becomes $ script.py prof arg --foo=1 The decorat...
python
def prof_main(main): """ Decorator for profiling main programs. Profiling is activated by prepending the command line options supported by the original main program with the keyword `prof`. Example: $ script.py arg --foo=1 becomes $ script.py prof arg --foo=1 The decorat...
[ "def", "prof_main", "(", "main", ")", ":", "@", "wraps", "(", "main", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "sys", "try", ":", "do_prof", "=", "sys", ".", "argv", "[", "1", "]", "==", "\"prof\"", ...
Decorator for profiling main programs. Profiling is activated by prepending the command line options supported by the original main program with the keyword `prof`. Example: $ script.py arg --foo=1 becomes $ script.py prof arg --foo=1 The decorated main accepts two new arguments...
[ "Decorator", "for", "profiling", "main", "programs", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L380-L429
materialsvirtuallab/monty
monty/functools.py
lazy_property.invalidate
def invalidate(cls, inst, name): """Invalidate a lazy attribute. This obviously violates the lazy contract. A subclass of lazy may however have a contract where invalidation is appropriate. """ inst_cls = inst.__class__ if not hasattr(inst, '__dict__'): rais...
python
def invalidate(cls, inst, name): """Invalidate a lazy attribute. This obviously violates the lazy contract. A subclass of lazy may however have a contract where invalidation is appropriate. """ inst_cls = inst.__class__ if not hasattr(inst, '__dict__'): rais...
[ "def", "invalidate", "(", "cls", ",", "inst", ",", "name", ")", ":", "inst_cls", "=", "inst", ".", "__class__", "if", "not", "hasattr", "(", "inst", ",", "'__dict__'", ")", ":", "raise", "AttributeError", "(", "\"'%s' object has no attribute '__dict__'\"", "%"...
Invalidate a lazy attribute. This obviously violates the lazy contract. A subclass of lazy may however have a contract where invalidation is appropriate.
[ "Invalidate", "a", "lazy", "attribute", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L257-L277
materialsvirtuallab/monty
monty/serialization.py
loadfn
def loadfn(fn, *args, **kwargs): """ Loads json/yaml/msgpack directly from a filename instead of a File-like object. For YAML, ruamel.yaml must be installed. The file type is automatically detected. YAML is assumed if the filename contains "yaml" (lower or upper case). Otherwise, json is always assu...
python
def loadfn(fn, *args, **kwargs): """ Loads json/yaml/msgpack directly from a filename instead of a File-like object. For YAML, ruamel.yaml must be installed. The file type is automatically detected. YAML is assumed if the filename contains "yaml" (lower or upper case). Otherwise, json is always assu...
[ "def", "loadfn", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "\"mpk\"", "in", "os", ".", "path", ".", "basename", "(", "fn", ")", ".", "lower", "(", ")", ":", "if", "msgpack", "is", "None", ":", "raise", "RuntimeError", ...
Loads json/yaml/msgpack directly from a filename instead of a File-like object. For YAML, ruamel.yaml must be installed. The file type is automatically detected. YAML is assumed if the filename contains "yaml" (lower or upper case). Otherwise, json is always assumed. Args: fn (str/Path): filena...
[ "Loads", "json", "/", "yaml", "/", "msgpack", "directly", "from", "a", "filename", "instead", "of", "a", "File", "-", "like", "object", ".", "For", "YAML", "ruamel", ".", "yaml", "must", "be", "installed", ".", "The", "file", "type", "is", "automatically...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/serialization.py#L47-L83
materialsvirtuallab/monty
monty/serialization.py
dumpfn
def dumpfn(obj, fn, *args, **kwargs): """ Dump to a json/yaml directly by filename instead of a File-like object. For YAML, ruamel.yaml must be installed. The file type is automatically detected. YAML is assumed if the filename contains "yaml" (lower or upper case). Otherwise, json is always assumed...
python
def dumpfn(obj, fn, *args, **kwargs): """ Dump to a json/yaml directly by filename instead of a File-like object. For YAML, ruamel.yaml must be installed. The file type is automatically detected. YAML is assumed if the filename contains "yaml" (lower or upper case). Otherwise, json is always assumed...
[ "def", "dumpfn", "(", "obj", ",", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "\"mpk\"", "in", "os", ".", "path", ".", "basename", "(", "fn", ")", ".", "lower", "(", ")", ":", "if", "msgpack", "is", "None", ":", "raise", ...
Dump to a json/yaml directly by filename instead of a File-like object. For YAML, ruamel.yaml must be installed. The file type is automatically detected. YAML is assumed if the filename contains "yaml" (lower or upper case). Otherwise, json is always assumed. Args: obj (object): Object to dump....
[ "Dump", "to", "a", "json", "/", "yaml", "directly", "by", "filename", "instead", "of", "a", "File", "-", "like", "object", ".", "For", "YAML", "ruamel", ".", "yaml", "must", "be", "installed", ".", "The", "file", "type", "is", "automatically", "detected"...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/serialization.py#L86-L123
materialsvirtuallab/monty
monty/collections.py
as_set
def as_set(obj): """ Convert obj into a set, returns None if obj is None. >>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2]) """ if obj is None or isinstance(obj, collections.Set): return obj if not isinstance(obj, collections.Iterable): ...
python
def as_set(obj): """ Convert obj into a set, returns None if obj is None. >>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2]) """ if obj is None or isinstance(obj, collections.Set): return obj if not isinstance(obj, collections.Iterable): ...
[ "def", "as_set", "(", "obj", ")", ":", "if", "obj", "is", "None", "or", "isinstance", "(", "obj", ",", "collections", ".", "Set", ")", ":", "return", "obj", "if", "not", "isinstance", "(", "obj", ",", "collections", ".", "Iterable", ")", ":", "return...
Convert obj into a set, returns None if obj is None. >>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2])
[ "Convert", "obj", "into", "a", "set", "returns", "None", "if", "obj", "is", "None", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/collections.py#L30-L42
materialsvirtuallab/monty
monty/collections.py
dict2namedtuple
def dict2namedtuple(*args, **kwargs): """ Helper function to create a :class:`namedtuple` from a dictionary. Example: >>> t = dict2namedtuple(foo=1, bar="hello") >>> assert t.foo == 1 and t.bar == "hello" >>> t = dict2namedtuple([("foo", 1), ("bar", "hello")]) >>> assert t...
python
def dict2namedtuple(*args, **kwargs): """ Helper function to create a :class:`namedtuple` from a dictionary. Example: >>> t = dict2namedtuple(foo=1, bar="hello") >>> assert t.foo == 1 and t.bar == "hello" >>> t = dict2namedtuple([("foo", 1), ("bar", "hello")]) >>> assert t...
[ "def", "dict2namedtuple", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "d", "=", "collections", ".", "OrderedDict", "(", "*", "args", ")", "d", ".", "update", "(", "*", "*", "kwargs", ")", "return", "collections", ".", "namedtuple", "(", "typ...
Helper function to create a :class:`namedtuple` from a dictionary. Example: >>> t = dict2namedtuple(foo=1, bar="hello") >>> assert t.foo == 1 and t.bar == "hello" >>> t = dict2namedtuple([("foo", 1), ("bar", "hello")]) >>> assert t[0] == t.foo and t[1] == t.bar .. warning:: ...
[ "Helper", "function", "to", "create", "a", ":", "class", ":", "namedtuple", "from", "a", "dictionary", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/collections.py#L187-L212
materialsvirtuallab/monty
monty/logging.py
logged
def logged(level=logging.DEBUG): """ Useful logging decorator. If a method is logged, the beginning and end of the method call will be logged at a pre-specified level. Args: level: Level to log method at. Defaults to DEBUG. """ def wrap(f): _logger = logging.getLogger("{}.{}".fo...
python
def logged(level=logging.DEBUG): """ Useful logging decorator. If a method is logged, the beginning and end of the method call will be logged at a pre-specified level. Args: level: Level to log method at. Defaults to DEBUG. """ def wrap(f): _logger = logging.getLogger("{}.{}".fo...
[ "def", "logged", "(", "level", "=", "logging", ".", "DEBUG", ")", ":", "def", "wrap", "(", "f", ")", ":", "_logger", "=", "logging", ".", "getLogger", "(", "\"{}.{}\"", ".", "format", "(", "f", ".", "__module__", ",", "f", ".", "__name__", ")", ")"...
Useful logging decorator. If a method is logged, the beginning and end of the method call will be logged at a pre-specified level. Args: level: Level to log method at. Defaults to DEBUG.
[ "Useful", "logging", "decorator", ".", "If", "a", "method", "is", "logged", "the", "beginning", "and", "end", "of", "the", "method", "call", "will", "be", "logged", "at", "a", "pre", "-", "specified", "level", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/logging.py#L24-L44
materialsvirtuallab/monty
monty/logging.py
enable_logging
def enable_logging(main): """ This decorator is used to decorate main functions. It adds the initialization of the logger and an argument parser that allows one to select the loglevel. Useful if we are writing simple main functions that call libraries where the logging module is used Args: ...
python
def enable_logging(main): """ This decorator is used to decorate main functions. It adds the initialization of the logger and an argument parser that allows one to select the loglevel. Useful if we are writing simple main functions that call libraries where the logging module is used Args: ...
[ "def", "enable_logging", "(", "main", ")", ":", "@", "functools", ".", "wraps", "(", "main", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", ...
This decorator is used to decorate main functions. It adds the initialization of the logger and an argument parser that allows one to select the loglevel. Useful if we are writing simple main functions that call libraries where the logging module is used Args: main: main functio...
[ "This", "decorator", "is", "used", "to", "decorate", "main", "functions", ".", "It", "adds", "the", "initialization", "of", "the", "logger", "and", "an", "argument", "parser", "that", "allows", "one", "to", "select", "the", "loglevel", ".", "Useful", "if", ...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/logging.py#L47-L83
materialsvirtuallab/monty
monty/os/path.py
which
def which(cmd): """ Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python") """ def is_exe(fp): return os.path.isfil...
python
def which(cmd): """ Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python") """ def is_exe(fp): return os.path.isfil...
[ "def", "which", "(", "cmd", ")", ":", "def", "is_exe", "(", "fp", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "fp", ")", "and", "os", ".", "access", "(", "fp", ",", "os", ".", "X_OK", ")", "fpath", ",", "fname", "=", "os", ".",...
Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python")
[ "Returns", "full", "path", "to", "a", "executable", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/os/path.py#L15-L41
materialsvirtuallab/monty
monty/os/path.py
zpath
def zpath(filename): """ Returns an existing (zipped or unzipped) file path given the unzipped version. If no path exists, returns the filename unmodified. Args: filename: filename without zip extension Returns: filename with a zip extension (unless an unzipped version exis...
python
def zpath(filename): """ Returns an existing (zipped or unzipped) file path given the unzipped version. If no path exists, returns the filename unmodified. Args: filename: filename without zip extension Returns: filename with a zip extension (unless an unzipped version exis...
[ "def", "zpath", "(", "filename", ")", ":", "for", "ext", "in", "[", "\"\"", ",", "'.gz'", ",", "'.GZ'", ",", "'.bz2'", ",", "'.BZ2'", ",", "'.z'", ",", "'.Z'", "]", ":", "zfilename", "=", "\"{}{}\"", ".", "format", "(", "filename", ",", "ext", ")",...
Returns an existing (zipped or unzipped) file path given the unzipped version. If no path exists, returns the filename unmodified. Args: filename: filename without zip extension Returns: filename with a zip extension (unless an unzipped version exists). If filename is not found, th...
[ "Returns", "an", "existing", "(", "zipped", "or", "unzipped", ")", "file", "path", "given", "the", "unzipped", "version", ".", "If", "no", "path", "exists", "returns", "the", "filename", "unmodified", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/os/path.py#L44-L61
materialsvirtuallab/monty
monty/os/path.py
find_exts
def find_exts(top, exts, exclude_dirs=None, include_dirs=None, match_mode="basename"): """ Find all files with the extension listed in `exts` that are located within the directory tree rooted at `top` (including top itself, but excluding '.' and '..') Args: top (str): Root dir...
python
def find_exts(top, exts, exclude_dirs=None, include_dirs=None, match_mode="basename"): """ Find all files with the extension listed in `exts` that are located within the directory tree rooted at `top` (including top itself, but excluding '.' and '..') Args: top (str): Root dir...
[ "def", "find_exts", "(", "top", ",", "exts", ",", "exclude_dirs", "=", "None", ",", "include_dirs", "=", "None", ",", "match_mode", "=", "\"basename\"", ")", ":", "from", "monty", ".", "string", "import", "list_strings", "exts", "=", "list_strings", "(", "...
Find all files with the extension listed in `exts` that are located within the directory tree rooted at `top` (including top itself, but excluding '.' and '..') Args: top (str): Root directory exts (str or list of strings): List of extensions. exclude_dirs (str): Wildcards used to e...
[ "Find", "all", "files", "with", "the", "extension", "listed", "in", "exts", "that", "are", "located", "within", "the", "directory", "tree", "rooted", "at", "top", "(", "including", "top", "itself", "but", "excluding", ".", "and", "..", ")" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/os/path.py#L64-L131
materialsvirtuallab/monty
monty/inspect.py
all_subclasses
def all_subclasses(cls): """ Given a class `cls`, this recursive function returns a list with all subclasses, subclasses of subclasses, and so on. """ subclasses = cls.__subclasses__() return subclasses + [g for s in subclasses for g in all_subclasses(s)]
python
def all_subclasses(cls): """ Given a class `cls`, this recursive function returns a list with all subclasses, subclasses of subclasses, and so on. """ subclasses = cls.__subclasses__() return subclasses + [g for s in subclasses for g in all_subclasses(s)]
[ "def", "all_subclasses", "(", "cls", ")", ":", "subclasses", "=", "cls", ".", "__subclasses__", "(", ")", "return", "subclasses", "+", "[", "g", "for", "s", "in", "subclasses", "for", "g", "in", "all_subclasses", "(", "s", ")", "]" ]
Given a class `cls`, this recursive function returns a list with all subclasses, subclasses of subclasses, and so on.
[ "Given", "a", "class", "cls", "this", "recursive", "function", "returns", "a", "list", "with", "all", "subclasses", "subclasses", "of", "subclasses", "and", "so", "on", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/inspect.py#L11-L17
materialsvirtuallab/monty
monty/inspect.py
find_top_pyfile
def find_top_pyfile(): """ This function inspects the Cpython frame to find the path of the script. """ import os frame = currentframe() while True: if frame.f_back is None: finfo = getframeinfo(frame) #print(getframeinfo(frame)) return os.path.abspath...
python
def find_top_pyfile(): """ This function inspects the Cpython frame to find the path of the script. """ import os frame = currentframe() while True: if frame.f_back is None: finfo = getframeinfo(frame) #print(getframeinfo(frame)) return os.path.abspath...
[ "def", "find_top_pyfile", "(", ")", ":", "import", "os", "frame", "=", "currentframe", "(", ")", "while", "True", ":", "if", "frame", ".", "f_back", "is", "None", ":", "finfo", "=", "getframeinfo", "(", "frame", ")", "#print(getframeinfo(frame))", "return", ...
This function inspects the Cpython frame to find the path of the script.
[ "This", "function", "inspects", "the", "Cpython", "frame", "to", "find", "the", "path", "of", "the", "script", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/inspect.py#L20-L32
materialsvirtuallab/monty
monty/inspect.py
initializer
def initializer(func): """ Automatically assigns the parameters. http://stackoverflow.com/questions/1389180/python-automatically-initialize-instance-variables >>> class process: ... @initializer ... def __init__(self, cmd, reachable=False, user='root'): ... pass >>> p = ...
python
def initializer(func): """ Automatically assigns the parameters. http://stackoverflow.com/questions/1389180/python-automatically-initialize-instance-variables >>> class process: ... @initializer ... def __init__(self, cmd, reachable=False, user='root'): ... pass >>> p = ...
[ "def", "initializer", "(", "func", ")", ":", "names", ",", "varargs", ",", "keywords", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "func", ")", "from", "functools", "import", "wraps", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", ...
Automatically assigns the parameters. http://stackoverflow.com/questions/1389180/python-automatically-initialize-instance-variables >>> class process: ... @initializer ... def __init__(self, cmd, reachable=False, user='root'): ... pass >>> p = process('halt', True) >>> p.cmd...
[ "Automatically", "assigns", "the", "parameters", ".", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "1389180", "/", "python", "-", "automatically", "-", "initialize", "-", "instance", "-", "variables" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/inspect.py#L75-L105
materialsvirtuallab/monty
monty/pprint.py
pprint_table
def pprint_table(table, out=sys.stdout, rstrip=False): """ Prints out a table of data, padded for alignment Each row must have the same number of columns. Args: table: The table to print. A list of lists. out: Output stream (file-like object) rstrip: if True, trailing withespace...
python
def pprint_table(table, out=sys.stdout, rstrip=False): """ Prints out a table of data, padded for alignment Each row must have the same number of columns. Args: table: The table to print. A list of lists. out: Output stream (file-like object) rstrip: if True, trailing withespace...
[ "def", "pprint_table", "(", "table", ",", "out", "=", "sys", ".", "stdout", ",", "rstrip", "=", "False", ")", ":", "def", "max_width_col", "(", "table", ",", "col_idx", ")", ":", "\"\"\"\n Get the maximum width of the given column index\n \"\"\"", "ret...
Prints out a table of data, padded for alignment Each row must have the same number of columns. Args: table: The table to print. A list of lists. out: Output stream (file-like object) rstrip: if True, trailing withespaces are removed from the entries.
[ "Prints", "out", "a", "table", "of", "data", "padded", "for", "alignment", "Each", "row", "must", "have", "the", "same", "number", "of", "columns", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/pprint.py#L10-L42
materialsvirtuallab/monty
monty/pprint.py
draw_tree
def draw_tree(node, child_iter=lambda n: n.children, text_str=lambda n: str(n)): """ Args: node: the root of the tree to be drawn, child_iter: function that when called with a node, returns an iterable over all its children text_str: turns a node into the text to be displayed in the tree...
python
def draw_tree(node, child_iter=lambda n: n.children, text_str=lambda n: str(n)): """ Args: node: the root of the tree to be drawn, child_iter: function that when called with a node, returns an iterable over all its children text_str: turns a node into the text to be displayed in the tree...
[ "def", "draw_tree", "(", "node", ",", "child_iter", "=", "lambda", "n", ":", "n", ".", "children", ",", "text_str", "=", "lambda", "n", ":", "str", "(", "n", ")", ")", ":", "return", "_draw_tree", "(", "node", ",", "''", ",", "child_iter", ",", "te...
Args: node: the root of the tree to be drawn, child_iter: function that when called with a node, returns an iterable over all its children text_str: turns a node into the text to be displayed in the tree. The default implementations of these two arguments retrieve the children by accessing ...
[ "Args", ":", "node", ":", "the", "root", "of", "the", "tree", "to", "be", "drawn", "child_iter", ":", "function", "that", "when", "called", "with", "a", "node", "returns", "an", "iterable", "over", "all", "its", "children", "text_str", ":", "turns", "a",...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/pprint.py#L45-L57
materialsvirtuallab/monty
monty/fractions.py
gcd
def gcd(*numbers): """ Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers. """ n = numbers[0] for i in numbers: n = pygcd(n, i) return n
python
def gcd(*numbers): """ Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers. """ n = numbers[0] for i in numbers: n = pygcd(n, i) return n
[ "def", "gcd", "(", "*", "numbers", ")", ":", "n", "=", "numbers", "[", "0", "]", "for", "i", "in", "numbers", ":", "n", "=", "pygcd", "(", "n", ",", "i", ")", "return", "n" ]
Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers.
[ "Returns", "the", "greatest", "common", "divisor", "for", "a", "sequence", "of", "numbers", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L22-L35
materialsvirtuallab/monty
monty/fractions.py
lcm
def lcm(*numbers): """ Return lowest common multiple of a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Lowest common multiple of numbers. """ n = 1 for i in numbers: n = (i * n) // gcd(i, n) return n
python
def lcm(*numbers): """ Return lowest common multiple of a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Lowest common multiple of numbers. """ n = 1 for i in numbers: n = (i * n) // gcd(i, n) return n
[ "def", "lcm", "(", "*", "numbers", ")", ":", "n", "=", "1", "for", "i", "in", "numbers", ":", "n", "=", "(", "i", "*", "n", ")", "//", "gcd", "(", "i", ",", "n", ")", "return", "n" ]
Return lowest common multiple of a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Lowest common multiple of numbers.
[ "Return", "lowest", "common", "multiple", "of", "a", "sequence", "of", "numbers", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L38-L51
materialsvirtuallab/monty
monty/fractions.py
gcd_float
def gcd_float(numbers, tol=1e-8): """ Returns the greatest common divisor for a sequence of numbers. Uses a numerical tolerance, so can be used on floats Args: numbers: Sequence of numbers. tol: Numerical tolerance Returns: (int) Greatest common divisor of numbers. """ ...
python
def gcd_float(numbers, tol=1e-8): """ Returns the greatest common divisor for a sequence of numbers. Uses a numerical tolerance, so can be used on floats Args: numbers: Sequence of numbers. tol: Numerical tolerance Returns: (int) Greatest common divisor of numbers. """ ...
[ "def", "gcd_float", "(", "numbers", ",", "tol", "=", "1e-8", ")", ":", "def", "pair_gcd_tol", "(", "a", ",", "b", ")", ":", "\"\"\"Calculate the Greatest Common Divisor of a and b.\n\n Unless b==0, the result will have the same sign as b (so that when\n b is divided...
Returns the greatest common divisor for a sequence of numbers. Uses a numerical tolerance, so can be used on floats Args: numbers: Sequence of numbers. tol: Numerical tolerance Returns: (int) Greatest common divisor of numbers.
[ "Returns", "the", "greatest", "common", "divisor", "for", "a", "sequence", "of", "numbers", ".", "Uses", "a", "numerical", "tolerance", "so", "can", "be", "used", "on", "floats" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L54-L80
materialsvirtuallab/monty
monty/itertools.py
chunks
def chunks(items, n): """ Yield successive n-sized chunks from a list-like object. >>> import pprint >>> pprint.pprint(list(chunks(range(1, 25), 10))) [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17, 18, 19, 20), (21, 22, 23, 24)] """ it = iter(items) chunk = tup...
python
def chunks(items, n): """ Yield successive n-sized chunks from a list-like object. >>> import pprint >>> pprint.pprint(list(chunks(range(1, 25), 10))) [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17, 18, 19, 20), (21, 22, 23, 24)] """ it = iter(items) chunk = tup...
[ "def", "chunks", "(", "items", ",", "n", ")", ":", "it", "=", "iter", "(", "items", ")", "chunk", "=", "tuple", "(", "itertools", ".", "islice", "(", "it", ",", "n", ")", ")", "while", "chunk", ":", "yield", "chunk", "chunk", "=", "tuple", "(", ...
Yield successive n-sized chunks from a list-like object. >>> import pprint >>> pprint.pprint(list(chunks(range(1, 25), 10))) [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17, 18, 19, 20), (21, 22, 23, 24)]
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "a", "list", "-", "like", "object", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/itertools.py#L7-L21
materialsvirtuallab/monty
monty/itertools.py
iterator_from_slice
def iterator_from_slice(s): """ Constructs an iterator given a slice object s. .. note:: The function returns an infinite iterator if s.stop is None """ import numpy as np start = s.start if s.start is not None else 0 step = s.step if s.step is not None else 1 if s.stop is Non...
python
def iterator_from_slice(s): """ Constructs an iterator given a slice object s. .. note:: The function returns an infinite iterator if s.stop is None """ import numpy as np start = s.start if s.start is not None else 0 step = s.step if s.step is not None else 1 if s.stop is Non...
[ "def", "iterator_from_slice", "(", "s", ")", ":", "import", "numpy", "as", "np", "start", "=", "s", ".", "start", "if", "s", ".", "start", "is", "not", "None", "else", "0", "step", "=", "s", ".", "step", "if", "s", ".", "step", "is", "not", "None...
Constructs an iterator given a slice object s. .. note:: The function returns an infinite iterator if s.stop is None
[ "Constructs", "an", "iterator", "given", "a", "slice", "object", "s", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/itertools.py#L24-L41
materialsvirtuallab/monty
monty/itertools.py
iuptri
def iuptri(items, diago=True, with_inds=False): """ A generator that yields the upper triangle of the matrix (items x items) Args: items: Iterable object with elements [e0, e1, ...] diago: False if diagonal matrix elements should be excluded with_inds: If True, (i,j) (e_i, e_j) is r...
python
def iuptri(items, diago=True, with_inds=False): """ A generator that yields the upper triangle of the matrix (items x items) Args: items: Iterable object with elements [e0, e1, ...] diago: False if diagonal matrix elements should be excluded with_inds: If True, (i,j) (e_i, e_j) is r...
[ "def", "iuptri", "(", "items", ",", "diago", "=", "True", ",", "with_inds", "=", "False", ")", ":", "for", "(", "ii", ",", "item1", ")", "in", "enumerate", "(", "items", ")", ":", "for", "(", "jj", ",", "item2", ")", "in", "enumerate", "(", "item...
A generator that yields the upper triangle of the matrix (items x items) Args: items: Iterable object with elements [e0, e1, ...] diago: False if diagonal matrix elements should be excluded with_inds: If True, (i,j) (e_i, e_j) is returned else (e_i, e_j) >>> for (ij, mate) in iuptri([0...
[ "A", "generator", "that", "yields", "the", "upper", "triangle", "of", "the", "matrix", "(", "items", "x", "items", ")" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/itertools.py#L44-L66
materialsvirtuallab/monty
monty/termcolor.py
colored
def colored(text, color=None, on_color=None, attrs=None): """Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, ...
python
def colored(text, color=None, on_color=None, attrs=None): """Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, ...
[ "def", "colored", "(", "text", ",", "color", "=", "None", ",", "on_color", "=", "None", ",", "attrs", "=", "None", ")", ":", "if", "__ISON", "and", "os", ".", "getenv", "(", "'ANSI_COLORS_DISABLED'", ")", "is", "None", ":", "fmt_str", "=", "'\\033[%dm%...
Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Example: color...
[ "Colorize", "text", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L115-L145
materialsvirtuallab/monty
monty/termcolor.py
cprint
def cprint(text, color=None, on_color=None, attrs=None, **kwargs): """Print colorize text. It accepts arguments of print function. """ try: print((colored(text, color, on_color, attrs)), **kwargs) except TypeError: # flush is not supported by py2.7 kwargs.pop("flush", None) ...
python
def cprint(text, color=None, on_color=None, attrs=None, **kwargs): """Print colorize text. It accepts arguments of print function. """ try: print((colored(text, color, on_color, attrs)), **kwargs) except TypeError: # flush is not supported by py2.7 kwargs.pop("flush", None) ...
[ "def", "cprint", "(", "text", ",", "color", "=", "None", ",", "on_color", "=", "None", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "print", "(", "(", "colored", "(", "text", ",", "color", ",", "on_color", ",", "attrs...
Print colorize text. It accepts arguments of print function.
[ "Print", "colorize", "text", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L148-L158
materialsvirtuallab/monty
monty/termcolor.py
colored_map
def colored_map(text, cmap): """ Return colorized text. cmap is a dict mapping tokens to color options. .. Example: colored_key("foo bar", {bar: "green"}) colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}}) """ if not __ISON: return text for key, v in cmap.i...
python
def colored_map(text, cmap): """ Return colorized text. cmap is a dict mapping tokens to color options. .. Example: colored_key("foo bar", {bar: "green"}) colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}}) """ if not __ISON: return text for key, v in cmap.i...
[ "def", "colored_map", "(", "text", ",", "cmap", ")", ":", "if", "not", "__ISON", ":", "return", "text", "for", "key", ",", "v", "in", "cmap", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "text", "=", "text", ...
Return colorized text. cmap is a dict mapping tokens to color options. .. Example: colored_key("foo bar", {bar: "green"}) colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}})
[ "Return", "colorized", "text", ".", "cmap", "is", "a", "dict", "mapping", "tokens", "to", "color", "options", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L161-L176
materialsvirtuallab/monty
monty/termcolor.py
cprint_map
def cprint_map(text, cmap, **kwargs): """ Print colorize text. cmap is a dict mapping keys to color options. kwargs are passed to print function Example: cprint_map("Hello world", {"Hello": "red"}) """ try: print(colored_map(text, cmap), **kwargs) except TypeError: ...
python
def cprint_map(text, cmap, **kwargs): """ Print colorize text. cmap is a dict mapping keys to color options. kwargs are passed to print function Example: cprint_map("Hello world", {"Hello": "red"}) """ try: print(colored_map(text, cmap), **kwargs) except TypeError: ...
[ "def", "cprint_map", "(", "text", ",", "cmap", ",", "*", "*", "kwargs", ")", ":", "try", ":", "print", "(", "colored_map", "(", "text", ",", "cmap", ")", ",", "*", "*", "kwargs", ")", "except", "TypeError", ":", "# flush is not supported by py2.7", "kwar...
Print colorize text. cmap is a dict mapping keys to color options. kwargs are passed to print function Example: cprint_map("Hello world", {"Hello": "red"})
[ "Print", "colorize", "text", ".", "cmap", "is", "a", "dict", "mapping", "keys", "to", "color", "options", ".", "kwargs", "are", "passed", "to", "print", "function" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L179-L193
materialsvirtuallab/monty
monty/termcolor.py
get_terminal_size
def get_terminal_size(): """" Return the size of the terminal as (nrow, ncols) Based on: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python """ try: rc = os.popen('stty size', 'r').read().split() return int(rc[0]), int(rc[1]) except: ...
python
def get_terminal_size(): """" Return the size of the terminal as (nrow, ncols) Based on: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python """ try: rc = os.popen('stty size', 'r').read().split() return int(rc[0]), int(rc[1]) except: ...
[ "def", "get_terminal_size", "(", ")", ":", "try", ":", "rc", "=", "os", ".", "popen", "(", "'stty size'", ",", "'r'", ")", ".", "read", "(", ")", ".", "split", "(", ")", "return", "int", "(", "rc", "[", "0", "]", ")", ",", "int", "(", "rc", "...
Return the size of the terminal as (nrow, ncols) Based on: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
[ "Return", "the", "size", "of", "the", "terminal", "as", "(", "nrow", "ncols", ")" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L196-L234
materialsvirtuallab/monty
monty/bisect.py
index
def index(a, x, atol=None): """Locate the leftmost value exactly equal to x.""" i = bs.bisect_left(a, x) if i != len(a): if atol is None: if a[i] == x: return i else: if abs(a[i] - x) < atol: return i raise ValueError
python
def index(a, x, atol=None): """Locate the leftmost value exactly equal to x.""" i = bs.bisect_left(a, x) if i != len(a): if atol is None: if a[i] == x: return i else: if abs(a[i] - x) < atol: return i raise ValueError
[ "def", "index", "(", "a", ",", "x", ",", "atol", "=", "None", ")", ":", "i", "=", "bs", ".", "bisect_left", "(", "a", ",", "x", ")", "if", "i", "!=", "len", "(", "a", ")", ":", "if", "atol", "is", "None", ":", "if", "a", "[", "i", "]", ...
Locate the leftmost value exactly equal to x.
[ "Locate", "the", "leftmost", "value", "exactly", "equal", "to", "x", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/bisect.py#L24-L32
materialsvirtuallab/monty
monty/bisect.py
find_lt
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
python
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
[ "def", "find_lt", "(", "a", ",", "x", ")", ":", "i", "=", "bs", ".", "bisect_left", "(", "a", ",", "x", ")", "if", "i", ":", "return", "i", "-", "1", "raise", "ValueError" ]
Find rightmost value less than x.
[ "Find", "rightmost", "value", "less", "than", "x", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/bisect.py#L35-L39
materialsvirtuallab/monty
monty/bisect.py
find_le
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
python
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
[ "def", "find_le", "(", "a", ",", "x", ")", ":", "i", "=", "bs", ".", "bisect_right", "(", "a", ",", "x", ")", "if", "i", ":", "return", "i", "-", "1", "raise", "ValueError" ]
Find rightmost value less than or equal to x.
[ "Find", "rightmost", "value", "less", "than", "or", "equal", "to", "x", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/bisect.py#L42-L46
materialsvirtuallab/monty
monty/bisect.py
find_gt
def find_gt(a, x): """Find leftmost value greater than x.""" i = bs.bisect_right(a, x) if i != len(a): return i raise ValueError
python
def find_gt(a, x): """Find leftmost value greater than x.""" i = bs.bisect_right(a, x) if i != len(a): return i raise ValueError
[ "def", "find_gt", "(", "a", ",", "x", ")", ":", "i", "=", "bs", ".", "bisect_right", "(", "a", ",", "x", ")", "if", "i", "!=", "len", "(", "a", ")", ":", "return", "i", "raise", "ValueError" ]
Find leftmost value greater than x.
[ "Find", "leftmost", "value", "greater", "than", "x", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/bisect.py#L49-L53
materialsvirtuallab/monty
monty/bisect.py
find_ge
def find_ge(a, x): """Find leftmost item greater than or equal to x.""" i = bs.bisect_left(a, x) if i != len(a): return i raise ValueError
python
def find_ge(a, x): """Find leftmost item greater than or equal to x.""" i = bs.bisect_left(a, x) if i != len(a): return i raise ValueError
[ "def", "find_ge", "(", "a", ",", "x", ")", ":", "i", "=", "bs", ".", "bisect_left", "(", "a", ",", "x", ")", "if", "i", "!=", "len", "(", "a", ")", ":", "return", "i", "raise", "ValueError" ]
Find leftmost item greater than or equal to x.
[ "Find", "leftmost", "item", "greater", "than", "or", "equal", "to", "x", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/bisect.py#L56-L60
materialsvirtuallab/monty
monty/json.py
jsanitize
def jsanitize(obj, strict=False, allow_bson=False): """ This method cleans an input json-like object, either a list or a dict or some sequence, nested or otherwise, by converting all non-string dictionary keys (such as int and float) to strings, and also recursively encodes all objects using Monty's...
python
def jsanitize(obj, strict=False, allow_bson=False): """ This method cleans an input json-like object, either a list or a dict or some sequence, nested or otherwise, by converting all non-string dictionary keys (such as int and float) to strings, and also recursively encodes all objects using Monty's...
[ "def", "jsanitize", "(", "obj", ",", "strict", "=", "False", ",", "allow_bson", "=", "False", ")", ":", "if", "allow_bson", "and", "(", "isinstance", "(", "obj", ",", "(", "datetime", ".", "datetime", ",", "bytes", ")", ")", "or", "(", "bson", "is", ...
This method cleans an input json-like object, either a list or a dict or some sequence, nested or otherwise, by converting all non-string dictionary keys (such as int and float) to strings, and also recursively encodes all objects using Monty's as_dict() protocol. Args: obj: input json-like obj...
[ "This", "method", "cleans", "an", "input", "json", "-", "like", "object", "either", "a", "list", "or", "a", "dict", "or", "some", "sequence", "nested", "or", "otherwise", "by", "converting", "all", "non", "-", "string", "dictionary", "keys", "(", "such", ...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L266-L314
materialsvirtuallab/monty
monty/json.py
MSONable.as_dict
def as_dict(self): """ A JSON serializable dict representation of an object. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__} try: parent_module = self.__class__.__module__.split('.')[0] module_version = impor...
python
def as_dict(self): """ A JSON serializable dict representation of an object. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__} try: parent_module = self.__class__.__module__.split('.')[0] module_version = impor...
[ "def", "as_dict", "(", "self", ")", ":", "d", "=", "{", "\"@module\"", ":", "self", ".", "__class__", ".", "__module__", ",", "\"@class\"", ":", "self", ".", "__class__", ".", "__name__", "}", "try", ":", "parent_module", "=", "self", ".", "__class__", ...
A JSON serializable dict representation of an object.
[ "A", "JSON", "serializable", "dict", "representation", "of", "an", "object", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L74-L120
materialsvirtuallab/monty
monty/json.py
MontyEncoder.default
def default(self, o): """ Overriding default method for JSON encoding. This method does two things: (a) If an object has a to_dict property, return the to_dict output. (b) If the @module and @class keys are not in the to_dict, add them to the output automatically. If the object h...
python
def default(self, o): """ Overriding default method for JSON encoding. This method does two things: (a) If an object has a to_dict property, return the to_dict output. (b) If the @module and @class keys are not in the to_dict, add them to the output automatically. If the object h...
[ "def", "default", "(", "self", ",", "o", ")", ":", "if", "isinstance", "(", "o", ",", "datetime", ".", "datetime", ")", ":", "return", "{", "\"@module\"", ":", "\"datetime\"", ",", "\"@class\"", ":", "\"datetime\"", ",", "\"string\"", ":", "o", ".", "_...
Overriding default method for JSON encoding. This method does two things: (a) If an object has a to_dict property, return the to_dict output. (b) If the @module and @class keys are not in the to_dict, add them to the output automatically. If the object has no to_dict property, the defaul...
[ "Overriding", "default", "method", "for", "JSON", "encoding", ".", "This", "method", "does", "two", "things", ":", "(", "a", ")", "If", "an", "object", "has", "a", "to_dict", "property", "return", "the", "to_dict", "output", ".", "(", "b", ")", "If", "...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L146-L192
materialsvirtuallab/monty
monty/json.py
MontyDecoder.process_decoded
def process_decoded(self, d): """ Recursive method to support decoding dicts and lists containing pymatgen objects. """ if isinstance(d, dict): if "@module" in d and "@class" in d: modname = d["@module"] classname = d["@class"] ...
python
def process_decoded(self, d): """ Recursive method to support decoding dicts and lists containing pymatgen objects. """ if isinstance(d, dict): if "@module" in d and "@class" in d: modname = d["@module"] classname = d["@class"] ...
[ "def", "process_decoded", "(", "self", ",", "d", ")", ":", "if", "isinstance", "(", "d", ",", "dict", ")", ":", "if", "\"@module\"", "in", "d", "and", "\"@class\"", "in", "d", ":", "modname", "=", "d", "[", "\"@module\"", "]", "classname", "=", "d", ...
Recursive method to support decoding dicts and lists containing pymatgen objects.
[ "Recursive", "method", "to", "support", "decoding", "dicts", "and", "lists", "containing", "pymatgen", "objects", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L210-L252
materialsvirtuallab/monty
monty/math.py
nCr
def nCr(n, r): """ Calculates nCr. Args: n (int): total number of items. r (int): items to choose Returns: nCr. """ f = math.factorial return int(f(n) / f(r) / f(n-r))
python
def nCr(n, r): """ Calculates nCr. Args: n (int): total number of items. r (int): items to choose Returns: nCr. """ f = math.factorial return int(f(n) / f(r) / f(n-r))
[ "def", "nCr", "(", "n", ",", "r", ")", ":", "f", "=", "math", ".", "factorial", "return", "int", "(", "f", "(", "n", ")", "/", "f", "(", "r", ")", "/", "f", "(", "n", "-", "r", ")", ")" ]
Calculates nCr. Args: n (int): total number of items. r (int): items to choose Returns: nCr.
[ "Calculates", "nCr", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/math.py#L20-L32
materialsvirtuallab/monty
monty/math.py
nPr
def nPr(n, r): """ Calculates nPr. Args: n (int): total number of items. r (int): items to permute Returns: nPr. """ f = math.factorial return int(f(n) / f(n-r))
python
def nPr(n, r): """ Calculates nPr. Args: n (int): total number of items. r (int): items to permute Returns: nPr. """ f = math.factorial return int(f(n) / f(n-r))
[ "def", "nPr", "(", "n", ",", "r", ")", ":", "f", "=", "math", ".", "factorial", "return", "int", "(", "f", "(", "n", ")", "/", "f", "(", "n", "-", "r", ")", ")" ]
Calculates nPr. Args: n (int): total number of items. r (int): items to permute Returns: nPr.
[ "Calculates", "nPr", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/math.py#L35-L47
materialsvirtuallab/monty
monty/shutil.py
copy_r
def copy_r(src, dst): """ Implements a recursive copy function similar to Unix's "cp -r" command. Surprisingly, python does not have a real equivalent. shutil.copytree only works if the destination directory is not present. Args: src (str): Source folder to copy. dst (str): Destinat...
python
def copy_r(src, dst): """ Implements a recursive copy function similar to Unix's "cp -r" command. Surprisingly, python does not have a real equivalent. shutil.copytree only works if the destination directory is not present. Args: src (str): Source folder to copy. dst (str): Destinat...
[ "def", "copy_r", "(", "src", ",", "dst", ")", ":", "abssrc", "=", "os", ".", "path", ".", "abspath", "(", "src", ")", "absdst", "=", "os", ".", "path", ".", "abspath", "(", "dst", ")", "try", ":", "os", ".", "makedirs", "(", "absdst", ")", "exc...
Implements a recursive copy function similar to Unix's "cp -r" command. Surprisingly, python does not have a real equivalent. shutil.copytree only works if the destination directory is not present. Args: src (str): Source folder to copy. dst (str): Destination folder.
[ "Implements", "a", "recursive", "copy", "function", "similar", "to", "Unix", "s", "cp", "-", "r", "command", ".", "Surprisingly", "python", "does", "not", "have", "a", "real", "equivalent", ".", "shutil", ".", "copytree", "only", "works", "if", "the", "des...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L15-L40
materialsvirtuallab/monty
monty/shutil.py
gzip_dir
def gzip_dir(path, compresslevel=6): """ Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: ...
python
def gzip_dir(path, compresslevel=6): """ Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: ...
[ "def", "gzip_dir", "(", "path", ",", "compresslevel", "=", "6", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "full_f", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "not", "f", ".", "lower", ...
Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: path (str): Path to directory. compressl...
[ "Gzips", "all", "files", "in", "a", "directory", ".", "Note", "that", "this", "is", "different", "from", "shutil", ".", "make_archive", "which", "creates", "a", "tar", "archive", ".", "The", "aim", "of", "this", "method", "is", "to", "create", "gzipped", ...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L43-L63
materialsvirtuallab/monty
monty/shutil.py
compress_file
def compress_file(filepath, compression="gz"): """ Compresses a file with the correct extension. Functions like standard Unix command line gzip and bzip2 in the sense that the original uncompressed files are not retained. Args: filepath (str): Path to file. compression (str): A comp...
python
def compress_file(filepath, compression="gz"): """ Compresses a file with the correct extension. Functions like standard Unix command line gzip and bzip2 in the sense that the original uncompressed files are not retained. Args: filepath (str): Path to file. compression (str): A comp...
[ "def", "compress_file", "(", "filepath", ",", "compression", "=", "\"gz\"", ")", ":", "if", "compression", "not", "in", "[", "\"gz\"", ",", "\"bz2\"", "]", ":", "raise", "ValueError", "(", "\"Supported compression formats are 'gz' and 'bz2'.\"", ")", "from", "mont...
Compresses a file with the correct extension. Functions like standard Unix command line gzip and bzip2 in the sense that the original uncompressed files are not retained. Args: filepath (str): Path to file. compression (str): A compression mode. Valid options are "gz" or "bz2". ...
[ "Compresses", "a", "file", "with", "the", "correct", "extension", ".", "Functions", "like", "standard", "Unix", "command", "line", "gzip", "and", "bzip2", "in", "the", "sense", "that", "the", "original", "uncompressed", "files", "are", "not", "retained", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L66-L84
materialsvirtuallab/monty
monty/shutil.py
compress_dir
def compress_dir(path, compression="gz"): """ Recursively compresses all files in a directory. Note that this compresses all files singly, i.e., it does not create a tar archive. For that, just use Python tarfile class. Args: path (str): Path to parent directory. compression (str): ...
python
def compress_dir(path, compression="gz"): """ Recursively compresses all files in a directory. Note that this compresses all files singly, i.e., it does not create a tar archive. For that, just use Python tarfile class. Args: path (str): Path to parent directory. compression (str): ...
[ "def", "compress_dir", "(", "path", ",", "compression", "=", "\"gz\"", ")", ":", "for", "parent", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "f", "in", "files", ":", "compress_file", "(", "os", ".", "path", ...
Recursively compresses all files in a directory. Note that this compresses all files singly, i.e., it does not create a tar archive. For that, just use Python tarfile class. Args: path (str): Path to parent directory. compression (str): A compression mode. Valid options are "gz" or ...
[ "Recursively", "compresses", "all", "files", "in", "a", "directory", ".", "Note", "that", "this", "compresses", "all", "files", "singly", "i", ".", "e", ".", "it", "does", "not", "create", "a", "tar", "archive", ".", "For", "that", "just", "use", "Python...
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L87-L100
materialsvirtuallab/monty
monty/shutil.py
decompress_file
def decompress_file(filepath): """ Decompresses a file with the correct extension. Automatically detects gz, bz2 or z extension. Args: filepath (str): Path to file. compression (str): A compression mode. Valid options are "gz" or "bz2". Defaults to "gz". """ toks = f...
python
def decompress_file(filepath): """ Decompresses a file with the correct extension. Automatically detects gz, bz2 or z extension. Args: filepath (str): Path to file. compression (str): A compression mode. Valid options are "gz" or "bz2". Defaults to "gz". """ toks = f...
[ "def", "decompress_file", "(", "filepath", ")", ":", "toks", "=", "filepath", ".", "split", "(", "\".\"", ")", "file_ext", "=", "toks", "[", "-", "1", "]", ".", "upper", "(", ")", "from", "monty", ".", "io", "import", "zopen", "if", "file_ext", "in",...
Decompresses a file with the correct extension. Automatically detects gz, bz2 or z extension. Args: filepath (str): Path to file. compression (str): A compression mode. Valid options are "gz" or "bz2". Defaults to "gz".
[ "Decompresses", "a", "file", "with", "the", "correct", "extension", ".", "Automatically", "detects", "gz", "bz2", "or", "z", "extension", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L103-L120
materialsvirtuallab/monty
monty/shutil.py
decompress_dir
def decompress_dir(path): """ Recursively decompresses all files in a directory. Args: path (str): Path to parent directory. """ for parent, subdirs, files in os.walk(path): for f in files: decompress_file(os.path.join(parent, f))
python
def decompress_dir(path): """ Recursively decompresses all files in a directory. Args: path (str): Path to parent directory. """ for parent, subdirs, files in os.walk(path): for f in files: decompress_file(os.path.join(parent, f))
[ "def", "decompress_dir", "(", "path", ")", ":", "for", "parent", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "f", "in", "files", ":", "decompress_file", "(", "os", ".", "path", ".", "join", "(", "parent", ",...
Recursively decompresses all files in a directory. Args: path (str): Path to parent directory.
[ "Recursively", "decompresses", "all", "files", "in", "a", "directory", "." ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L123-L132
materialsvirtuallab/monty
monty/shutil.py
remove
def remove(path, follow_symlink=False): """ Implements an remove function that will delete files, folder trees and symlink trees 1.) Remove a file 2.) Remove a symlink and follow into with a recursive rm if follow_symlink 3.) Remove directory with rmtree Args: path (str): path to remov...
python
def remove(path, follow_symlink=False): """ Implements an remove function that will delete files, folder trees and symlink trees 1.) Remove a file 2.) Remove a symlink and follow into with a recursive rm if follow_symlink 3.) Remove directory with rmtree Args: path (str): path to remov...
[ "def", "remove", "(", "path", ",", "follow_symlink", "=", "False", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")", "elif", "os", ".", "path", ".", "islink", "(", "path", ")", ":", ...
Implements an remove function that will delete files, folder trees and symlink trees 1.) Remove a file 2.) Remove a symlink and follow into with a recursive rm if follow_symlink 3.) Remove directory with rmtree Args: path (str): path to remove follow_symlink(bool): follow symlinks and ...
[ "Implements", "an", "remove", "function", "that", "will", "delete", "files", "folder", "trees", "and", "symlink", "trees" ]
train
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L135-L154
fair-research/bdbag
bdbag/bdbag_utils.py
compute_hashes
def compute_hashes(obj, hashes=frozenset(['md5'])): """ Digests input data read from file-like object fd or passed directly as bytes-like object. Compute hashes for multiple algorithms. Default is MD5. Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTT...
python
def compute_hashes(obj, hashes=frozenset(['md5'])): """ Digests input data read from file-like object fd or passed directly as bytes-like object. Compute hashes for multiple algorithms. Default is MD5. Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTT...
[ "def", "compute_hashes", "(", "obj", ",", "hashes", "=", "frozenset", "(", "[", "'md5'", "]", ")", ")", ":", "if", "not", "(", "hasattr", "(", "obj", ",", "'read'", ")", "or", "isinstance", "(", "obj", ",", "bytes", ")", ")", ":", "raise", "ValueEr...
Digests input data read from file-like object fd or passed directly as bytes-like object. Compute hashes for multiple algorithms. Default is MD5. Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTTP header.
[ "Digests", "input", "data", "read", "from", "file", "-", "like", "object", "fd", "or", "passed", "directly", "as", "bytes", "-", "like", "object", ".", "Compute", "hashes", "for", "multiple", "algorithms", ".", "Default", "is", "MD5", ".", "Returns", "a", ...
train
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbag_utils.py#L221-L258
fair-research/bdbag
bdbag/bdbag_utils.py
compute_file_hashes
def compute_file_hashes(file_path, hashes=frozenset(['md5'])): """ Digests data read from file denoted by file_path. """ if not os.path.exists(file_path): logging.warning("%s does not exist" % file_path) return else: logging.debug("Computing [%s] hashes for file [%s]" % ('...
python
def compute_file_hashes(file_path, hashes=frozenset(['md5'])): """ Digests data read from file denoted by file_path. """ if not os.path.exists(file_path): logging.warning("%s does not exist" % file_path) return else: logging.debug("Computing [%s] hashes for file [%s]" % ('...
[ "def", "compute_file_hashes", "(", "file_path", ",", "hashes", "=", "frozenset", "(", "[", "'md5'", "]", ")", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "logging", ".", "warning", "(", "\"%s does not exist\"", "%...
Digests data read from file denoted by file_path.
[ "Digests", "data", "read", "from", "file", "denoted", "by", "file_path", "." ]
train
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbag_utils.py#L261-L276
fair-research/bdbag
bdbag/bdbagit.py
make_bag
def make_bag(bag_dir, bag_info=None, processes=1, checksums=None, encoding='utf-8', remote_entries=None, spec_version="0.97"): """ Convert a given directory into a bag. You can pass in arbitrary key/value pairs to put into the bag...
python
def make_bag(bag_dir, bag_info=None, processes=1, checksums=None, encoding='utf-8', remote_entries=None, spec_version="0.97"): """ Convert a given directory into a bag. You can pass in arbitrary key/value pairs to put into the bag...
[ "def", "make_bag", "(", "bag_dir", ",", "bag_info", "=", "None", ",", "processes", "=", "1", ",", "checksums", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "remote_entries", "=", "None", ",", "spec_version", "=", "\"0.97\"", ")", ":", "if", "spec_v...
Convert a given directory into a bag. You can pass in arbitrary key/value pairs to put into the bag-info.txt metadata file as the bag_info dictionary.
[ "Convert", "a", "given", "directory", "into", "a", "bag", ".", "You", "can", "pass", "in", "arbitrary", "key", "/", "value", "pairs", "to", "put", "into", "the", "bag", "-", "info", ".", "txt", "metadata", "file", "as", "the", "bag_info", "dictionary", ...
train
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L50-L162
fair-research/bdbag
bdbag/bdbagit.py
BDBag.save
def save(self, processes=1, manifests=False): """ save will persist any changes that have been made to the bag metadata (self.info). If you have modified the payload of the bag (added, modified, removed files in the data directory) and want to regenerate manifests set th...
python
def save(self, processes=1, manifests=False): """ save will persist any changes that have been made to the bag metadata (self.info). If you have modified the payload of the bag (added, modified, removed files in the data directory) and want to regenerate manifests set th...
[ "def", "save", "(", "self", ",", "processes", "=", "1", ",", "manifests", "=", "False", ")", ":", "# Error checking", "if", "not", "self", ".", "path", ":", "raise", "BagError", "(", "_", "(", "'Bag.save() called before setting the path!'", ")", ")", "if", ...
save will persist any changes that have been made to the bag metadata (self.info). If you have modified the payload of the bag (added, modified, removed files in the data directory) and want to regenerate manifests set the manifests parameter to True. The default is False since you ...
[ "save", "will", "persist", "any", "changes", "that", "have", "been", "made", "to", "the", "bag", "metadata", "(", "self", ".", "info", ")", "." ]
train
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L397-L471
fair-research/bdbag
bdbag/bdbagit.py
BDBag.validate
def validate(self, processes=1, fast=False, completeness_only=False, callback=None): """Checks the structure and contents are valid. If you supply the parameter fast=True the Payload-Oxum (if present) will be used to check that the payload files are present and accounted for, instead of...
python
def validate(self, processes=1, fast=False, completeness_only=False, callback=None): """Checks the structure and contents are valid. If you supply the parameter fast=True the Payload-Oxum (if present) will be used to check that the payload files are present and accounted for, instead of...
[ "def", "validate", "(", "self", ",", "processes", "=", "1", ",", "fast", "=", "False", ",", "completeness_only", "=", "False", ",", "callback", "=", "None", ")", ":", "self", ".", "_validate_structure", "(", ")", "self", ".", "_validate_bagittxt", "(", "...
Checks the structure and contents are valid. If you supply the parameter fast=True the Payload-Oxum (if present) will be used to check that the payload files are present and accounted for, instead of re-calculating fixities and comparing them against the manifest. By default validate() ...
[ "Checks", "the", "structure", "and", "contents", "are", "valid", "." ]
train
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L473-L489
fair-research/bdbag
bdbag/bdbagit.py
BDBag._validate_fetch
def _validate_fetch(self): """Validate the fetch.txt file Raises `BagError` for errors and otherwise returns no value """ for url, file_size, filename in self.fetch_entries(): # fetch_entries will raise a BagError for unsafe filenames # so at this point we will c...
python
def _validate_fetch(self): """Validate the fetch.txt file Raises `BagError` for errors and otherwise returns no value """ for url, file_size, filename in self.fetch_entries(): # fetch_entries will raise a BagError for unsafe filenames # so at this point we will c...
[ "def", "_validate_fetch", "(", "self", ")", ":", "for", "url", ",", "file_size", ",", "filename", "in", "self", ".", "fetch_entries", "(", ")", ":", "# fetch_entries will raise a BagError for unsafe filenames", "# so at this point we will check only that the URL is minimally"...
Validate the fetch.txt file Raises `BagError` for errors and otherwise returns no value
[ "Validate", "the", "fetch", ".", "txt", "file" ]
train
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L491-L505
fair-research/bdbag
bdbag/bdbagit.py
BDBag._validate_completeness
def _validate_completeness(self): """ Verify that the actual file manifests match the files in the data directory """ errors = list() # First we'll make sure there's no mismatch between the filesystem # and the list of files in the manifest(s) only_in_manifests, ...
python
def _validate_completeness(self): """ Verify that the actual file manifests match the files in the data directory """ errors = list() # First we'll make sure there's no mismatch between the filesystem # and the list of files in the manifest(s) only_in_manifests, ...
[ "def", "_validate_completeness", "(", "self", ")", ":", "errors", "=", "list", "(", ")", "# First we'll make sure there's no mismatch between the filesystem", "# and the list of files in the manifest(s)", "only_in_manifests", ",", "only_on_fs", ",", "only_in_fetch", "=", "self"...
Verify that the actual file manifests match the files in the data directory
[ "Verify", "that", "the", "actual", "file", "manifests", "match", "the", "files", "in", "the", "data", "directory" ]
train
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L523-L546
fair-research/bdbag
bdbag/bdbagit.py
BDBag._validate_entries
def _validate_entries(self, processes, callback=None): """ Verify that the actual file contents match the recorded hashes stored in the manifest files """ errors = list() if os.name == 'posix': worker_init = posix_multiprocessing_worker_initializer else: ...
python
def _validate_entries(self, processes, callback=None): """ Verify that the actual file contents match the recorded hashes stored in the manifest files """ errors = list() if os.name == 'posix': worker_init = posix_multiprocessing_worker_initializer else: ...
[ "def", "_validate_entries", "(", "self", ",", "processes", ",", "callback", "=", "None", ")", ":", "errors", "=", "list", "(", ")", "if", "os", ".", "name", "==", "'posix'", ":", "worker_init", "=", "posix_multiprocessing_worker_initializer", "else", ":", "w...
Verify that the actual file contents match the recorded hashes stored in the manifest files
[ "Verify", "that", "the", "actual", "file", "contents", "match", "the", "recorded", "hashes", "stored", "in", "the", "manifest", "files" ]
train
https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L548-L600
alertot/detectem
detectem/cli.py
get_detection_results
def get_detection_results(url, timeout, metadata=False, save_har=False): """ Return results from detector. This function prepares the environment loading the plugins, getting the response and passing it to the detector. In case of errors, it raises exceptions to be handled externally. """ plu...
python
def get_detection_results(url, timeout, metadata=False, save_har=False): """ Return results from detector. This function prepares the environment loading the plugins, getting the response and passing it to the detector. In case of errors, it raises exceptions to be handled externally. """ plu...
[ "def", "get_detection_results", "(", "url", ",", "timeout", ",", "metadata", "=", "False", ",", "save_har", "=", "False", ")", ":", "plugins", "=", "load_plugins", "(", ")", "if", "not", "plugins", ":", "raise", "NoPluginsError", "(", "'No plugins found'", "...
Return results from detector. This function prepares the environment loading the plugins, getting the response and passing it to the detector. In case of errors, it raises exceptions to be handled externally.
[ "Return", "results", "from", "detector", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/cli.py#L73-L106
alertot/detectem
detectem/cli.py
get_plugins
def get_plugins(metadata): """ Return the registered plugins. Load and return all registered plugins. """ plugins = load_plugins() if not plugins: raise NoPluginsError('No plugins found') results = [] for p in sorted(plugins.get_all(), key=attrgetter('name')): if metadata: ...
python
def get_plugins(metadata): """ Return the registered plugins. Load and return all registered plugins. """ plugins = load_plugins() if not plugins: raise NoPluginsError('No plugins found') results = [] for p in sorted(plugins.get_all(), key=attrgetter('name')): if metadata: ...
[ "def", "get_plugins", "(", "metadata", ")", ":", "plugins", "=", "load_plugins", "(", ")", "if", "not", "plugins", ":", "raise", "NoPluginsError", "(", "'No plugins found'", ")", "results", "=", "[", "]", "for", "p", "in", "sorted", "(", "plugins", ".", ...
Return the registered plugins. Load and return all registered plugins.
[ "Return", "the", "registered", "plugins", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/cli.py#L109-L128
alertot/detectem
detectem/utils.py
get_most_complete_pm
def get_most_complete_pm(pms): """ Return plugin match with longer version, if not available will return plugin match with ``presence=True`` """ if not pms: return None selected_version = None selected_presence = None for pm in pms: if pm.version: if not sel...
python
def get_most_complete_pm(pms): """ Return plugin match with longer version, if not available will return plugin match with ``presence=True`` """ if not pms: return None selected_version = None selected_presence = None for pm in pms: if pm.version: if not sel...
[ "def", "get_most_complete_pm", "(", "pms", ")", ":", "if", "not", "pms", ":", "return", "None", "selected_version", "=", "None", "selected_presence", "=", "None", "for", "pm", "in", "pms", ":", "if", "pm", ".", "version", ":", "if", "not", "selected_versio...
Return plugin match with longer version, if not available will return plugin match with ``presence=True``
[ "Return", "plugin", "match", "with", "longer", "version", "if", "not", "available", "will", "return", "plugin", "match", "with", "presence", "=", "True" ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/utils.py#L25-L45
alertot/detectem
detectem/utils.py
docker_container
def docker_container(): """ Start the Splash server on a Docker container. If the container doesn't exist, it is created and named 'splash-detectem'. """ if SETUP_SPLASH: dm = DockerManager() dm.start_container() try: requests.post(f'{SPLASH_URL}/_gc') except requests.e...
python
def docker_container(): """ Start the Splash server on a Docker container. If the container doesn't exist, it is created and named 'splash-detectem'. """ if SETUP_SPLASH: dm = DockerManager() dm.start_container() try: requests.post(f'{SPLASH_URL}/_gc') except requests.e...
[ "def", "docker_container", "(", ")", ":", "if", "SETUP_SPLASH", ":", "dm", "=", "DockerManager", "(", ")", "dm", ".", "start_container", "(", ")", "try", ":", "requests", ".", "post", "(", "f'{SPLASH_URL}/_gc'", ")", "except", "requests", ".", "exceptions", ...
Start the Splash server on a Docker container. If the container doesn't exist, it is created and named 'splash-detectem'.
[ "Start", "the", "Splash", "server", "on", "a", "Docker", "container", ".", "If", "the", "container", "doesn", "t", "exist", "it", "is", "created", "and", "named", "splash", "-", "detectem", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/utils.py#L126-L140
alertot/detectem
detectem/response.py
is_url_allowed
def is_url_allowed(url): """ Return ``True`` if ``url`` is not in ``blacklist``. :rtype: bool """ blacklist = [ r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif', r'\.svg' ] for ft in blacklist: if re.search(ft, url): return Fal...
python
def is_url_allowed(url): """ Return ``True`` if ``url`` is not in ``blacklist``. :rtype: bool """ blacklist = [ r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif', r'\.svg' ] for ft in blacklist: if re.search(ft, url): return Fal...
[ "def", "is_url_allowed", "(", "url", ")", ":", "blacklist", "=", "[", "r'\\.ttf'", ",", "r'\\.woff'", ",", "r'fonts\\.googleapis\\.com'", ",", "r'\\.png'", ",", "r'\\.jpe?g'", ",", "r'\\.gif'", ",", "r'\\.svg'", "]", "for", "ft", "in", "blacklist", ":", "if", ...
Return ``True`` if ``url`` is not in ``blacklist``. :rtype: bool
[ "Return", "True", "if", "url", "is", "not", "in", "blacklist", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L21-L36
alertot/detectem
detectem/response.py
is_valid_mimetype
def is_valid_mimetype(response): """ Return ``True`` if the mimetype is not blacklisted. :rtype: bool """ blacklist = [ 'image/', ] mimetype = response.get('mimeType') if not mimetype: return True for bw in blacklist: if bw in mimetype: return Fals...
python
def is_valid_mimetype(response): """ Return ``True`` if the mimetype is not blacklisted. :rtype: bool """ blacklist = [ 'image/', ] mimetype = response.get('mimeType') if not mimetype: return True for bw in blacklist: if bw in mimetype: return Fals...
[ "def", "is_valid_mimetype", "(", "response", ")", ":", "blacklist", "=", "[", "'image/'", ",", "]", "mimetype", "=", "response", ".", "get", "(", "'mimeType'", ")", "if", "not", "mimetype", ":", "return", "True", "for", "bw", "in", "blacklist", ":", "if"...
Return ``True`` if the mimetype is not blacklisted. :rtype: bool
[ "Return", "True", "if", "the", "mimetype", "is", "not", "blacklisted", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L39-L57
alertot/detectem
detectem/response.py
get_charset
def get_charset(response): """ Return charset from ``response`` or default charset. :rtype: str """ # Set default charset charset = DEFAULT_CHARSET m = re.findall(r';charset=(.*)', response.get('mimeType', '')) if m: charset = m[0] return charset
python
def get_charset(response): """ Return charset from ``response`` or default charset. :rtype: str """ # Set default charset charset = DEFAULT_CHARSET m = re.findall(r';charset=(.*)', response.get('mimeType', '')) if m: charset = m[0] return charset
[ "def", "get_charset", "(", "response", ")", ":", "# Set default charset", "charset", "=", "DEFAULT_CHARSET", "m", "=", "re", ".", "findall", "(", "r';charset=(.*)'", ",", "response", ".", "get", "(", "'mimeType'", ",", "''", ")", ")", "if", "m", ":", "char...
Return charset from ``response`` or default charset. :rtype: str
[ "Return", "charset", "from", "response", "or", "default", "charset", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L60-L73
alertot/detectem
detectem/response.py
create_lua_script
def create_lua_script(plugins): """ Return script template filled up with plugin javascript data. :rtype: str """ lua_template = pkg_resources.resource_string('detectem', 'script.lua') template = Template(lua_template.decode('utf-8')) javascript_data = to_javascript_data(plugins) return ...
python
def create_lua_script(plugins): """ Return script template filled up with plugin javascript data. :rtype: str """ lua_template = pkg_resources.resource_string('detectem', 'script.lua') template = Template(lua_template.decode('utf-8')) javascript_data = to_javascript_data(plugins) return ...
[ "def", "create_lua_script", "(", "plugins", ")", ":", "lua_template", "=", "pkg_resources", ".", "resource_string", "(", "'detectem'", ",", "'script.lua'", ")", "template", "=", "Template", "(", "lua_template", ".", "decode", "(", "'utf-8'", ")", ")", "javascrip...
Return script template filled up with plugin javascript data. :rtype: str
[ "Return", "script", "template", "filled", "up", "with", "plugin", "javascript", "data", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L76-L87
alertot/detectem
detectem/response.py
to_javascript_data
def to_javascript_data(plugins): """ Return a dictionary with all JavaScript matchers. Quotes are escaped. :rtype: dict """ def escape(v): return re.sub(r'"', r'\\"', v) def dom_matchers(p): dom_matchers = p.get_matchers('dom') escaped_dom_matchers = [] for d...
python
def to_javascript_data(plugins): """ Return a dictionary with all JavaScript matchers. Quotes are escaped. :rtype: dict """ def escape(v): return re.sub(r'"', r'\\"', v) def dom_matchers(p): dom_matchers = p.get_matchers('dom') escaped_dom_matchers = [] for d...
[ "def", "to_javascript_data", "(", "plugins", ")", ":", "def", "escape", "(", "v", ")", ":", "return", "re", ".", "sub", "(", "r'\"'", ",", "r'\\\\\"'", ",", "v", ")", "def", "dom_matchers", "(", "p", ")", ":", "dom_matchers", "=", "p", ".", "get_matc...
Return a dictionary with all JavaScript matchers. Quotes are escaped. :rtype: dict
[ "Return", "a", "dictionary", "with", "all", "JavaScript", "matchers", ".", "Quotes", "are", "escaped", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L90-L117
alertot/detectem
detectem/response.py
get_response
def get_response(url, plugins, timeout=SPLASH_TIMEOUT): """ Return response with HAR, inline scritps and software detected by JS matchers. :rtype: dict """ lua_script = create_lua_script(plugins) lua = urllib.parse.quote_plus(lua_script) page_url = f'{SPLASH_URL}/execute?url={url}&timeout=...
python
def get_response(url, plugins, timeout=SPLASH_TIMEOUT): """ Return response with HAR, inline scritps and software detected by JS matchers. :rtype: dict """ lua_script = create_lua_script(plugins) lua = urllib.parse.quote_plus(lua_script) page_url = f'{SPLASH_URL}/execute?url={url}&timeout=...
[ "def", "get_response", "(", "url", ",", "plugins", ",", "timeout", "=", "SPLASH_TIMEOUT", ")", ":", "lua_script", "=", "create_lua_script", "(", "plugins", ")", "lua", "=", "urllib", ".", "parse", ".", "quote_plus", "(", "lua_script", ")", "page_url", "=", ...
Return response with HAR, inline scritps and software detected by JS matchers. :rtype: dict
[ "Return", "response", "with", "HAR", "inline", "scritps", "and", "software", "detected", "by", "JS", "matchers", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L120-L157
alertot/detectem
detectem/response.py
get_valid_har
def get_valid_har(har_data): """ Return list of valid HAR entries. :rtype: list """ new_entries = [] entries = har_data.get('log', {}).get('entries', []) logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)}) for entry in entries: url = entry['request']['url'] ...
python
def get_valid_har(har_data): """ Return list of valid HAR entries. :rtype: list """ new_entries = [] entries = har_data.get('log', {}).get('entries', []) logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)}) for entry in entries: url = entry['request']['url'] ...
[ "def", "get_valid_har", "(", "har_data", ")", ":", "new_entries", "=", "[", "]", "entries", "=", "har_data", ".", "get", "(", "'log'", ",", "{", "}", ")", ".", "get", "(", "'entries'", ",", "[", "]", ")", "logger", ".", "debug", "(", "'[+] Detected %...
Return list of valid HAR entries. :rtype: list
[ "Return", "list", "of", "valid", "HAR", "entries", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L194-L223
alertot/detectem
scripts/get_software_hashes.py
get_files_from_github
def get_files_from_github(user_and_repo, filedir, regex, prefer_tags): ''' Return dictionary of version:directory and directory has extracted files. ''' github_url = f'https://api.github.com/repos/{user_and_repo}' args = f'?per_page={N_RESULTS}' results = [] json_data = None # Determine the rig...
python
def get_files_from_github(user_and_repo, filedir, regex, prefer_tags): ''' Return dictionary of version:directory and directory has extracted files. ''' github_url = f'https://api.github.com/repos/{user_and_repo}' args = f'?per_page={N_RESULTS}' results = [] json_data = None # Determine the rig...
[ "def", "get_files_from_github", "(", "user_and_repo", ",", "filedir", ",", "regex", ",", "prefer_tags", ")", ":", "github_url", "=", "f'https://api.github.com/repos/{user_and_repo}'", "args", "=", "f'?per_page={N_RESULTS}'", "results", "=", "[", "]", "json_data", "=", ...
Return dictionary of version:directory and directory has extracted files.
[ "Return", "dictionary", "of", "version", ":", "directory", "and", "directory", "has", "extracted", "files", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/scripts/get_software_hashes.py#L21-L72
alertot/detectem
detectem/core.py
HarProcessor._script_to_har_entry
def _script_to_har_entry(cls, script, url): ''' Return entry for embed script ''' entry = { 'request': {'url': url}, 'response': {'url': url, 'content': {'text': script}} } cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY) return entry
python
def _script_to_har_entry(cls, script, url): ''' Return entry for embed script ''' entry = { 'request': {'url': url}, 'response': {'url': url, 'content': {'text': script}} } cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY) return entry
[ "def", "_script_to_har_entry", "(", "cls", ",", "script", ",", "url", ")", ":", "entry", "=", "{", "'request'", ":", "{", "'url'", ":", "url", "}", ",", "'response'", ":", "{", "'url'", ":", "url", ",", "'content'", ":", "{", "'text'", ":", "script",...
Return entry for embed script
[ "Return", "entry", "for", "embed", "script" ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L56-L65
alertot/detectem
detectem/core.py
HarProcessor.mark_entries
def mark_entries(self, entries): ''' Mark one entry as main entry and the rest as resource entry. Main entry is the entry that contain response's body of the requested URL. ''' for entry in entries: self._set_entry_type(entry, RESOURCE_ENTRY) # If f...
python
def mark_entries(self, entries): ''' Mark one entry as main entry and the rest as resource entry. Main entry is the entry that contain response's body of the requested URL. ''' for entry in entries: self._set_entry_type(entry, RESOURCE_ENTRY) # If f...
[ "def", "mark_entries", "(", "self", ",", "entries", ")", ":", "for", "entry", "in", "entries", ":", "self", ".", "_set_entry_type", "(", "entry", ",", "RESOURCE_ENTRY", ")", "# If first entry doesn't have a redirect, set is as main entry", "main_entry", "=", "entries"...
Mark one entry as main entry and the rest as resource entry. Main entry is the entry that contain response's body of the requested URL.
[ "Mark", "one", "entry", "as", "main", "entry", "and", "the", "rest", "as", "resource", "entry", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L67-L93
alertot/detectem
detectem/core.py
Detector.get_hints
def get_hints(self, plugin): ''' Return plugin hints from ``plugin``. ''' hints = [] for hint_name in getattr(plugin, 'hints', []): hint_plugin = self._plugins.get(hint_name) if hint_plugin: hint_result = Result( name=hint_plugin.name,...
python
def get_hints(self, plugin): ''' Return plugin hints from ``plugin``. ''' hints = [] for hint_name in getattr(plugin, 'hints', []): hint_plugin = self._plugins.get(hint_name) if hint_plugin: hint_result = Result( name=hint_plugin.name,...
[ "def", "get_hints", "(", "self", ",", "plugin", ")", ":", "hints", "=", "[", "]", "for", "hint_name", "in", "getattr", "(", "plugin", ",", "'hints'", ",", "[", "]", ")", ":", "hint_plugin", "=", "self", ".", "_plugins", ".", "get", "(", "hint_name", ...
Return plugin hints from ``plugin``.
[ "Return", "plugin", "hints", "from", "plugin", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L121-L141
alertot/detectem
detectem/core.py
Detector.process_from_splash
def process_from_splash(self): ''' Add softwares found in the DOM ''' for software in self._softwares_from_splash: plugin = self._plugins.get(software['name']) # Determine if it's a version or presence result try: additional_data = {'version': softwar...
python
def process_from_splash(self): ''' Add softwares found in the DOM ''' for software in self._softwares_from_splash: plugin = self._plugins.get(software['name']) # Determine if it's a version or presence result try: additional_data = {'version': softwar...
[ "def", "process_from_splash", "(", "self", ")", ":", "for", "software", "in", "self", ".", "_softwares_from_splash", ":", "plugin", "=", "self", ".", "_plugins", ".", "get", "(", "software", "[", "'name'", "]", ")", "# Determine if it's a version or presence resul...
Add softwares found in the DOM
[ "Add", "softwares", "found", "in", "the", "DOM" ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L143-L165
alertot/detectem
detectem/core.py
Detector.process_har
def process_har(self): """ Detect plugins present in the page. """ hints = [] version_plugins = self._plugins.with_version_matchers() generic_plugins = self._plugins.with_generic_matchers() for entry in self.har: for plugin in version_plugins: pm = s...
python
def process_har(self): """ Detect plugins present in the page. """ hints = [] version_plugins = self._plugins.with_version_matchers() generic_plugins = self._plugins.with_generic_matchers() for entry in self.har: for plugin in version_plugins: pm = s...
[ "def", "process_har", "(", "self", ")", ":", "hints", "=", "[", "]", "version_plugins", "=", "self", ".", "_plugins", ".", "with_version_matchers", "(", ")", "generic_plugins", "=", "self", ".", "_plugins", ".", "with_generic_matchers", "(", ")", "for", "ent...
Detect plugins present in the page.
[ "Detect", "plugins", "present", "in", "the", "page", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L197-L273
alertot/detectem
detectem/core.py
Detector.get_results
def get_results(self, metadata=False): """ Return results of the analysis. """ results_data = [] self.process_har() self.process_from_splash() for rt in sorted(self._results.get_results()): rdict = {'name': rt.name} if rt.version: rdict['...
python
def get_results(self, metadata=False): """ Return results of the analysis. """ results_data = [] self.process_har() self.process_from_splash() for rt in sorted(self._results.get_results()): rdict = {'name': rt.name} if rt.version: rdict['...
[ "def", "get_results", "(", "self", ",", "metadata", "=", "False", ")", ":", "results_data", "=", "[", "]", "self", ".", "process_har", "(", ")", "self", ".", "process_from_splash", "(", ")", "for", "rt", "in", "sorted", "(", "self", ".", "_results", "....
Return results of the analysis.
[ "Return", "results", "of", "the", "analysis", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L275-L295
alertot/detectem
detectem/plugin.py
load_plugins
def load_plugins(): """ Return the list of plugin instances. """ loader = _PluginLoader() for pkg in PLUGIN_PACKAGES: loader.load_plugins(pkg) return loader.plugins
python
def load_plugins(): """ Return the list of plugin instances. """ loader = _PluginLoader() for pkg in PLUGIN_PACKAGES: loader.load_plugins(pkg) return loader.plugins
[ "def", "load_plugins", "(", ")", ":", "loader", "=", "_PluginLoader", "(", ")", "for", "pkg", "in", "PLUGIN_PACKAGES", ":", "loader", ".", "load_plugins", "(", "pkg", ")", "return", "loader", ".", "plugins" ]
Return the list of plugin instances.
[ "Return", "the", "list", "of", "plugin", "instances", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L158-L165
alertot/detectem
detectem/plugin.py
_PluginLoader._get_plugin_module_paths
def _get_plugin_module_paths(self, plugin_dir): ''' Return a list of every module in `plugin_dir`. ''' filepaths = [ fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True) if not fp.endswith('__init__.py') ] rel_paths = [re.sub(plugin_dir.rstrip('...
python
def _get_plugin_module_paths(self, plugin_dir): ''' Return a list of every module in `plugin_dir`. ''' filepaths = [ fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True) if not fp.endswith('__init__.py') ] rel_paths = [re.sub(plugin_dir.rstrip('...
[ "def", "_get_plugin_module_paths", "(", "self", ",", "plugin_dir", ")", ":", "filepaths", "=", "[", "fp", "for", "fp", "in", "glob", ".", "glob", "(", "'{}/**/*.py'", ".", "format", "(", "plugin_dir", ")", ",", "recursive", "=", "True", ")", "if", "not",...
Return a list of every module in `plugin_dir`.
[ "Return", "a", "list", "of", "every", "module", "in", "plugin_dir", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L75-L84
alertot/detectem
detectem/plugin.py
_PluginLoader._is_plugin_ok
def _is_plugin_ok(self, instance): ''' Return `True` if: 1. Plugin meets plugin interface. 2. Is not already registered in the plugin collection. 3. Have accepted tags. Otherwise, return `False` and log warnings. ''' try: verifyObject(IPlugin, instan...
python
def _is_plugin_ok(self, instance): ''' Return `True` if: 1. Plugin meets plugin interface. 2. Is not already registered in the plugin collection. 3. Have accepted tags. Otherwise, return `False` and log warnings. ''' try: verifyObject(IPlugin, instan...
[ "def", "_is_plugin_ok", "(", "self", ",", "instance", ")", ":", "try", ":", "verifyObject", "(", "IPlugin", ",", "instance", ")", "except", "BrokenImplementation", ":", "logger", ".", "warning", "(", "\"Plugin '%(name)s' doesn't provide the plugin interface\"", ",", ...
Return `True` if: 1. Plugin meets plugin interface. 2. Is not already registered in the plugin collection. 3. Have accepted tags. Otherwise, return `False` and log warnings.
[ "Return", "True", "if", ":", "1", ".", "Plugin", "meets", "plugin", "interface", ".", "2", ".", "Is", "not", "already", "registered", "in", "the", "plugin", "collection", ".", "3", ".", "Have", "accepted", "tags", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L86-L123
alertot/detectem
detectem/plugin.py
_PluginLoader.load_plugins
def load_plugins(self, plugins_package): ''' Load plugins from `plugins_package` module. ''' try: # Resolve directory in the filesystem plugin_dir = find_spec(plugins_package).submodule_search_locations[0] except ImportError: logger.error( "Cou...
python
def load_plugins(self, plugins_package): ''' Load plugins from `plugins_package` module. ''' try: # Resolve directory in the filesystem plugin_dir = find_spec(plugins_package).submodule_search_locations[0] except ImportError: logger.error( "Cou...
[ "def", "load_plugins", "(", "self", ",", "plugins_package", ")", ":", "try", ":", "# Resolve directory in the filesystem", "plugin_dir", "=", "find_spec", "(", "plugins_package", ")", ".", "submodule_search_locations", "[", "0", "]", "except", "ImportError", ":", "l...
Load plugins from `plugins_package` module.
[ "Load", "plugins", "from", "plugins_package", "module", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L125-L155
alertot/detectem
detectem/matchers.py
extract_named_group
def extract_named_group(text, named_group, matchers, return_presence=False): ''' Return ``named_group`` match from ``text`` reached by using a matcher from ``matchers``. It also supports matching without a ``named_group`` in a matcher, which sets ``presence=True``. ``presence`` is ...
python
def extract_named_group(text, named_group, matchers, return_presence=False): ''' Return ``named_group`` match from ``text`` reached by using a matcher from ``matchers``. It also supports matching without a ``named_group`` in a matcher, which sets ``presence=True``. ``presence`` is ...
[ "def", "extract_named_group", "(", "text", ",", "named_group", ",", "matchers", ",", "return_presence", "=", "False", ")", ":", "presence", "=", "False", "for", "matcher", "in", "matchers", ":", "if", "isinstance", "(", "matcher", ",", "str", ")", ":", "v"...
Return ``named_group`` match from ``text`` reached by using a matcher from ``matchers``. It also supports matching without a ``named_group`` in a matcher, which sets ``presence=True``. ``presence`` is only returned if ``return_presence=True``.
[ "Return", "named_group", "match", "from", "text", "reached", "by", "using", "a", "matcher", "from", "matchers", "." ]
train
https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/matchers.py#L12-L48
jmcarp/robobrowser
robobrowser/browser.py
RoboState.parsed
def parsed(self): """Lazily parse response content, using HTML parser specified by the browser. """ return BeautifulSoup( self.response.content, features=self.browser.parser, )
python
def parsed(self): """Lazily parse response content, using HTML parser specified by the browser. """ return BeautifulSoup( self.response.content, features=self.browser.parser, )
[ "def", "parsed", "(", "self", ")", ":", "return", "BeautifulSoup", "(", "self", ".", "response", ".", "content", ",", "features", "=", "self", ".", "browser", ".", "parser", ",", ")" ]
Lazily parse response content, using HTML parser specified by the browser.
[ "Lazily", "parse", "response", "content", "using", "HTML", "parser", "specified", "by", "the", "browser", "." ]
train
https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L34-L41
jmcarp/robobrowser
robobrowser/browser.py
RoboBrowser._build_send_args
def _build_send_args(self, **kwargs): """Merge optional arguments with defaults. :param kwargs: Keyword arguments to `Session::send` """ out = {} out.update(self._default_send_args) out.update(kwargs) return out
python
def _build_send_args(self, **kwargs): """Merge optional arguments with defaults. :param kwargs: Keyword arguments to `Session::send` """ out = {} out.update(self._default_send_args) out.update(kwargs) return out
[ "def", "_build_send_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "out", "=", "{", "}", "out", ".", "update", "(", "self", ".", "_default_send_args", ")", "out", ".", "update", "(", "kwargs", ")", "return", "out" ]
Merge optional arguments with defaults. :param kwargs: Keyword arguments to `Session::send`
[ "Merge", "optional", "arguments", "with", "defaults", "." ]
train
https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L186-L195
jmcarp/robobrowser
robobrowser/browser.py
RoboBrowser.open
def open(self, url, method='get', **kwargs): """Open a URL. :param str url: URL to open :param str method: Optional method; defaults to `'get'` :param kwargs: Keyword arguments to `Session::request` """ response = self.session.request(method, url, **self._build_send_arg...
python
def open(self, url, method='get', **kwargs): """Open a URL. :param str url: URL to open :param str method: Optional method; defaults to `'get'` :param kwargs: Keyword arguments to `Session::request` """ response = self.session.request(method, url, **self._build_send_arg...
[ "def", "open", "(", "self", ",", "url", ",", "method", "=", "'get'", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "session", ".", "request", "(", "method", ",", "url", ",", "*", "*", "self", ".", "_build_send_args", "(", "*", ...
Open a URL. :param str url: URL to open :param str method: Optional method; defaults to `'get'` :param kwargs: Keyword arguments to `Session::request`
[ "Open", "a", "URL", "." ]
train
https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L197-L206
jmcarp/robobrowser
robobrowser/browser.py
RoboBrowser._update_state
def _update_state(self, response): """Update the state of the browser. Create a new state object, and append to or overwrite the browser's state history. :param requests.MockResponse: New response object """ # Clear trailing states self._states = self._states[:self._cur...
python
def _update_state(self, response): """Update the state of the browser. Create a new state object, and append to or overwrite the browser's state history. :param requests.MockResponse: New response object """ # Clear trailing states self._states = self._states[:self._cur...
[ "def", "_update_state", "(", "self", ",", "response", ")", ":", "# Clear trailing states", "self", ".", "_states", "=", "self", ".", "_states", "[", ":", "self", ".", "_cursor", "+", "1", "]", "# Append new state", "state", "=", "RoboState", "(", "self", "...
Update the state of the browser. Create a new state object, and append to or overwrite the browser's state history. :param requests.MockResponse: New response object
[ "Update", "the", "state", "of", "the", "browser", ".", "Create", "a", "new", "state", "object", "and", "append", "to", "or", "overwrite", "the", "browser", "s", "state", "history", "." ]
train
https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L208-L228