repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/remove_duplicate_files.py
deduplicate
def deduplicate(directories: List[str], recursive: bool, dummy_run: bool) -> None: """ De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subd...
python
def deduplicate(directories: List[str], recursive: bool, dummy_run: bool) -> None: """ De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subd...
[ "def", "deduplicate", "(", "directories", ":", "List", "[", "str", "]", ",", "recursive", ":", "bool", ",", "dummy_run", ":", "bool", ")", "->", "None", ":", "# -------------------------------------------------------------------------", "# Catalogue files by their size", ...
De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_run: say what it'll do, but don't do it
[ "De", "-", "duplicate", "files", "within", "one", "or", "more", "directories", ".", "Remove", "files", "that", "are", "identical", "to", "ones", "already", "considered", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/remove_duplicate_files.py#L53-L186
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/remove_duplicate_files.py
main
def main() -> None: """ Command-line processor. See ``--help`` for details. """ parser = ArgumentParser( description="Remove duplicate files" ) parser.add_argument( "directory", nargs="+", help="Files and/or directories to check and remove duplicates from." ) pars...
python
def main() -> None: """ Command-line processor. See ``--help`` for details. """ parser = ArgumentParser( description="Remove duplicate files" ) parser.add_argument( "directory", nargs="+", help="Files and/or directories to check and remove duplicates from." ) pars...
[ "def", "main", "(", ")", "->", "None", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"Remove duplicate files\"", ")", "parser", ".", "add_argument", "(", "\"directory\"", ",", "nargs", "=", "\"+\"", ",", "help", "=", "\"Files and/or directorie...
Command-line processor. See ``--help`` for details.
[ "Command", "-", "line", "processor", ".", "See", "--", "help", "for", "details", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/remove_duplicate_files.py#L189-L231
RudolfCardinal/pythonlib
cardinal_pythonlib/django/fields/helpers.py
valid_choice
def valid_choice(strvalue: str, choices: Iterable[Tuple[str, str]]) -> bool: """ Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/t...
python
def valid_choice(strvalue: str, choices: Iterable[Tuple[str, str]]) -> bool: """ Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/t...
[ "def", "valid_choice", "(", "strvalue", ":", "str", ",", "choices", ":", "Iterable", "[", "Tuple", "[", "str", ",", "str", "]", "]", ")", "->", "bool", ":", "return", "strvalue", "in", "[", "str", "(", "x", "[", "0", "]", ")", "for", "x", "in", ...
Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/topics/http/urls/) but Python is happy with a string-to-integer-PK lookup, e.g. ....
[ "Checks", "that", "value", "is", "one", "of", "the", "valid", "option", "in", "choices", "where", "choices", "is", "a", "list", "/", "tuple", "of", "2", "-", "tuples", "(", "option", "description", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/helpers.py#L36-L53
RudolfCardinal/pythonlib
cardinal_pythonlib/django/fields/helpers.py
choice_explanation
def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str: """ Returns the explanation associated with a Django choice tuple-list. """ for k, v in choices: if k == value: return v return ''
python
def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str: """ Returns the explanation associated with a Django choice tuple-list. """ for k, v in choices: if k == value: return v return ''
[ "def", "choice_explanation", "(", "value", ":", "str", ",", "choices", ":", "Iterable", "[", "Tuple", "[", "str", ",", "str", "]", "]", ")", "->", "str", ":", "for", "k", ",", "v", "in", "choices", ":", "if", "k", "==", "value", ":", "return", "v...
Returns the explanation associated with a Django choice tuple-list.
[ "Returns", "the", "explanation", "associated", "with", "a", "Django", "choice", "tuple", "-", "list", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/helpers.py#L56-L63
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
tee
def tee(infile: IO, *files: IO) -> Thread: r""" Print the file-like object ``infile`` to the file-like object(s) ``files`` in a separate thread. Starts and returns that thread. The type (text, binary) must MATCH across all files. From https://stackoverflow.com/questions/4984428/p...
python
def tee(infile: IO, *files: IO) -> Thread: r""" Print the file-like object ``infile`` to the file-like object(s) ``files`` in a separate thread. Starts and returns that thread. The type (text, binary) must MATCH across all files. From https://stackoverflow.com/questions/4984428/p...
[ "def", "tee", "(", "infile", ":", "IO", ",", "*", "files", ":", "IO", ")", "->", "Thread", ":", "# noqa", "def", "fanout", "(", "_infile", ":", "IO", ",", "*", "_files", ":", "IO", ")", ":", "for", "line", "in", "iter", "(", "_infile", ".", "re...
r""" Print the file-like object ``infile`` to the file-like object(s) ``files`` in a separate thread. Starts and returns that thread. The type (text, binary) must MATCH across all files. From https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-a...
[ "r", "Print", "the", "file", "-", "like", "object", "infile", "to", "the", "file", "-", "like", "object", "(", "s", ")", "files", "in", "a", "separate", "thread", ".", "Starts", "and", "returns", "that", "thread", ".", "The", "type", "(", "text", "bi...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L82-L145
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
teed_call
def teed_call(cmd_args, stdout_targets: List[TextIO] = None, stderr_targets: List[TextIO] = None, encoding: str = sys.getdefaultencoding(), **kwargs): """ Runs a command and captures its output via :func:`tee` to one or more destinations. The output i...
python
def teed_call(cmd_args, stdout_targets: List[TextIO] = None, stderr_targets: List[TextIO] = None, encoding: str = sys.getdefaultencoding(), **kwargs): """ Runs a command and captures its output via :func:`tee` to one or more destinations. The output i...
[ "def", "teed_call", "(", "cmd_args", ",", "stdout_targets", ":", "List", "[", "TextIO", "]", "=", "None", ",", "stderr_targets", ":", "List", "[", "TextIO", "]", "=", "None", ",", "encoding", ":", "str", "=", "sys", ".", "getdefaultencoding", "(", ")", ...
Runs a command and captures its output via :func:`tee` to one or more destinations. The output is always captured (otherwise we would lose control of the output and ability to ``tee`` it); if no destination is specified, we add a null handler. We insist on ``TextIO`` output files to match ``sys.stdo...
[ "Runs", "a", "command", "and", "captures", "its", "output", "via", ":", "func", ":", "tee", "to", "one", "or", "more", "destinations", ".", "The", "output", "is", "always", "captured", "(", "otherwise", "we", "would", "lose", "control", "of", "the", "out...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L148-L190
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
tee_log
def tee_log(tee_file: TextIO, loglevel: int) -> None: """ Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream """ handler = get_monochrome_handler(stream=...
python
def tee_log(tee_file: TextIO, loglevel: int) -> None: """ Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream """ handler = get_monochrome_handler(stream=...
[ "def", "tee_log", "(", "tee_file", ":", "TextIO", ",", "loglevel", ":", "int", ")", "->", "None", ":", "handler", "=", "get_monochrome_handler", "(", "stream", "=", "tee_file", ")", "handler", ".", "setLevel", "(", "loglevel", ")", "rootlogger", "=", "logg...
Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream
[ "Context", "manager", "to", "add", "a", "file", "output", "stream", "to", "our", "logging", "system", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L290-L315
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
TeeContextManager.write
def write(self, message: str) -> None: """ To act as a file. """ self.underlying_stream.write(message) self.file.write(message)
python
def write(self, message: str) -> None: """ To act as a file. """ self.underlying_stream.write(message) self.file.write(message)
[ "def", "write", "(", "self", ",", "message", ":", "str", ")", "->", "None", ":", "self", ".", "underlying_stream", ".", "write", "(", "message", ")", "self", ".", "file", ".", "write", "(", "message", ")" ]
To act as a file.
[ "To", "act", "as", "a", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L257-L262
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
TeeContextManager.flush
def flush(self) -> None: """ To act as a file. """ self.underlying_stream.flush() self.file.flush() os.fsync(self.file.fileno())
python
def flush(self) -> None: """ To act as a file. """ self.underlying_stream.flush() self.file.flush() os.fsync(self.file.fileno())
[ "def", "flush", "(", "self", ")", "->", "None", ":", "self", ".", "underlying_stream", ".", "flush", "(", ")", "self", ".", "file", ".", "flush", "(", ")", "os", ".", "fsync", "(", "self", ".", "file", ".", "fileno", "(", ")", ")" ]
To act as a file.
[ "To", "act", "as", "a", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L264-L270
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
TeeContextManager.close
def close(self) -> None: """ To act as a file. """ if self.underlying_stream: if self.using_stdout: sys.stdout = self.underlying_stream else: sys.stderr = self.underlying_stream self.underlying_stream = None if s...
python
def close(self) -> None: """ To act as a file. """ if self.underlying_stream: if self.using_stdout: sys.stdout = self.underlying_stream else: sys.stderr = self.underlying_stream self.underlying_stream = None if s...
[ "def", "close", "(", "self", ")", "->", "None", ":", "if", "self", ".", "underlying_stream", ":", "if", "self", ".", "using_stdout", ":", "sys", ".", "stdout", "=", "self", ".", "underlying_stream", "else", ":", "sys", ".", "stderr", "=", "self", ".", ...
To act as a file.
[ "To", "act", "as", "a", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L272-L286
davenquinn/Attitude
attitude/error/bootstrap.py
bootstrap
def bootstrap(array): """ Provides a bootstrap resampling of an array. Provides another statistical method to estimate the variance of a dataset. For a `PCA` object in this library, it should be applied to `Orientation.array` method. """ reg_func = lambda a: N.linalg.svd(a,full_matrices=Fal...
python
def bootstrap(array): """ Provides a bootstrap resampling of an array. Provides another statistical method to estimate the variance of a dataset. For a `PCA` object in this library, it should be applied to `Orientation.array` method. """ reg_func = lambda a: N.linalg.svd(a,full_matrices=Fal...
[ "def", "bootstrap", "(", "array", ")", ":", "reg_func", "=", "lambda", "a", ":", "N", ".", "linalg", ".", "svd", "(", "a", ",", "full_matrices", "=", "False", ")", "[", "2", "]", "[", "2", "]", "beta_boots", "=", "bootstrap", "(", "array", ",", "...
Provides a bootstrap resampling of an array. Provides another statistical method to estimate the variance of a dataset. For a `PCA` object in this library, it should be applied to `Orientation.array` method.
[ "Provides", "a", "bootstrap", "resampling", "of", "an", "array", ".", "Provides", "another", "statistical", "method", "to", "estimate", "the", "variance", "of", "a", "dataset", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/bootstrap.py#L6-L16
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
sql_string_literal
def sql_string_literal(text: str) -> str: """ Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'" """ # ANSI SQL: http://www.contrib.andrew.cmu.edu/~shad...
python
def sql_string_literal(text: str) -> str: """ Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'" """ # ANSI SQL: http://www.contrib.andrew.cmu.edu/~shad...
[ "def", "sql_string_literal", "(", "text", ":", "str", ")", "->", "str", ":", "# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt", "# <character string literal>", "return", "SQUOTE", "+", "text", ".", "replace", "(", "SQUOTE", ",", "DOUBLE_SQUOTE", ")",...
Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'"
[ "Transforms", "text", "into", "its", "ANSI", "SQL", "-", "quoted", "version", "e", ".", "g", ".", "(", "in", "Python", "repr", "()", "format", ")", ":" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L42-L54
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
sql_datetime_literal
def sql_datetime_literal(dt: DateTimeLikeType, subsecond: bool = False) -> str: """ Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'...
python
def sql_datetime_literal(dt: DateTimeLikeType, subsecond: bool = False) -> str: """ Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'...
[ "def", "sql_datetime_literal", "(", "dt", ":", "DateTimeLikeType", ",", "subsecond", ":", "bool", "=", "False", ")", "->", "str", ":", "# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt", "# <timestamp string>", "# ... the subsecond part is non-ANSI", "fmt",...
Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'2000-12-31 23:59:59.123456'`` or similar.
[ "Transforms", "a", "Python", "object", "that", "is", "of", "duck", "type", "datetime", ".", "datetime", "into", "an", "ANSI", "SQL", "literal", "string", "like", "2000", "-", "12", "-", "31", "23", ":", "59", ":", "59", "or", "if", "subsecond", "=", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L70-L82
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
sql_comment
def sql_comment(comment: str) -> str: """ Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``. """ """Using -- as a comment marker is ANSI SQL.""" if not comment: return "" return "\n".join("-- {}".format(x) for x in comment.splitlines())
python
def sql_comment(comment: str) -> str: """ Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``. """ """Using -- as a comment marker is ANSI SQL.""" if not comment: return "" return "\n".join("-- {}".format(x) for x in comment.splitlines())
[ "def", "sql_comment", "(", "comment", ":", "str", ")", "->", "str", ":", "\"\"\"Using -- as a comment marker is ANSI SQL.\"\"\"", "if", "not", "comment", ":", "return", "\"\"", "return", "\"\\n\"", ".", "join", "(", "\"-- {}\"", ".", "format", "(", "x", ")", "...
Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``.
[ "Transforms", "a", "single", "-", "or", "multi", "-", "line", "string", "into", "an", "ANSI", "SQL", "comment", "prefixed", "by", "--", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L85-L93
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
sql_dequote_string
def sql_dequote_string(s: str) -> str: """ Reverses :func:`sql_quote_string`. """ if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE: raise ValueError("Not an SQL string literal") s = s[1:-1] # strip off the surrounding quotes return s.replace(DOUBLE_SQUOTE, SQUOTE)
python
def sql_dequote_string(s: str) -> str: """ Reverses :func:`sql_quote_string`. """ if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE: raise ValueError("Not an SQL string literal") s = s[1:-1] # strip off the surrounding quotes return s.replace(DOUBLE_SQUOTE, SQUOTE)
[ "def", "sql_dequote_string", "(", "s", ":", "str", ")", "->", "str", ":", "if", "len", "(", "s", ")", "<", "2", "or", "s", "[", "0", "]", "!=", "SQUOTE", "or", "s", "[", "-", "1", "]", "!=", "SQUOTE", ":", "raise", "ValueError", "(", "\"Not an ...
Reverses :func:`sql_quote_string`.
[ "Reverses", ":", "func", ":", "sql_quote_string", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L100-L107
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
gen_items_from_sql_csv
def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]: """ Splits a comma-separated list of quoted SQL values, with ``'`` as the quote character. Allows escaping of the quote character by doubling it. Returns the quotes (and escaped quotes) as part of the result. Allows newlines etc. with...
python
def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]: """ Splits a comma-separated list of quoted SQL values, with ``'`` as the quote character. Allows escaping of the quote character by doubling it. Returns the quotes (and escaped quotes) as part of the result. Allows newlines etc. with...
[ "def", "gen_items_from_sql_csv", "(", "s", ":", "str", ")", "->", "Generator", "[", "str", ",", "None", ",", "None", "]", ":", "# csv.reader will not both process the quotes and return the quotes;", "# we need them to distinguish e.g. NULL from 'NULL'.", "# log.warning('gen_ite...
Splits a comma-separated list of quoted SQL values, with ``'`` as the quote character. Allows escaping of the quote character by doubling it. Returns the quotes (and escaped quotes) as part of the result. Allows newlines etc. within the string passed.
[ "Splits", "a", "comma", "-", "separated", "list", "of", "quoted", "SQL", "values", "with", "as", "the", "quote", "character", ".", "Allows", "escaping", "of", "the", "quote", "character", "by", "doubling", "it", ".", "Returns", "the", "quotes", "(", "and",...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L114-L153
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
get_case_insensitive_dict_key
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]: """ Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one). """ for key in d.keys(): if k.lower() == key.lower(): return ...
python
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]: """ Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one). """ for key in d.keys(): if k.lower() == key.lower(): return ...
[ "def", "get_case_insensitive_dict_key", "(", "d", ":", "Dict", ",", "k", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "for", "key", "in", "d", ".", "keys", "(", ")", ":", "if", "k", ".", "lower", "(", ")", "==", "key", ".", "lower", ...
Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one).
[ "Within", "the", "dictionary", "d", "find", "a", "key", "that", "matches", "(", "in", "case", "-", "insensitive", "fashion", ")", "the", "key", "k", "and", "return", "it", "(", "or", "None", "if", "there", "isn", "t", "one", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L36-L44
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
merge_two_dicts
def merge_two_dicts(x: Dict, y: Dict) -> Dict: """ Given two dicts, merge them into a new dict as a shallow copy, e.g. .. code-block:: python z = merge_two_dicts(x, y) If you can guarantee Python 3.5, then a simpler syntax is: .. code-block:: python z = {**x, **y} See http:...
python
def merge_two_dicts(x: Dict, y: Dict) -> Dict: """ Given two dicts, merge them into a new dict as a shallow copy, e.g. .. code-block:: python z = merge_two_dicts(x, y) If you can guarantee Python 3.5, then a simpler syntax is: .. code-block:: python z = {**x, **y} See http:...
[ "def", "merge_two_dicts", "(", "x", ":", "Dict", ",", "y", ":", "Dict", ")", "->", "Dict", ":", "z", "=", "x", ".", "copy", "(", ")", "z", ".", "update", "(", "y", ")", "return", "z" ]
Given two dicts, merge them into a new dict as a shallow copy, e.g. .. code-block:: python z = merge_two_dicts(x, y) If you can guarantee Python 3.5, then a simpler syntax is: .. code-block:: python z = {**x, **y} See http://stackoverflow.com/questions/38987.
[ "Given", "two", "dicts", "merge", "them", "into", "a", "new", "dict", "as", "a", "shallow", "copy", "e", ".", "g", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L60-L78
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
rename_key
def rename_key(d: Dict[str, Any], old: str, new: str) -> None: """ Rename a key in dictionary ``d`` from ``old`` to ``new``, in place. """ d[new] = d.pop(old)
python
def rename_key(d: Dict[str, Any], old: str, new: str) -> None: """ Rename a key in dictionary ``d`` from ``old`` to ``new``, in place. """ d[new] = d.pop(old)
[ "def", "rename_key", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "old", ":", "str", ",", "new", ":", "str", ")", "->", "None", ":", "d", "[", "new", "]", "=", "d", ".", "pop", "(", "old", ")" ]
Rename a key in dictionary ``d`` from ``old`` to ``new``, in place.
[ "Rename", "a", "key", "in", "dictionary", "d", "from", "old", "to", "new", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L81-L85
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
rename_keys
def rename_keys(d: Dict[str, Any], mapping: Dict[str, str]) -> Dict[str, Any]: """ Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: ...
python
def rename_keys(d: Dict[str, Any], mapping: Dict[str, str]) -> Dict[str, Any]: """ Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: ...
[ "def", "rename_keys", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "mapping", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "result", "=", "{", "}", "# type: Dict[str, Any]", "for", "k"...
Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: a new dictionary Keys that are not in ``mapping`` are left unchanged. The i...
[ "Returns", "a", "copy", "of", "the", "dictionary", "d", "with", "its", "keys", "renamed", "according", "to", "mapping", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L88-L108
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
rename_keys_in_dict
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None: """ Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See h...
python
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None: """ Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See h...
[ "def", "rename_keys_in_dict", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "renames", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "None", ":", "# noqa", "for", "old_key", ",", "new_key", "in", "renames", ".", "items", "(", ")",...
Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary.
[ "Renames", "IN", "PLACE", "the", "keys", "in", "d", "according", "to", "the", "mapping", "in", "renames", ".", "Args", ":", "d", ":", "a", "dictionary", "to", "modify", "renames", ":", "a", "dictionary", "of", "the", "format", "{", "old_key_name", ":", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L111-L131
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
prefix_dict_keys
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]: """ Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys. """ result = {} # type: Dict[str, Any] for k, v in d.items(): result[prefix + k] = v return result
python
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]: """ Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys. """ result = {} # type: Dict[str, Any] for k, v in d.items(): result[prefix + k] = v return result
[ "def", "prefix_dict_keys", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "prefix", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "result", "=", "{", "}", "# type: Dict[str, Any]", "for", "k", ",", "v", "in", "d", "."...
Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys.
[ "Returns", "a", "dictionary", "that", "s", "a", "copy", "of", "as", "d", "but", "with", "prefix", "prepended", "to", "its", "keys", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L134-L142
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
reversedict
def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping. """ return {v: k for k, v in d.items()}
python
def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping. """ return {v: k for k, v in d.items()}
[ "def", "reversedict", "(", "d", ":", "Dict", "[", "Any", ",", "Any", "]", ")", "->", "Dict", "[", "Any", ",", "Any", "]", ":", "return", "{", "v", ":", "k", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", "}" ]
Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping.
[ "Takes", "a", "k", "-", ">", "v", "mapping", "and", "returns", "a", "v", "-", ">", "k", "mapping", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L145-L149
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
set_null_values_in_dict
def set_null_values_in_dict(d: Dict[str, Any], null_literals: List[Any]) -> None: """ Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``. """ if not null_literals: return # DO NOT add/delete values to/from a dictionary during ...
python
def set_null_values_in_dict(d: Dict[str, Any], null_literals: List[Any]) -> None: """ Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``. """ if not null_literals: return # DO NOT add/delete values to/from a dictionary during ...
[ "def", "set_null_values_in_dict", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "null_literals", ":", "List", "[", "Any", "]", ")", "->", "None", ":", "if", "not", "null_literals", ":", "return", "# DO NOT add/delete values to/from a dictionary during...
Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``.
[ "Within", "d", "(", "in", "place", ")", "replace", "any", "values", "found", "in", "null_literals", "with", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L152-L167
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
map_keys_to_values
def map_keys_to_values(l: List[Any], d: Dict[Any, Any], default: Any = None, raise_if_missing: bool = False, omit_if_missing: bool = False) -> List[Any]: """ The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l...
python
def map_keys_to_values(l: List[Any], d: Dict[Any, Any], default: Any = None, raise_if_missing: bool = False, omit_if_missing: bool = False) -> List[Any]: """ The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l...
[ "def", "map_keys_to_values", "(", "l", ":", "List", "[", "Any", "]", ",", "d", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "default", ":", "Any", "=", "None", ",", "raise_if_missing", ":", "bool", "=", "False", ",", "omit_if_missing", ":", "bool",...
The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l``, and return a list of corresponding values -- substituting ``default`` if any are missing, or raising :exc:`KeyError` if ``raise_if_missing`` is true, or omitting the entry if ``omit_if_missing`` i...
[ "The", "d", "dictionary", "contains", "a", "key", "-", ">", "value", "mapping", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L170-L188
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
dict_diff
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any], deleted_value: Any = None) -> Dict[Any, Any]: """ Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to us...
python
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any], deleted_value: Any = None) -> Dict[Any, Any]: """ Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to us...
[ "def", "dict_diff", "(", "d1", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "d2", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "deleted_value", ":", "Any", "=", "None", ")", "->", "Dict", "[", "Any", ",", "Any", "]", ":", "changes", "=", ...
Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to use for deleted keys; see below Returns: dict: a dictionary of the format ``{k: v}`` where the ``k``/``v`` pairs ...
[ "Returns", "a", "representation", "of", "the", "changes", "that", "need", "to", "be", "made", "to", "d1", "to", "create", "d2", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L191-L215
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
delete_keys
def delete_keys(d: Dict[Any, Any], keys_to_delete: List[Any], keys_to_keep: List[Any]) -> None: """ Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are d...
python
def delete_keys(d: Dict[Any, Any], keys_to_delete: List[Any], keys_to_keep: List[Any]) -> None: """ Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are d...
[ "def", "delete_keys", "(", "d", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "keys_to_delete", ":", "List", "[", "Any", "]", ",", "keys_to_keep", ":", "List", "[", "Any", "]", ")", "->", "None", ":", "for", "k", "in", "keys_to_delete", ":", "if",...
Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are deleted... keys_to_keep: ... unless they are present in this list.
[ "Deletes", "keys", "from", "a", "dictionary", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L218-L234
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
StringListType.process_bind_param
def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
python
def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
[ "def", "process_bind_param", "(", "self", ",", "value", ":", "Optional", "[", "List", "[", "str", "]", "]", ",", "dialect", ":", "Dialect", ")", "->", "str", ":", "retval", "=", "self", ".", "_strlist_to_dbstr", "(", "value", ")", "return", "retval" ]
Convert things on the way from Python to the database.
[ "Convert", "things", "on", "the", "way", "from", "Python", "to", "the", "database", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L208-L212
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
StringListType.process_result_value
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_strlist(value) return retval
python
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_strlist(value) return retval
[ "def", "process_result_value", "(", "self", ",", "value", ":", "Optional", "[", "str", "]", ",", "dialect", ":", "Dialect", ")", "->", "List", "[", "str", "]", ":", "retval", "=", "self", ".", "_dbstr_to_strlist", "(", "value", ")", "return", "retval" ]
Convert things on the way from the database to Python.
[ "Convert", "things", "on", "the", "way", "from", "the", "database", "to", "Python", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L223-L227
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
IntListType.process_literal_param
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
python
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
[ "def", "process_literal_param", "(", "self", ",", "value", ":", "Optional", "[", "List", "[", "int", "]", "]", ",", "dialect", ":", "Dialect", ")", "->", "str", ":", "retval", "=", "self", ".", "_intlist_to_dbstr", "(", "value", ")", "return", "retval" ]
Convert things on the way from Python to the database.
[ "Convert", "things", "on", "the", "way", "from", "Python", "to", "the", "database", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L271-L275
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
IntListType.process_result_value
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[int]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_intlist(value) return retval
python
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[int]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_intlist(value) return retval
[ "def", "process_result_value", "(", "self", ",", "value", ":", "Optional", "[", "str", "]", ",", "dialect", ":", "Dialect", ")", "->", "List", "[", "int", "]", ":", "retval", "=", "self", ".", "_dbstr_to_intlist", "(", "value", ")", "return", "retval" ]
Convert things on the way from the database to Python.
[ "Convert", "things", "on", "the", "way", "from", "the", "database", "to", "Python", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L277-L281
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.reset
def reset(self) -> None: """ Reset the timers. """ self._overallstart = get_now_utc_pendulum() self._starttimes.clear() self._totaldurations.clear() self._count.clear() self._stack.clear()
python
def reset(self) -> None: """ Reset the timers. """ self._overallstart = get_now_utc_pendulum() self._starttimes.clear() self._totaldurations.clear() self._count.clear() self._stack.clear()
[ "def", "reset", "(", "self", ")", "->", "None", ":", "self", ".", "_overallstart", "=", "get_now_utc_pendulum", "(", ")", "self", ".", "_starttimes", ".", "clear", "(", ")", "self", ".", "_totaldurations", ".", "clear", "(", ")", "self", ".", "_count", ...
Reset the timers.
[ "Reset", "the", "timers", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L58-L66
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.set_timing
def set_timing(self, timing: bool, reset: bool = False) -> None: """ Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers? """ self._timing = timing if reset: ...
python
def set_timing(self, timing: bool, reset: bool = False) -> None: """ Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers? """ self._timing = timing if reset: ...
[ "def", "set_timing", "(", "self", ",", "timing", ":", "bool", ",", "reset", ":", "bool", "=", "False", ")", "->", "None", ":", "self", ".", "_timing", "=", "timing", "if", "reset", ":", "self", ".", "reset", "(", ")" ]
Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers?
[ "Manually", "set", "the", "timing", "parameter", "and", "optionally", "reset", "the", "timers", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L68-L79
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.start
def start(self, name: str, increment_count: bool = True) -> None: """ Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer """ if not self._timing: return now = get_now_utc_pendu...
python
def start(self, name: str, increment_count: bool = True) -> None: """ Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer """ if not self._timing: return now = get_now_utc_pendu...
[ "def", "start", "(", "self", ",", "name", ":", "str", ",", "increment_count", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "not", "self", ".", "_timing", ":", "return", "now", "=", "get_now_utc_pendulum", "(", ")", "# If we were already timing s...
Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer
[ "Start", "a", "named", "timer", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L81-L106
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.stop
def stop(self, name: str) -> None: """ Stop a named timer. Args: name: timer to stop """ if not self._timing: return now = get_now_utc_pendulum() # Validity check if not self._stack: raise AssertionError("MultiTimer.st...
python
def stop(self, name: str) -> None: """ Stop a named timer. Args: name: timer to stop """ if not self._timing: return now = get_now_utc_pendulum() # Validity check if not self._stack: raise AssertionError("MultiTimer.st...
[ "def", "stop", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "if", "not", "self", ".", "_timing", ":", "return", "now", "=", "get_now_utc_pendulum", "(", ")", "# Validity check", "if", "not", "self", ".", "_stack", ":", "raise", "Assert...
Stop a named timer. Args: name: timer to stop
[ "Stop", "a", "named", "timer", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L108-L135
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.report
def report(self) -> None: """ Finish and report to the log. """ while self._stack: self.stop(self._stack[-1]) now = get_now_utc_pendulum() grand_total = datetime.timedelta() overall_duration = now - self._overallstart for name, duration in self...
python
def report(self) -> None: """ Finish and report to the log. """ while self._stack: self.stop(self._stack[-1]) now = get_now_utc_pendulum() grand_total = datetime.timedelta() overall_duration = now - self._overallstart for name, duration in self...
[ "def", "report", "(", "self", ")", "->", "None", ":", "while", "self", ".", "_stack", ":", "self", ".", "stop", "(", "self", ".", "_stack", "[", "-", "1", "]", ")", "now", "=", "get_now_utc_pendulum", "(", ")", "grand_total", "=", "datetime", ".", ...
Finish and report to the log.
[ "Finish", "and", "report", "to", "the", "log", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L137-L179
davenquinn/Attitude
attitude/display/stereonet.py
girdle_error
def girdle_error(ax, fit, **kwargs): """ Plot an attitude measurement on an `mplstereonet` axes object. """ vertices = [] codes = [] for sheet in ('upper','lower'): err = plane_errors(fit.axes, fit.covariance_matrix, sheet=sheet) lonlat = N.array(err) lonl...
python
def girdle_error(ax, fit, **kwargs): """ Plot an attitude measurement on an `mplstereonet` axes object. """ vertices = [] codes = [] for sheet in ('upper','lower'): err = plane_errors(fit.axes, fit.covariance_matrix, sheet=sheet) lonlat = N.array(err) lonl...
[ "def", "girdle_error", "(", "ax", ",", "fit", ",", "*", "*", "kwargs", ")", ":", "vertices", "=", "[", "]", "codes", "=", "[", "]", "for", "sheet", "in", "(", "'upper'", ",", "'lower'", ")", ":", "err", "=", "plane_errors", "(", "fit", ".", "axes...
Plot an attitude measurement on an `mplstereonet` axes object.
[ "Plot", "an", "attitude", "measurement", "on", "an", "mplstereonet", "axes", "object", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/stereonet.py#L21-L39
davenquinn/Attitude
attitude/display/stereonet.py
pole_error
def pole_error(ax, fit, **kwargs): """ Plot the error to the pole to a plane on a `mplstereonet` axis object. """ ell = normal_errors(fit.axes, fit.covariance_matrix) lonlat = -N.array(ell) n = len(lonlat) codes = [Path.MOVETO] codes += [Path.LINETO]*(n-1) vertices = list(lonlat)...
python
def pole_error(ax, fit, **kwargs): """ Plot the error to the pole to a plane on a `mplstereonet` axis object. """ ell = normal_errors(fit.axes, fit.covariance_matrix) lonlat = -N.array(ell) n = len(lonlat) codes = [Path.MOVETO] codes += [Path.LINETO]*(n-1) vertices = list(lonlat)...
[ "def", "pole_error", "(", "ax", ",", "fit", ",", "*", "*", "kwargs", ")", ":", "ell", "=", "normal_errors", "(", "fit", ".", "axes", ",", "fit", ".", "covariance_matrix", ")", "lonlat", "=", "-", "N", ".", "array", "(", "ell", ")", "n", "=", "len...
Plot the error to the pole to a plane on a `mplstereonet` axis object.
[ "Plot", "the", "error", "to", "the", "pole", "to", "a", "plane", "on", "a", "mplstereonet", "axis", "object", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/stereonet.py#L41-L53
RudolfCardinal/pythonlib
cardinal_pythonlib/network.py
ping
def ping(hostname: str, timeout_s: int = 5) -> bool: """ Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful? """ if sys.platform == "win32": timeout_ms = timeout_s * 1000 ...
python
def ping(hostname: str, timeout_s: int = 5) -> bool: """ Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful? """ if sys.platform == "win32": timeout_ms = timeout_s * 1000 ...
[ "def", "ping", "(", "hostname", ":", "str", ",", "timeout_s", ":", "int", "=", "5", ")", "->", "bool", ":", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "timeout_ms", "=", "timeout_s", "*", "1000", "args", "=", "[", "\"ping\"", ",", "hostnam...
Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful?
[ "Pings", "a", "host", "using", "OS", "tools", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/network.py#L59-L92
RudolfCardinal/pythonlib
cardinal_pythonlib/network.py
download
def download(url: str, filename: str, skip_cert_verify: bool = True) -> None: """ Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check? """ log.info("Downloading from {} to {}", url, fi...
python
def download(url: str, filename: str, skip_cert_verify: bool = True) -> None: """ Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check? """ log.info("Downloading from {} to {}", url, fi...
[ "def", "download", "(", "url", ":", "str", ",", "filename", ":", "str", ",", "skip_cert_verify", ":", "bool", "=", "True", ")", "->", "None", ":", "log", ".", "info", "(", "\"Downloading from {} to {}\"", ",", "url", ",", "filename", ")", "# urllib.request...
Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check?
[ "Downloads", "a", "URL", "to", "a", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/network.py#L99-L127
RudolfCardinal/pythonlib
cardinal_pythonlib/network.py
gen_binary_files_from_urls
def gen_binary_files_from_urls( urls: Iterable[str], on_disk: bool = False, show_info: bool = True) -> Generator[BinaryIO, None, None]: """ Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that...
python
def gen_binary_files_from_urls( urls: Iterable[str], on_disk: bool = False, show_info: bool = True) -> Generator[BinaryIO, None, None]: """ Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that...
[ "def", "gen_binary_files_from_urls", "(", "urls", ":", "Iterable", "[", "str", "]", ",", "on_disk", ":", "bool", "=", "False", ",", "show_info", ":", "bool", "=", "True", ")", "->", "Generator", "[", "BinaryIO", ",", "None", ",", "None", "]", ":", "for...
Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that are on disk (permitting random access); if ``False``, yields in-memory files (which will not permit random access) show_info: show progress...
[ "Generate", "binary", "files", "from", "a", "series", "of", "URLs", "(", "one", "per", "URL", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/network.py#L134-L166
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
find_nth
def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int: """ Finds the position of *n*\ th occurrence of ``x`` in ``s``, or ``-1`` if there isn't one. - The ``n`` parameter is zero-based (i.e. 0 for the first, 1 for the second...). - If ``overlap`` is true, allows fragments to ...
python
def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int: """ Finds the position of *n*\ th occurrence of ``x`` in ``s``, or ``-1`` if there isn't one. - The ``n`` parameter is zero-based (i.e. 0 for the first, 1 for the second...). - If ``overlap`` is true, allows fragments to ...
[ "def", "find_nth", "(", "s", ":", "str", ",", "x", ":", "str", ",", "n", ":", "int", "=", "0", ",", "overlap", ":", "bool", "=", "False", ")", "->", "int", ":", "# noqa", "length_of_fragment", "=", "1", "if", "overlap", "else", "len", "(", "x", ...
Finds the position of *n*\ th occurrence of ``x`` in ``s``, or ``-1`` if there isn't one. - The ``n`` parameter is zero-based (i.e. 0 for the first, 1 for the second...). - If ``overlap`` is true, allows fragments to overlap. If not, they must be distinct. As per https://stackove...
[ "Finds", "the", "position", "of", "*", "n", "*", "\\", "th", "occurrence", "of", "x", "in", "s", "or", "-", "1", "if", "there", "isn", "t", "one", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L35-L54
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
split_string
def split_string(x: str, n: int) -> List[str]: """ Split string into chunks of length n """ # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
python
def split_string(x: str, n: int) -> List[str]: """ Split string into chunks of length n """ # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
[ "def", "split_string", "(", "x", ":", "str", ",", "n", ":", "int", ")", "->", "List", "[", "str", "]", ":", "# https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa", "return", "[", "x", "[", "i", ":", "i", "+", "n", "]", "for", ...
Split string into chunks of length n
[ "Split", "string", "into", "chunks", "of", "length", "n" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L61-L66
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
multiple_replace
def multiple_replace(text: str, rep: Dict[str, str]) -> str: """ Returns a version of ``text`` in which the keys of ``rep`` (a dict) have been replaced by their values. As per http://stackoverflow.com/questions/6116978/python-replace-multiple-strings. """ rep = dict((re.escape(k), v) for k,...
python
def multiple_replace(text: str, rep: Dict[str, str]) -> str: """ Returns a version of ``text`` in which the keys of ``rep`` (a dict) have been replaced by their values. As per http://stackoverflow.com/questions/6116978/python-replace-multiple-strings. """ rep = dict((re.escape(k), v) for k,...
[ "def", "multiple_replace", "(", "text", ":", "str", ",", "rep", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "str", ":", "rep", "=", "dict", "(", "(", "re", ".", "escape", "(", "k", ")", ",", "v", ")", "for", "k", ",", "v", "in", "r...
Returns a version of ``text`` in which the keys of ``rep`` (a dict) have been replaced by their values. As per http://stackoverflow.com/questions/6116978/python-replace-multiple-strings.
[ "Returns", "a", "version", "of", "text", "in", "which", "the", "keys", "of", "rep", "(", "a", "dict", ")", "have", "been", "replaced", "by", "their", "values", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L73-L83
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
replace_in_list
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: """ Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "ori...
python
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: """ Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "ori...
[ "def", "replace_in_list", "(", "stringlist", ":", "Iterable", "[", "str", "]", ",", "replacedict", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "List", "[", "str", "]", ":", "newlist", "=", "[", "]", "for", "fromstring", "in", "stringlist", "...
Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings
[ "Returns", "a", "list", "produced", "by", "applying", ":", "func", ":", "multiple_replace", "to", "every", "string", "in", "stringlist", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L86-L103
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
mangle_unicode_to_ascii
def mangle_unicode_to_ascii(s: Any) -> str: """ Mangle unicode to ASCII, losing accents etc. in the process. """ # http://stackoverflow.com/questions/1207457 if s is None: return "" if not isinstance(s, str): s = str(s) return ( unicodedata.normalize('NFKD', s) ...
python
def mangle_unicode_to_ascii(s: Any) -> str: """ Mangle unicode to ASCII, losing accents etc. in the process. """ # http://stackoverflow.com/questions/1207457 if s is None: return "" if not isinstance(s, str): s = str(s) return ( unicodedata.normalize('NFKD', s) ...
[ "def", "mangle_unicode_to_ascii", "(", "s", ":", "Any", ")", "->", "str", ":", "# http://stackoverflow.com/questions/1207457", "if", "s", "is", "None", ":", "return", "\"\"", "if", "not", "isinstance", "(", "s", ",", "str", ")", ":", "s", "=", "str", "(", ...
Mangle unicode to ASCII, losing accents etc. in the process.
[ "Mangle", "unicode", "to", "ASCII", "losing", "accents", "etc", ".", "in", "the", "process", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L110-L123
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
strnum
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return "{}{}{}".format(prefix, num, suffix)
python
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return "{}{}{}".format(prefix, num, suffix)
[ "def", "strnum", "(", "prefix", ":", "str", ",", "num", ":", "int", ",", "suffix", ":", "str", "=", "\"\"", ")", "->", "str", ":", "return", "\"{}{}{}\"", ".", "format", "(", "prefix", ",", "num", ",", "suffix", ")" ]
Makes a string of the format ``<prefix><number><suffix>``.
[ "Makes", "a", "string", "of", "the", "format", "<prefix", ">", "<number", ">", "<suffix", ">", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L130-L134
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
strnumlist
def strnumlist(prefix: str, numbers: List[int], suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list. """ return ["{}{}{}".format(prefix, num, suffix) for num in numbers]
python
def strnumlist(prefix: str, numbers: List[int], suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list. """ return ["{}{}{}".format(prefix, num, suffix) for num in numbers]
[ "def", "strnumlist", "(", "prefix", ":", "str", ",", "numbers", ":", "List", "[", "int", "]", ",", "suffix", ":", "str", "=", "\"\"", ")", "->", "List", "[", "str", "]", ":", "return", "[", "\"{}{}{}\"", ".", "format", "(", "prefix", ",", "num", ...
Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list.
[ "Makes", "a", "string", "of", "the", "format", "<prefix", ">", "<number", ">", "<suffix", ">", "for", "every", "number", "in", "numbers", "and", "returns", "them", "as", "a", "list", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L137-L142
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
strseq
def strseq(prefix: str, first: int, last: int, suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list. """ return [strnum(prefix, n, suffix) for n in range(first, last + 1)]
python
def strseq(prefix: str, first: int, last: int, suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list. """ return [strnum(prefix, n, suffix) for n in range(first, last + 1)]
[ "def", "strseq", "(", "prefix", ":", "str", ",", "first", ":", "int", ",", "last", ":", "int", ",", "suffix", ":", "str", "=", "\"\"", ")", "->", "List", "[", "str", "]", ":", "return", "[", "strnum", "(", "prefix", ",", "n", ",", "suffix", ")"...
Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list.
[ "Makes", "a", "string", "of", "the", "format", "<prefix", ">", "<number", ">", "<suffix", ">", "for", "every", "number", "from", "first", "to", "last", "inclusive", "and", "returns", "them", "as", "a", "list", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L145-L150
davenquinn/Attitude
attitude/display/plot/misc.py
aligned_residuals
def aligned_residuals(pca): """ Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset. """ A = pca.rotated() fig, axes = P.subplots(2,1, sharex=True, frameon=False) fig.subplots_adjus...
python
def aligned_residuals(pca): """ Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset. """ A = pca.rotated() fig, axes = P.subplots(2,1, sharex=True, frameon=False) fig.subplots_adjus...
[ "def", "aligned_residuals", "(", "pca", ")", ":", "A", "=", "pca", ".", "rotated", "(", ")", "fig", ",", "axes", "=", "P", ".", "subplots", "(", "2", ",", "1", ",", "sharex", "=", "True", ",", "frameon", "=", "False", ")", "fig", ".", "subplots_a...
Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset.
[ "Plots", "error", "components", "along", "with", "bootstrap", "resampled", "error", "surface", ".", "Provides", "another", "statistical", "method", "to", "estimate", "the", "variance", "of", "a", "dataset", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/misc.py#L6-L37
ivanprjcts/sdklib
sdklib/util/design_pattern.py
Singleton.get_instance
def get_instance(self): """ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned. """ try: return self._instance...
python
def get_instance(self): """ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned. """ try: return self._instance...
[ "def", "get_instance", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_instance", "except", "AttributeError", ":", "self", ".", "_instance", "=", "self", ".", "_decorated", "(", ")", "return", "self", ".", "_instance" ]
Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned.
[ "Returns", "the", "singleton", "instance", ".", "Upon", "its", "first", "call", "it", "creates", "a", "new", "instance", "of", "the", "decorated", "class", "and", "calls", "its", "__init__", "method", ".", "On", "all", "subsequent", "calls", "the", "already"...
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/design_pattern.py#L25-L35
meyersj/geotweet
geotweet/mapreduce/metro_wordcount.py
MRMetroMongoWordCount.mapper_init
def mapper_init(self): """ build local spatial index of US metro areas """ self.lookup = CachedMetroLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
python
def mapper_init(self): """ build local spatial index of US metro areas """ self.lookup = CachedMetroLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
[ "def", "mapper_init", "(", "self", ")", ":", "self", ".", "lookup", "=", "CachedMetroLookup", "(", "precision", "=", "GEOHASH_PRECISION", ")", "self", ".", "extractor", "=", "WordExtractor", "(", ")" ]
build local spatial index of US metro areas
[ "build", "local", "spatial", "index", "of", "US", "metro", "areas" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/metro_wordcount.py#L96-L99
meyersj/geotweet
geotweet/mapreduce/metro_wordcount.py
MRMetroMongoWordCount.reducer_init_output
def reducer_init_output(self): """ establish connection to MongoDB """ try: self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT) except ServerSelectionTimeoutError: # failed to connect to running MongoDB instance self.mongo = None
python
def reducer_init_output(self): """ establish connection to MongoDB """ try: self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT) except ServerSelectionTimeoutError: # failed to connect to running MongoDB instance self.mongo = None
[ "def", "reducer_init_output", "(", "self", ")", ":", "try", ":", "self", ".", "mongo", "=", "MongoGeo", "(", "db", "=", "DB", ",", "collection", "=", "COLLECTION", ",", "timeout", "=", "MONGO_TIMEOUT", ")", "except", "ServerSelectionTimeoutError", ":", "# fa...
establish connection to MongoDB
[ "establish", "connection", "to", "MongoDB" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/metro_wordcount.py#L124-L130
The-Politico/politico-civic-geography
geography/models/division.py
Division.save
def save(self, *args, **kwargs): """ **uid**: :code:`division:{parentuid}_{levelcode}-{code}` """ slug = "{}:{}".format(self.level.uid, self.code) if self.parent: self.uid = "{}_{}".format(self.parent.uid, slug) else: self.uid = slug self.s...
python
def save(self, *args, **kwargs): """ **uid**: :code:`division:{parentuid}_{levelcode}-{code}` """ slug = "{}:{}".format(self.level.uid, self.code) if self.parent: self.uid = "{}_{}".format(self.parent.uid, slug) else: self.uid = slug self.s...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "slug", "=", "\"{}:{}\"", ".", "format", "(", "self", ".", "level", ".", "uid", ",", "self", ".", "code", ")", "if", "self", ".", "parent", ":", "self", ".", "uid"...
**uid**: :code:`division:{parentuid}_{levelcode}-{code}`
[ "**", "uid", "**", ":", ":", "code", ":", "division", ":", "{", "parentuid", "}", "_", "{", "levelcode", "}", "-", "{", "code", "}" ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L70-L82
The-Politico/politico-civic-geography
geography/models/division.py
Division.add_intersecting
def add_intersecting(self, division, intersection=None, symm=True): """ Adds paired relationships between intersecting divisions. Optional intersection represents the portion of the area of the related division intersecting this division. You can only specify an intersection on ...
python
def add_intersecting(self, division, intersection=None, symm=True): """ Adds paired relationships between intersecting divisions. Optional intersection represents the portion of the area of the related division intersecting this division. You can only specify an intersection on ...
[ "def", "add_intersecting", "(", "self", ",", "division", ",", "intersection", "=", "None", ",", "symm", "=", "True", ")", ":", "relationship", ",", "created", "=", "IntersectRelationship", ".", "objects", ".", "update_or_create", "(", "from_division", "=", "se...
Adds paired relationships between intersecting divisions. Optional intersection represents the portion of the area of the related division intersecting this division. You can only specify an intersection on one side of the relationship when adding a peer.
[ "Adds", "paired", "relationships", "between", "intersecting", "divisions", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L84-L99
The-Politico/politico-civic-geography
geography/models/division.py
Division.remove_intersecting
def remove_intersecting(self, division, symm=True): """Removes paired relationships between intersecting divisions""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).delete() if symm: division.remove_intersecting(self, False)
python
def remove_intersecting(self, division, symm=True): """Removes paired relationships between intersecting divisions""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).delete() if symm: division.remove_intersecting(self, False)
[ "def", "remove_intersecting", "(", "self", ",", "division", ",", "symm", "=", "True", ")", ":", "IntersectRelationship", ".", "objects", ".", "filter", "(", "from_division", "=", "self", ",", "to_division", "=", "division", ")", ".", "delete", "(", ")", "i...
Removes paired relationships between intersecting divisions
[ "Removes", "paired", "relationships", "between", "intersecting", "divisions" ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L101-L107
The-Politico/politico-civic-geography
geography/models/division.py
Division.set_intersection
def set_intersection(self, division, intersection): """Set intersection percentage of intersecting divisions.""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
python
def set_intersection(self, division, intersection): """Set intersection percentage of intersecting divisions.""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
[ "def", "set_intersection", "(", "self", ",", "division", ",", "intersection", ")", ":", "IntersectRelationship", ".", "objects", ".", "filter", "(", "from_division", "=", "self", ",", "to_division", "=", "division", ")", ".", "update", "(", "intersection", "="...
Set intersection percentage of intersecting divisions.
[ "Set", "intersection", "percentage", "of", "intersecting", "divisions", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L109-L113
The-Politico/politico-civic-geography
geography/models/division.py
Division.get_intersection
def get_intersection(self, division): """Get intersection percentage of intersecting divisions.""" try: return IntersectRelationship.objects.get( from_division=self, to_division=division ).intersection except ObjectDoesNotExist: raise Exception...
python
def get_intersection(self, division): """Get intersection percentage of intersecting divisions.""" try: return IntersectRelationship.objects.get( from_division=self, to_division=division ).intersection except ObjectDoesNotExist: raise Exception...
[ "def", "get_intersection", "(", "self", ",", "division", ")", ":", "try", ":", "return", "IntersectRelationship", ".", "objects", ".", "get", "(", "from_division", "=", "self", ",", "to_division", "=", "division", ")", ".", "intersection", "except", "ObjectDoe...
Get intersection percentage of intersecting divisions.
[ "Get", "intersection", "percentage", "of", "intersecting", "divisions", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L115-L122
RudolfCardinal/pythonlib
cardinal_pythonlib/slurm.py
launch_slurm
def launch_slurm(jobname: str, cmd: str, memory_mb: int, project: str, qos: str, email: str, duration: timedelta, tasks_per_node: int, cpus_per_task: int, partition: s...
python
def launch_slurm(jobname: str, cmd: str, memory_mb: int, project: str, qos: str, email: str, duration: timedelta, tasks_per_node: int, cpus_per_task: int, partition: s...
[ "def", "launch_slurm", "(", "jobname", ":", "str", ",", "cmd", ":", "str", ",", "memory_mb", ":", "int", ",", "project", ":", "str", ",", "qos", ":", "str", ",", "email", ":", "str", ",", "duration", ":", "timedelta", ",", "tasks_per_node", ":", "int...
Launch a job into the SLURM environment. Args: jobname: name of the job cmd: command to be executed memory_mb: maximum memory requirement per process (Mb) project: project name qos: quality-of-service name email: user's e-mail address duration: maximum durati...
[ "Launch", "a", "job", "into", "the", "SLURM", "environment", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/slurm.py#L66-L211
RudolfCardinal/pythonlib
cardinal_pythonlib/slurm.py
launch_cambridge_hphi
def launch_cambridge_hphi( jobname: str, cmd: str, memory_mb: int, qos: str, email: str, duration: timedelta, cpus_per_task: int, project: str = "hphi", tasks_per_node: int = 1, partition: str = "wbic-cs", # 2018-02: was "wbic", now "wbic-...
python
def launch_cambridge_hphi( jobname: str, cmd: str, memory_mb: int, qos: str, email: str, duration: timedelta, cpus_per_task: int, project: str = "hphi", tasks_per_node: int = 1, partition: str = "wbic-cs", # 2018-02: was "wbic", now "wbic-...
[ "def", "launch_cambridge_hphi", "(", "jobname", ":", "str", ",", "cmd", ":", "str", ",", "memory_mb", ":", "int", ",", "qos", ":", "str", ",", "email", ":", "str", ",", "duration", ":", "timedelta", ",", "cpus_per_task", ":", "int", ",", "project", ":"...
Specialization of :func:`launch_slurm` (q.v.) with defaults for the University of Cambridge WBIC HPHI.
[ "Specialization", "of", ":", "func", ":", "launch_slurm", "(", "q", ".", "v", ".", ")", "with", "defaults", "for", "the", "University", "of", "Cambridge", "WBIC", "HPHI", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/slurm.py#L214-L248
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
get_drug
def get_drug(drug_name: str, name_is_generic: bool = False, include_categories: bool = False) -> Optional[Drug]: """ Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``....
python
def get_drug(drug_name: str, name_is_generic: bool = False, include_categories: bool = False) -> Optional[Drug]: """ Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``....
[ "def", "get_drug", "(", "drug_name", ":", "str", ",", "name_is_generic", ":", "bool", "=", "False", ",", "include_categories", ":", "bool", "=", "False", ")", "->", "Optional", "[", "Drug", "]", ":", "drug_name", "=", "drug_name", ".", "strip", "(", ")",...
Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``. Set ``include_categories=True`` to include drug categories (such as tricyclics) as well as individual drugs.
[ "Converts", "a", "drug", "name", "to", "a", ":", "class", ":", ".", "Drug", "class", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1295-L1317
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_name_to_generic
def drug_name_to_generic(drug_name: str, unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> str: """ Converts a drug name to the name of its generic equivalent. """ drug = get_drug(drug_na...
python
def drug_name_to_generic(drug_name: str, unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> str: """ Converts a drug name to the name of its generic equivalent. """ drug = get_drug(drug_na...
[ "def", "drug_name_to_generic", "(", "drug_name", ":", "str", ",", "unknown_to_default", ":", "bool", "=", "False", ",", "default", ":", "str", "=", "None", ",", "include_categories", ":", "bool", "=", "False", ")", "->", "str", ":", "drug", "=", "get_drug"...
Converts a drug name to the name of its generic equivalent.
[ "Converts", "a", "drug", "name", "to", "the", "name", "of", "its", "generic", "equivalent", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1324-L1334
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_names_to_generic
def drug_names_to_generic(drugs: List[str], unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> List[str]: """ Converts a list of drug names to their generic equivalents. The arguments are ...
python
def drug_names_to_generic(drugs: List[str], unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> List[str]: """ Converts a list of drug names to their generic equivalents. The arguments are ...
[ "def", "drug_names_to_generic", "(", "drugs", ":", "List", "[", "str", "]", ",", "unknown_to_default", ":", "bool", "=", "False", ",", "default", ":", "str", "=", "None", ",", "include_categories", ":", "bool", "=", "False", ")", "->", "List", "[", "str"...
Converts a list of drug names to their generic equivalents. The arguments are as for :func:`drug_name_to_generic` but this function handles a list of drug names rather than a single one. Note in passing the following conversion of blank-type representations from R via ``reticulate``, when using e.g. t...
[ "Converts", "a", "list", "of", "drug", "names", "to", "their", "generic", "equivalents", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1337-L1369
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_matches_criteria
def drug_matches_criteria(drug: Drug, **criteria: Dict[str, bool]) -> bool: """ Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of ...
python
def drug_matches_criteria(drug: Drug, **criteria: Dict[str, bool]) -> bool: """ Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of ...
[ "def", "drug_matches_criteria", "(", "drug", ":", "Drug", ",", "*", "*", "criteria", ":", "Dict", "[", "str", ",", "bool", "]", ")", "->", "bool", ":", "for", "attribute", ",", "value", "in", "criteria", ".", "items", "(", ")", ":", "if", "getattr", ...
Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of the :class:`Drug` class. For example, you can include keyword argum...
[ "Determines", "whether", "a", "drug", "passed", "as", "an", "instance", "of", ":", "class", ":", ".", "Drug", "matches", "the", "specified", "criteria", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1376-L1390
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
all_drugs_where
def all_drugs_where(sort=True, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[Drug]: """ Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If ``include_categories`` is true, then drug categories (like "tric...
python
def all_drugs_where(sort=True, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[Drug]: """ Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If ``include_categories`` is true, then drug categories (like "tric...
[ "def", "all_drugs_where", "(", "sort", "=", "True", ",", "include_categories", ":", "bool", "=", "False", ",", "*", "*", "criteria", ":", "Dict", "[", "str", ",", "bool", "]", ")", "->", "List", "[", "Drug", "]", ":", "matching_drugs", "=", "[", "]",...
Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If ``include_categories`` is true, then drug categories (like "tricyclics") are included as well as individual drugs. Pass keyword arguments such as .. code-block:: python from cardinal_pythonlib.psychiatr...
[ "Find", "all", "drugs", "matching", "the", "specified", "criteria", "(", "see", ":", "func", ":", "drug_matches_criteria", ")", ".", "If", "include_categories", "is", "true", "then", "drug", "categories", "(", "like", "tricyclics", ")", "are", "included", "as"...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1393-L1420
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_name_matches_criteria
def drug_name_matches_criteria(drug_name: str, name_is_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> bool: """ Establish whether a single drug, passed by name, matches the spec...
python
def drug_name_matches_criteria(drug_name: str, name_is_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> bool: """ Establish whether a single drug, passed by name, matches the spec...
[ "def", "drug_name_matches_criteria", "(", "drug_name", ":", "str", ",", "name_is_generic", ":", "bool", "=", "False", ",", "include_categories", ":", "bool", "=", "False", ",", "*", "*", "criteria", ":", "Dict", "[", "str", ",", "bool", "]", ")", "->", "...
Establish whether a single drug, passed by name, matches the specified criteria. See :func:`drug_matches_criteria`.
[ "Establish", "whether", "a", "single", "drug", "passed", "by", "name", "matches", "the", "specified", "criteria", ".", "See", ":", "func", ":", "drug_matches_criteria", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1423-L1436
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_names_match_criteria
def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[bool]: """ Establish whether multiple drugs, passed as a list of ...
python
def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[bool]: """ Establish whether multiple drugs, passed as a list of ...
[ "def", "drug_names_match_criteria", "(", "drug_names", ":", "List", "[", "str", "]", ",", "names_are_generic", ":", "bool", "=", "False", ",", "include_categories", ":", "bool", "=", "False", ",", "*", "*", "criteria", ":", "Dict", "[", "str", ",", "bool",...
Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`.
[ "Establish", "whether", "multiple", "drugs", "passed", "as", "a", "list", "of", "drug", "names", "each", "matches", "the", "specified", "criteria", ".", "See", ":", "func", ":", "drug_matches_criteria", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1439-L1454
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.regex_text
def regex_text(self) -> str: """ Return regex text (yet to be compiled) for this drug. """ if self._regex_text is None: possibilities = [] # type: List[str] for p in list(set(self.all_generics + self.alternatives)): if self.add_preceding_word_boun...
python
def regex_text(self) -> str: """ Return regex text (yet to be compiled) for this drug. """ if self._regex_text is None: possibilities = [] # type: List[str] for p in list(set(self.all_generics + self.alternatives)): if self.add_preceding_word_boun...
[ "def", "regex_text", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_regex_text", "is", "None", ":", "possibilities", "=", "[", "]", "# type: List[str]", "for", "p", "in", "list", "(", "set", "(", "self", ".", "all_generics", "+", "self", ".",...
Return regex text (yet to be compiled) for this drug.
[ "Return", "regex", "text", "(", "yet", "to", "be", "compiled", ")", "for", "this", "drug", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L501-L516
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.regex
def regex(self) -> Pattern: """ Returns a compiled regex for this drug. """ if self._regex is None: self._regex = re.compile(self.regex_text, re.IGNORECASE | re.DOTALL) return self._regex
python
def regex(self) -> Pattern: """ Returns a compiled regex for this drug. """ if self._regex is None: self._regex = re.compile(self.regex_text, re.IGNORECASE | re.DOTALL) return self._regex
[ "def", "regex", "(", "self", ")", "->", "Pattern", ":", "if", "self", ".", "_regex", "is", "None", ":", "self", ".", "_regex", "=", "re", ".", "compile", "(", "self", ".", "regex_text", ",", "re", ".", "IGNORECASE", "|", "re", ".", "DOTALL", ")", ...
Returns a compiled regex for this drug.
[ "Returns", "a", "compiled", "regex", "for", "this", "drug", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L519-L526
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.regex_to_sql_like
def regex_to_sql_like(regex_text: str, single_wildcard: str = "_", zero_or_more_wildcard: str = "%") -> List[str]: """ Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but work...
python
def regex_to_sql_like(regex_text: str, single_wildcard: str = "_", zero_or_more_wildcard: str = "%") -> List[str]: """ Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but work...
[ "def", "regex_to_sql_like", "(", "regex_text", ":", "str", ",", "single_wildcard", ":", "str", "=", "\"_\"", ",", "zero_or_more_wildcard", ":", "str", "=", "\"%\"", ")", "->", "List", "[", "str", "]", ":", "def", "append_to_all", "(", "new_content", ":", "...
Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but works for current built-in regular expressions. Args: regex_text: regular expression text to work with single_wildcard: SQL single wildcard, typically an unde...
[ "Converts", "regular", "expression", "text", "to", "a", "reasonably", "close", "fragment", "for", "the", "SQL", "LIKE", "operator", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L529-L605
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.sql_like_fragments
def sql_like_fragments(self) -> List[str]: """ Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and...
python
def sql_like_fragments(self) -> List[str]: """ Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and...
[ "def", "sql_like_fragments", "(", "self", ")", "->", "List", "[", "str", "]", ":", "if", "self", ".", "_sql_like_fragments", "is", "None", ":", "self", ".", "_sql_like_fragments", "=", "[", "]", "for", "p", "in", "list", "(", "set", "(", "self", ".", ...
Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and ``%``.
[ "Returns", "all", "the", "string", "literals", "to", "which", "a", "database", "column", "should", "be", "compared", "using", "the", "SQL", "LIKE", "operator", "to", "match", "this", "drug", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L608-L621
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.name_matches
def name_matches(self, name: str) -> bool: """ Detects whether the name that's passed matches our knowledge of any of things that this drug might be called: generic name, brand name(s), common misspellings. The parameter should be pre-stripped of edge whitespace. """ ...
python
def name_matches(self, name: str) -> bool: """ Detects whether the name that's passed matches our knowledge of any of things that this drug might be called: generic name, brand name(s), common misspellings. The parameter should be pre-stripped of edge whitespace. """ ...
[ "def", "name_matches", "(", "self", ",", "name", ":", "str", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "regex", ".", "match", "(", "name", ")", ")" ]
Detects whether the name that's passed matches our knowledge of any of things that this drug might be called: generic name, brand name(s), common misspellings. The parameter should be pre-stripped of edge whitespace.
[ "Detects", "whether", "the", "name", "that", "s", "passed", "matches", "our", "knowledge", "of", "any", "of", "things", "that", "this", "drug", "might", "be", "called", ":", "generic", "name", "brand", "name", "(", "s", ")", "common", "misspellings", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L623-L631
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.sql_column_like_drug
def sql_column_like_drug(self, column_name: str) -> str: """ Returns SQL like .. code-block:: sql (column_name LIKE '%drugname1%' OR column_name LIKE '%drugname2%') for the drug names that this Drug object knows about. Args: column_name: c...
python
def sql_column_like_drug(self, column_name: str) -> str: """ Returns SQL like .. code-block:: sql (column_name LIKE '%drugname1%' OR column_name LIKE '%drugname2%') for the drug names that this Drug object knows about. Args: column_name: c...
[ "def", "sql_column_like_drug", "(", "self", ",", "column_name", ":", "str", ")", "->", "str", ":", "clauses", "=", "[", "\"{col} LIKE {fragment}\"", ".", "format", "(", "col", "=", "column_name", ",", "fragment", "=", "sql_string_literal", "(", "f", ")", ")"...
Returns SQL like .. code-block:: sql (column_name LIKE '%drugname1%' OR column_name LIKE '%drugname2%') for the drug names that this Drug object knows about. Args: column_name: column name, pre-escaped if necessary Returns: SQL fragme...
[ "Returns", "SQL", "like" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L633-L657
davenquinn/Attitude
attitude/stereonet.py
quaternion
def quaternion(vector, angle): """ Unit quaternion for a vector and an angle """ return N.cos(angle/2)+vector*N.sin(angle/2)
python
def quaternion(vector, angle): """ Unit quaternion for a vector and an angle """ return N.cos(angle/2)+vector*N.sin(angle/2)
[ "def", "quaternion", "(", "vector", ",", "angle", ")", ":", "return", "N", ".", "cos", "(", "angle", "/", "2", ")", "+", "vector", "*", "N", ".", "sin", "(", "angle", "/", "2", ")" ]
Unit quaternion for a vector and an angle
[ "Unit", "quaternion", "for", "a", "vector", "and", "an", "angle" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L7-L11
davenquinn/Attitude
attitude/stereonet.py
ellipse
def ellipse(n=1000, adaptive=False): """ Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given. """ u = N.linspace(0,2*N.pi,n) # Get a bundle of vectors defining # a full rotation around the unit...
python
def ellipse(n=1000, adaptive=False): """ Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given. """ u = N.linspace(0,2*N.pi,n) # Get a bundle of vectors defining # a full rotation around the unit...
[ "def", "ellipse", "(", "n", "=", "1000", ",", "adaptive", "=", "False", ")", ":", "u", "=", "N", ".", "linspace", "(", "0", ",", "2", "*", "N", ".", "pi", ",", "n", ")", "# Get a bundle of vectors defining", "# a full rotation around the unit circle", "ret...
Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given.
[ "Get", "a", "parameterized", "set", "of", "vectors", "defining", "ellipse", "for", "a", "major", "and", "minor", "axis", "length", ".", "Resulting", "vector", "bundle", "has", "major", "axes", "along", "axes", "given", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L13-L23
davenquinn/Attitude
attitude/stereonet.py
scale_errors
def scale_errors(cov_axes, confidence_level=0.95): """ Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic """ dof = len(cov_axes) x2t = chi2.ppf(confidence_level,dof) return N.sqrt(x2t*cov_axes)
python
def scale_errors(cov_axes, confidence_level=0.95): """ Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic """ dof = len(cov_axes) x2t = chi2.ppf(confidence_level,dof) return N.sqrt(x2t*cov_axes)
[ "def", "scale_errors", "(", "cov_axes", ",", "confidence_level", "=", "0.95", ")", ":", "dof", "=", "len", "(", "cov_axes", ")", "x2t", "=", "chi2", ".", "ppf", "(", "confidence_level", ",", "dof", ")", "return", "N", ".", "sqrt", "(", "x2t", "*", "c...
Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic
[ "Returns", "major", "axes", "of", "error", "ellipse", "or", "hyperbola", "rescaled", "using", "chi2", "test", "statistic" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L33-L40
davenquinn/Attitude
attitude/stereonet.py
normal_errors
def normal_errors(axes, covariance_matrix, **kwargs): """ Currently assumes upper hemisphere of stereonet """ level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.diagonal(covariance_matrix) ell = ellipse(**kwargs) if axes[2,2] < 0: axes...
python
def normal_errors(axes, covariance_matrix, **kwargs): """ Currently assumes upper hemisphere of stereonet """ level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.diagonal(covariance_matrix) ell = ellipse(**kwargs) if axes[2,2] < 0: axes...
[ "def", "normal_errors", "(", "axes", ",", "covariance_matrix", ",", "*", "*", "kwargs", ")", ":", "level", "=", "kwargs", ".", "pop", "(", "'level'", ",", "1", ")", "traditional_layout", "=", "kwargs", ".", "pop", "(", "'traditional_layout'", ",", "True", ...
Currently assumes upper hemisphere of stereonet
[ "Currently", "assumes", "upper", "hemisphere", "of", "stereonet" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L42-L70
davenquinn/Attitude
attitude/stereonet.py
plane_errors
def plane_errors(axes, covariance_matrix, sheet='upper',**kwargs): """ kwargs: traditional_layout boolean [True] Lay the stereonet out traditionally, with north at the pole of the diagram. The default is a more natural and intuitive visualization with vertical at the pole and the co...
python
def plane_errors(axes, covariance_matrix, sheet='upper',**kwargs): """ kwargs: traditional_layout boolean [True] Lay the stereonet out traditionally, with north at the pole of the diagram. The default is a more natural and intuitive visualization with vertical at the pole and the co...
[ "def", "plane_errors", "(", "axes", ",", "covariance_matrix", ",", "sheet", "=", "'upper'", ",", "*", "*", "kwargs", ")", ":", "level", "=", "kwargs", ".", "pop", "(", "'level'", ",", "1", ")", "traditional_layout", "=", "kwargs", ".", "pop", "(", "'tr...
kwargs: traditional_layout boolean [True] Lay the stereonet out traditionally, with north at the pole of the diagram. The default is a more natural and intuitive visualization with vertical at the pole and the compass points of strike around the equator. Thus, longitude at the equat...
[ "kwargs", ":", "traditional_layout", "boolean", "[", "True", "]", "Lay", "the", "stereonet", "out", "traditionally", "with", "north", "at", "the", "pole", "of", "the", "diagram", ".", "The", "default", "is", "a", "more", "natural", "and", "intuitive", "visua...
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L114-L154
davenquinn/Attitude
attitude/stereonet.py
iterative_plane_errors
def iterative_plane_errors(axes,covariance_matrix, **kwargs): """ An iterative version of `pca.plane_errors`, which computes an error surface for a plane. """ sheet = kwargs.pop('sheet','upper') level = kwargs.pop('level',1) n = kwargs.pop('n',100) cov = N.sqrt(N.diagonal(covariance_mat...
python
def iterative_plane_errors(axes,covariance_matrix, **kwargs): """ An iterative version of `pca.plane_errors`, which computes an error surface for a plane. """ sheet = kwargs.pop('sheet','upper') level = kwargs.pop('level',1) n = kwargs.pop('n',100) cov = N.sqrt(N.diagonal(covariance_mat...
[ "def", "iterative_plane_errors", "(", "axes", ",", "covariance_matrix", ",", "*", "*", "kwargs", ")", ":", "sheet", "=", "kwargs", ".", "pop", "(", "'sheet'", ",", "'upper'", ")", "level", "=", "kwargs", ".", "pop", "(", "'level'", ",", "1", ")", "n", ...
An iterative version of `pca.plane_errors`, which computes an error surface for a plane.
[ "An", "iterative", "version", "of", "pca", ".", "plane_errors", "which", "computes", "an", "error", "surface", "for", "a", "plane", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L156-L193
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/sql_grammar.py
SqlGrammar.quote_identifier_if_required
def quote_identifier_if_required(cls, identifier: str, debug_force_quote: bool = False) -> str: """ Transforms a SQL identifier (such as a column name) into a version that is quoted if required (or, with ``debug_force_quote=True``, is quoted regardles...
python
def quote_identifier_if_required(cls, identifier: str, debug_force_quote: bool = False) -> str: """ Transforms a SQL identifier (such as a column name) into a version that is quoted if required (or, with ``debug_force_quote=True``, is quoted regardles...
[ "def", "quote_identifier_if_required", "(", "cls", ",", "identifier", ":", "str", ",", "debug_force_quote", ":", "bool", "=", "False", ")", "->", "str", ":", "if", "debug_force_quote", ":", "return", "cls", ".", "quote_identifier", "(", "identifier", ")", "if"...
Transforms a SQL identifier (such as a column name) into a version that is quoted if required (or, with ``debug_force_quote=True``, is quoted regardless).
[ "Transforms", "a", "SQL", "identifier", "(", "such", "as", "a", "column", "name", ")", "into", "a", "version", "that", "is", "quoted", "if", "required", "(", "or", "with", "debug_force_quote", "=", "True", "is", "quoted", "regardless", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/sql_grammar.py#L640-L653
The-Politico/politico-civic-geography
geography/models/geometry.py
Geometry.to_topojson
def to_topojson(self): """Adds points and converts to topojson string.""" topojson = self.topojson topojson["objects"]["points"] = { "type": "GeometryCollection", "geometries": [point.to_topojson() for point in self.points.all()], } return json.dumps(topoj...
python
def to_topojson(self): """Adds points and converts to topojson string.""" topojson = self.topojson topojson["objects"]["points"] = { "type": "GeometryCollection", "geometries": [point.to_topojson() for point in self.points.all()], } return json.dumps(topoj...
[ "def", "to_topojson", "(", "self", ")", ":", "topojson", "=", "self", ".", "topojson", "topojson", "[", "\"objects\"", "]", "[", "\"points\"", "]", "=", "{", "\"type\"", ":", "\"GeometryCollection\"", ",", "\"geometries\"", ":", "[", "point", ".", "to_topojs...
Adds points and converts to topojson string.
[ "Adds", "points", "and", "converts", "to", "topojson", "string", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/geometry.py#L124-L131
Netuitive/netuitive-client-python
netuitive/client.py
Client.post
def post(self, element): """ :param element: Element to post to Netuitive :type element: object """ try: if self.disabled is True: element.clear_samples() logging.error('Posting has been disabled. ' ...
python
def post(self, element): """ :param element: Element to post to Netuitive :type element: object """ try: if self.disabled is True: element.clear_samples() logging.error('Posting has been disabled. ' ...
[ "def", "post", "(", "self", ",", "element", ")", ":", "try", ":", "if", "self", ".", "disabled", "is", "True", ":", "element", ".", "clear_samples", "(", ")", "logging", ".", "error", "(", "'Posting has been disabled. '", "'See previous errors for details.'", ...
:param element: Element to post to Netuitive :type element: object
[ ":", "param", "element", ":", "Element", "to", "post", "to", "Netuitive", ":", "type", "element", ":", "object" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/client.py#L56-L115
Netuitive/netuitive-client-python
netuitive/client.py
Client.post_event
def post_event(self, event): """ :param event: Event to post to Netuitive :type event: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) ...
python
def post_event(self, event): """ :param event: Event to post to Netuitive :type event: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) ...
[ "def", "post_event", "(", "self", ",", "event", ")", ":", "if", "self", ".", "disabled", "is", "True", ":", "logging", ".", "error", "(", "'Posting has been disabled. '", "'See previous errors for details.'", ")", "return", "(", "False", ")", "payload", "=", "...
:param event: Event to post to Netuitive :type event: object
[ ":", "param", "event", ":", "Event", "to", "post", "to", "Netuitive", ":", "type", "event", ":", "object" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/client.py#L117-L157
Netuitive/netuitive-client-python
netuitive/client.py
Client.post_check
def post_check(self, check): """ :param check: Check to post to Metricly :type check: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) ...
python
def post_check(self, check): """ :param check: Check to post to Metricly :type check: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) ...
[ "def", "post_check", "(", "self", ",", "check", ")", ":", "if", "self", ".", "disabled", "is", "True", ":", "logging", ".", "error", "(", "'Posting has been disabled. '", "'See previous errors for details.'", ")", "return", "(", "False", ")", "url", "=", "self...
:param check: Check to post to Metricly :type check: object
[ ":", "param", "check", ":", "Check", "to", "post", "to", "Metricly", ":", "type", "check", ":", "object" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/client.py#L159-L195
ivanprjcts/sdklib
sdklib/util/urls.py
urlsplit
def urlsplit(url): """ Split url into scheme, host, port, path, query :param str url: :return: scheme, host, port, path, query """ p = '((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' m = re.search(p, url) scheme = m.group('scheme') host = m.group('host') port = m....
python
def urlsplit(url): """ Split url into scheme, host, port, path, query :param str url: :return: scheme, host, port, path, query """ p = '((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' m = re.search(p, url) scheme = m.group('scheme') host = m.group('host') port = m....
[ "def", "urlsplit", "(", "url", ")", ":", "p", "=", "'((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*'", "m", "=", "re", ".", "search", "(", "p", ",", "url", ")", "scheme", "=", "m", ".", "group", "(", "'scheme'", ")", "host", "=", "m", ".", ...
Split url into scheme, host, port, path, query :param str url: :return: scheme, host, port, path, query
[ "Split", "url", "into", "scheme", "host", "port", "path", "query" ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/urls.py#L6-L21
ivanprjcts/sdklib
sdklib/util/urls.py
generate_url
def generate_url(scheme=None, host=None, port=None, path=None, query=None): """ Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return: """ url = "" if scheme is not None: url += "%s://" % scheme...
python
def generate_url(scheme=None, host=None, port=None, path=None, query=None): """ Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return: """ url = "" if scheme is not None: url += "%s://" % scheme...
[ "def", "generate_url", "(", "scheme", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "path", "=", "None", ",", "query", "=", "None", ")", ":", "url", "=", "\"\"", "if", "scheme", "is", "not", "None", ":", "url", "+=", "\"%s...
Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return:
[ "Generate", "URI", "from", "parameters", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/urls.py#L60-L82
meyersj/geotweet
geotweet/osm.py
OSMRunner.run
def run(self): """ For each state in states file build url and download file """ states = open(self.states, 'r').read().splitlines() for state in states: url = self.build_url(state) log = "Downloading State < {0} > from < {1} >" logging.info(log.format(state, ...
python
def run(self): """ For each state in states file build url and download file """ states = open(self.states, 'r').read().splitlines() for state in states: url = self.build_url(state) log = "Downloading State < {0} > from < {1} >" logging.info(log.format(state, ...
[ "def", "run", "(", "self", ")", ":", "states", "=", "open", "(", "self", ".", "states", ",", "'r'", ")", ".", "read", "(", ")", ".", "splitlines", "(", ")", "for", "state", "in", "states", ":", "url", "=", "self", ".", "build_url", "(", "state", ...
For each state in states file build url and download file
[ "For", "each", "state", "in", "states", "file", "build", "url", "and", "download", "file" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L37-L45
meyersj/geotweet
geotweet/osm.py
OSMRunner.download
def download(self, output_dir, url, overwrite): """ Dowload file to /tmp """ tmp = self.url2tmp(output_dir, url) if os.path.isfile(tmp) and not overwrite: logging.info("File {0} already exists. Skipping download.".format(tmp)) return tmp f = open(tmp, 'wb') ...
python
def download(self, output_dir, url, overwrite): """ Dowload file to /tmp """ tmp = self.url2tmp(output_dir, url) if os.path.isfile(tmp) and not overwrite: logging.info("File {0} already exists. Skipping download.".format(tmp)) return tmp f = open(tmp, 'wb') ...
[ "def", "download", "(", "self", ",", "output_dir", ",", "url", ",", "overwrite", ")", ":", "tmp", "=", "self", ".", "url2tmp", "(", "output_dir", ",", "url", ")", "if", "os", ".", "path", ".", "isfile", "(", "tmp", ")", "and", "not", "overwrite", "...
Dowload file to /tmp
[ "Dowload", "file", "to", "/", "tmp" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L47-L65
meyersj/geotweet
geotweet/osm.py
OSMRunner.extract
def extract(self, pbf, output): """ extract POI nodes from osm pbf extract """ logging.info("Extracting POI nodes from {0} to {1}".format(pbf, output)) with open(output, 'w') as f: # define callback for each node that is processed def nodes_callback(nodes): ...
python
def extract(self, pbf, output): """ extract POI nodes from osm pbf extract """ logging.info("Extracting POI nodes from {0} to {1}".format(pbf, output)) with open(output, 'w') as f: # define callback for each node that is processed def nodes_callback(nodes): ...
[ "def", "extract", "(", "self", ",", "pbf", ",", "output", ")", ":", "logging", ".", "info", "(", "\"Extracting POI nodes from {0} to {1}\"", ".", "format", "(", "pbf", ",", "output", ")", ")", "with", "open", "(", "output", ",", "'w'", ")", "as", "f", ...
extract POI nodes from osm pbf extract
[ "extract", "POI", "nodes", "from", "osm", "pbf", "extract" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L67-L81
meyersj/geotweet
geotweet/osm.py
OSMRunner.url2tmp
def url2tmp(self, root, url): """ convert url path to filename """ filename = url.rsplit('/', 1)[-1] return os.path.join(root, filename)
python
def url2tmp(self, root, url): """ convert url path to filename """ filename = url.rsplit('/', 1)[-1] return os.path.join(root, filename)
[ "def", "url2tmp", "(", "self", ",", "root", ",", "url", ")", ":", "filename", "=", "url", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "-", "1", "]", "return", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")" ]
convert url path to filename
[ "convert", "url", "path", "to", "filename" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L86-L89
RudolfCardinal/pythonlib
cardinal_pythonlib/ui.py
ask_user
def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return result if len(result) > 0 else...
python
def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return result if len(result) > 0 else...
[ "def", "ask_user", "(", "prompt", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "if", "default", "is", "None", ":", "prompt", "+=", "\": \"", "else", ":", "prompt", "+=", "\" [\"", "+", "default", ...
Prompts the user, with a default. Returns user input from ``stdin``.
[ "Prompts", "the", "user", "with", "a", "default", ".", "Returns", "user", "input", "from", "stdin", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/ui.py#L44-L53
RudolfCardinal/pythonlib
cardinal_pythonlib/ui.py
get_save_as_filename
def get_save_as_filename(defaultfilename: str, defaultextension: str, title: str = "Save As") -> str: """ Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # ...
python
def get_save_as_filename(defaultfilename: str, defaultextension: str, title: str = "Save As") -> str: """ Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # ...
[ "def", "get_save_as_filename", "(", "defaultfilename", ":", "str", ",", "defaultextension", ":", "str", ",", "title", ":", "str", "=", "\"Save As\"", ")", "->", "str", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "# create and get Tk topmost window", "# (...
Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename.
[ "Provides", "a", "GUI", "Save", "As", "dialogue", "(", "via", "tkinter", ")", "and", "returns", "the", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/ui.py#L63-L81
RudolfCardinal/pythonlib
cardinal_pythonlib/ui.py
get_open_filename
def get_open_filename(defaultfilename: str, defaultextension: str, title: str = "Open") -> str: """ Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # (don't do this too ...
python
def get_open_filename(defaultfilename: str, defaultextension: str, title: str = "Open") -> str: """ Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # (don't do this too ...
[ "def", "get_open_filename", "(", "defaultfilename", ":", "str", ",", "defaultextension", ":", "str", ",", "title", ":", "str", "=", "\"Open\"", ")", "->", "str", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "# create and get Tk topmost window", "# (don't ...
Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename.
[ "Provides", "a", "GUI", "Open", "dialogue", "(", "via", "tkinter", ")", "and", "returns", "the", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/ui.py#L84-L101
RudolfCardinal/pythonlib
cardinal_pythonlib/argparse_func.py
str2bool
def str2bool(v: str) -> bool: """ ``argparse`` type that maps strings in case-insensitive fashion like this: .. code-block:: none argument strings value ------------------------------- ----- 'yes', 'true', 't', 'y', '1' True 'no', 'false', 'f', 'n'...
python
def str2bool(v: str) -> bool: """ ``argparse`` type that maps strings in case-insensitive fashion like this: .. code-block:: none argument strings value ------------------------------- ----- 'yes', 'true', 't', 'y', '1' True 'no', 'false', 'f', 'n'...
[ "def", "str2bool", "(", "v", ":", "str", ")", "->", "bool", ":", "# noqa", "lv", "=", "v", ".", "lower", "(", ")", "if", "lv", "in", "(", "'yes'", ",", "'true'", ",", "'t'", ",", "'y'", ",", "'1'", ")", ":", "return", "True", "elif", "lv", "i...
``argparse`` type that maps strings in case-insensitive fashion like this: .. code-block:: none argument strings value ------------------------------- ----- 'yes', 'true', 't', 'y', '1' True 'no', 'false', 'f', 'n', '0' False From https://...
[ "argparse", "type", "that", "maps", "strings", "in", "case", "-", "insensitive", "fashion", "like", "this", ":", "..", "code", "-", "block", "::", "none", "argument", "strings", "value", "-------------------------------", "-----", "yes", "true", "t", "y", "1",...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/argparse_func.py#L101-L132
RudolfCardinal/pythonlib
cardinal_pythonlib/argparse_func.py
positive_int
def positive_int(value: str) -> int: """ ``argparse`` argument type that checks that its value is a positive integer. """ try: ivalue = int(value) assert ivalue > 0 except (AssertionError, TypeError, ValueError): raise ArgumentTypeError( "{!r} is an invalid po...
python
def positive_int(value: str) -> int: """ ``argparse`` argument type that checks that its value is a positive integer. """ try: ivalue = int(value) assert ivalue > 0 except (AssertionError, TypeError, ValueError): raise ArgumentTypeError( "{!r} is an invalid po...
[ "def", "positive_int", "(", "value", ":", "str", ")", "->", "int", ":", "try", ":", "ivalue", "=", "int", "(", "value", ")", "assert", "ivalue", ">", "0", "except", "(", "AssertionError", ",", "TypeError", ",", "ValueError", ")", ":", "raise", "Argumen...
``argparse`` argument type that checks that its value is a positive integer.
[ "argparse", "argument", "type", "that", "checks", "that", "its", "value", "is", "a", "positive", "integer", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/argparse_func.py#L135-L146
RudolfCardinal/pythonlib
cardinal_pythonlib/argparse_func.py
percentage
def percentage(value: str) -> float: """ ``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]). """ try: fvalue = float(value) assert 0 <= fvalue <= 100 except (AssertionError, TypeError, ValueError): raise A...
python
def percentage(value: str) -> float: """ ``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]). """ try: fvalue = float(value) assert 0 <= fvalue <= 100 except (AssertionError, TypeError, ValueError): raise A...
[ "def", "percentage", "(", "value", ":", "str", ")", "->", "float", ":", "try", ":", "fvalue", "=", "float", "(", "value", ")", "assert", "0", "<=", "fvalue", "<=", "100", "except", "(", "AssertionError", ",", "TypeError", ",", "ValueError", ")", ":", ...
``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]).
[ "argparse", "argument", "type", "that", "checks", "that", "its", "value", "is", "a", "percentage", "(", "in", "the", "sense", "of", "a", "float", "in", "the", "range", "[", "0", "100", "]", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/argparse_func.py#L163-L174
calston/rhumba
rhumba/http_client.py
HTTPRequest.abort_request
def abort_request(self, request): """Called to abort request on timeout""" self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
python
def abort_request(self, request): """Called to abort request on timeout""" self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
[ "def", "abort_request", "(", "self", ",", "request", ")", ":", "self", ".", "timedout", "=", "True", "try", ":", "request", ".", "cancel", "(", ")", "except", "error", ".", "AlreadyCancelled", ":", "return" ]
Called to abort request on timeout
[ "Called", "to", "abort", "request", "on", "timeout" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L69-L75
calston/rhumba
rhumba/http_client.py
HTTPRequest.getBody
def getBody(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return cls().request(url, method, headers, data, socket, time...
python
def getBody(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return cls().request(url, method, headers, data, socket, time...
[ "def", "getBody", "(", "cls", ",", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "{", "}", ",", "data", "=", "None", ",", "socket", "=", "None", ",", "timeout", "=", "120", ")", ":", "if", "not", "'User-Agent'", "in", "headers", ":", "...
Make an HTTP request and return the body
[ "Make", "an", "HTTP", "request", "and", "return", "the", "body" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L131-L137
calston/rhumba
rhumba/http_client.py
HTTPRequest.getJson
def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Fetch a JSON result via HTTP """ if not 'Content-Type' in headers: headers['Content-Type'] = ['application/json'] body = yield cls().getBody(url, method, headers, data, socket, timeout) ...
python
def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Fetch a JSON result via HTTP """ if not 'Content-Type' in headers: headers['Content-Type'] = ['application/json'] body = yield cls().getBody(url, method, headers, data, socket, timeout) ...
[ "def", "getJson", "(", "cls", ",", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "{", "}", ",", "data", "=", "None", ",", "socket", "=", "None", ",", "timeout", "=", "120", ")", ":", "if", "not", "'Content-Type'", "in", "headers", ":", ...
Fetch a JSON result via HTTP
[ "Fetch", "a", "JSON", "result", "via", "HTTP" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L141-L149
davenquinn/Attitude
attitude/geom/__init__.py
aligned_covariance
def aligned_covariance(fit, type='noise'): """ Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space """ cov = fit._covariance_matrix(type) # Rescale eigenvectors to sum to 1 cov /= N.linalg.norm(cov) return dot(fit.axes,cov)
python
def aligned_covariance(fit, type='noise'): """ Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space """ cov = fit._covariance_matrix(type) # Rescale eigenvectors to sum to 1 cov /= N.linalg.norm(cov) return dot(fit.axes,cov)
[ "def", "aligned_covariance", "(", "fit", ",", "type", "=", "'noise'", ")", ":", "cov", "=", "fit", ".", "_covariance_matrix", "(", "type", ")", "# Rescale eigenvectors to sum to 1", "cov", "/=", "N", ".", "linalg", ".", "norm", "(", "cov", ")", "return", "...
Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space
[ "Covariance", "rescaled", "so", "that", "eigenvectors", "sum", "to", "1", "and", "rotated", "into", "data", "coordinates", "from", "PCA", "space" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/__init__.py#L7-L15