repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
avihad/twistes | twistes/utilities.py | EsUtils.validate_scan_result | def validate_scan_result(results):
""" Check if there's a failed shard in the scan query"""
if results[EsConst.SHARDS][EsConst.FAILED] and results[EsConst.SHARDS][EsConst.FAILED] > 0:
raise ScanError(
'Scroll request has failed on %d shards out of %d.' %
(results[EsConst.SHARDS][EsConst.FAILED], results[EsConst.SHARDS][EsConst.TOTAL])
) | python | def validate_scan_result(results):
""" Check if there's a failed shard in the scan query"""
if results[EsConst.SHARDS][EsConst.FAILED] and results[EsConst.SHARDS][EsConst.FAILED] > 0:
raise ScanError(
'Scroll request has failed on %d shards out of %d.' %
(results[EsConst.SHARDS][EsConst.FAILED], results[EsConst.SHARDS][EsConst.TOTAL])
) | [
"def",
"validate_scan_result",
"(",
"results",
")",
":",
"if",
"results",
"[",
"EsConst",
".",
"SHARDS",
"]",
"[",
"EsConst",
".",
"FAILED",
"]",
"and",
"results",
"[",
"EsConst",
".",
"SHARDS",
"]",
"[",
"EsConst",
".",
"FAILED",
"]",
">",
"0",
":",
... | Check if there's a failed shard in the scan query | [
"Check",
"if",
"there",
"s",
"a",
"failed",
"shard",
"in",
"the",
"scan",
"query"
] | 9ab8f5aa088b8886aefe3dec85a400e5035e034a | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/utilities.py#L47-L53 | train | 53,000 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/helpers.py#L56-L63 | train | 53,001 |
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=tee_file)
handler.setLevel(loglevel)
rootlogger = logging.getLogger()
rootlogger.addHandler(handler)
# Tee the main stdout/stderr as required.
with TeeContextManager(tee_file, capture_stdout=True):
with TeeContextManager(tee_file, capture_stderr=True):
try:
yield
except Exception:
# We catch this so that the exception also goes to
# the log.
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value,
exc_traceback)
log.critical("\n" + "".join(lines))
raise | 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=tee_file)
handler.setLevel(loglevel)
rootlogger = logging.getLogger()
rootlogger.addHandler(handler)
# Tee the main stdout/stderr as required.
with TeeContextManager(tee_file, capture_stdout=True):
with TeeContextManager(tee_file, capture_stderr=True):
try:
yield
except Exception:
# We catch this so that the exception also goes to
# the log.
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value,
exc_traceback)
log.critical("\n" + "".join(lines))
raise | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L290-L315 | train | 53,002 |
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=False)[2][2]
beta_boots = bootstrap(array, func=reg_func)
return yhat, yhat_boots | 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=False)[2][2]
beta_boots = bootstrap(array, func=reg_func)
return yhat, yhat_boots | [
"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",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/bootstrap.py#L6-L16 | train | 53,003 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L81-L85 | train | 53,004 |
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:
a new dictionary
Keys that are not in ``mapping`` are left unchanged.
The input parameters are not modified.
"""
result = {} # type: Dict[str, Any]
for k, v in d.items():
if k in mapping:
k = mapping[k]
result[k] = v
return result | 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:
a new dictionary
Keys that are not in ``mapping`` are left unchanged.
The input parameters are not modified.
"""
result = {} # type: Dict[str, Any]
for k, v in d.items():
if k in mapping:
k = mapping[k]
result[k] = v
return result | [
"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 input parameters are not modified. | [
"Returns",
"a",
"copy",
"of",
"the",
"dictionary",
"d",
"with",
"its",
"keys",
"renamed",
"according",
"to",
"mapping",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L88-L108 | train | 53,005 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L134-L142 | train | 53,006 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L145-L149 | train | 53,007 |
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``, 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`` is true.
"""
result = []
for k in l:
if raise_if_missing and k not in d:
raise ValueError("Missing key: " + repr(k))
if omit_if_missing and k not in d:
continue
result.append(d.get(k, default))
return result | 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``, 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`` is true.
"""
result = []
for k in l:
if raise_if_missing and k not in d:
raise ValueError("Missing key: " + repr(k))
if omit_if_missing and k not in d:
continue
result.append(d.get(k, default))
return result | [
"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`` is true. | [
"The",
"d",
"dictionary",
"contains",
"a",
"key",
"-",
">",
"value",
"mapping",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L170-L188 | train | 53,008 |
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 use for deleted keys; see below
Returns:
dict: a dictionary of the format ``{k: v}`` where the ``k``/``v`` pairs
are key/value pairs that are absent from ``d1`` and present in ``d2``,
or present in both but with different values (in which case the ``d2``
value is shown). If a key ``k`` is present in ``d1`` but absent in
``d2``, the result dictionary has the entry ``{k: deleted_value}``.
"""
changes = {k: v for k, v in d2.items()
if k not in d1 or d2[k] != d1[k]}
for k in d1.keys():
if k not in d2:
changes[k] = deleted_value
return changes | 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 use for deleted keys; see below
Returns:
dict: a dictionary of the format ``{k: v}`` where the ``k``/``v`` pairs
are key/value pairs that are absent from ``d1`` and present in ``d2``,
or present in both but with different values (in which case the ``d2``
value is shown). If a key ``k`` is present in ``d1`` but absent in
``d2``, the result dictionary has the entry ``{k: deleted_value}``.
"""
changes = {k: v for k, v in d2.items()
if k not in d1 or d2[k] != d1[k]}
for k in d1.keys():
if k not in d2:
changes[k] = deleted_value
return changes | [
"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
are key/value pairs that are absent from ``d1`` and present in ``d2``,
or present in both but with different values (in which case the ``d2``
value is shown). If a key ``k`` is present in ``d1`` but absent in
``d2``, the result dictionary has the entry ``{k: deleted_value}``. | [
"Returns",
"a",
"representation",
"of",
"the",
"changes",
"that",
"need",
"to",
"be",
"made",
"to",
"d1",
"to",
"create",
"d2",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L191-L215 | train | 53,009 |
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 deleted...
keys_to_keep:
... unless they are present in this list.
"""
for k in keys_to_delete:
if k in d and k not in keys_to_keep:
del d[k] | 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 deleted...
keys_to_keep:
... unless they are present in this list.
"""
for k in keys_to_delete:
if k in d and k not in keys_to_keep:
del d[k] | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L218-L234 | train | 53,010 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L58-L66 | train | 53,011 |
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:
self.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:
self.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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L68-L79 | train | 53,012 |
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_pendulum()
# If we were already timing something else, pause that.
if self._stack:
last = self._stack[-1]
self._totaldurations[last] += now - self._starttimes[last]
# Start timing our new thing
if name not in self._starttimes:
self._totaldurations[name] = datetime.timedelta()
self._count[name] = 0
self._starttimes[name] = now
if increment_count:
self._count[name] += 1
self._stack.append(name) | 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_pendulum()
# If we were already timing something else, pause that.
if self._stack:
last = self._stack[-1]
self._totaldurations[last] += now - self._starttimes[last]
# Start timing our new thing
if name not in self._starttimes:
self._totaldurations[name] = datetime.timedelta()
self._count[name] = 0
self._starttimes[name] = now
if increment_count:
self._count[name] += 1
self._stack.append(name) | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L81-L106 | train | 53,013 |
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.stop() when nothing running")
if self._stack[-1] != name:
raise AssertionError(
"MultiTimer.stop({}) when {} is running".format(
repr(name), repr(self._stack[-1])))
# Finish what we were asked to
self._totaldurations[name] += now - self._starttimes[name]
self._stack.pop()
# Now, if we were timing something else before we started "name",
# resume...
if self._stack:
last = self._stack[-1]
self._starttimes[last] = now | 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.stop() when nothing running")
if self._stack[-1] != name:
raise AssertionError(
"MultiTimer.stop({}) when {} is running".format(
repr(name), repr(self._stack[-1])))
# Finish what we were asked to
self._totaldurations[name] += now - self._starttimes[name]
self._stack.pop()
# Now, if we were timing something else before we started "name",
# resume...
if self._stack:
last = self._stack[-1]
self._starttimes[last] = now | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L108-L135 | train | 53,014 |
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._totaldurations.items():
grand_total += duration
log.info("Timing summary:")
summaries = []
for name, duration in self._totaldurations.items():
n = self._count[name]
total_sec = duration.total_seconds()
mean = total_sec / n if n > 0 else None
summaries.append({
'total': total_sec,
'description': (
"- {}: {:.3f} s ({:.2f}%, n={}, mean={:.3f}s)".format(
name,
total_sec,
(100 * total_sec / grand_total.total_seconds()),
n,
mean)),
})
summaries.sort(key=lambda x: x['total'], reverse=True)
for s in summaries:
# noinspection PyTypeChecker
log.info(s["description"])
if not self._totaldurations:
log.info("<no timings recorded>")
unmetered = overall_duration - grand_total
log.info(
"Unmetered time: {:.3f} s ({:.2f}%)",
unmetered.total_seconds(),
100 * unmetered.total_seconds() / overall_duration.total_seconds()
)
log.info("Total time: {:.3f} s", grand_total.total_seconds()) | 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._totaldurations.items():
grand_total += duration
log.info("Timing summary:")
summaries = []
for name, duration in self._totaldurations.items():
n = self._count[name]
total_sec = duration.total_seconds()
mean = total_sec / n if n > 0 else None
summaries.append({
'total': total_sec,
'description': (
"- {}: {:.3f} s ({:.2f}%, n={}, mean={:.3f}s)".format(
name,
total_sec,
(100 * total_sec / grand_total.total_seconds()),
n,
mean)),
})
summaries.sort(key=lambda x: x['total'], reverse=True)
for s in summaries:
# noinspection PyTypeChecker
log.info(s["description"])
if not self._totaldurations:
log.info("<no timings recorded>")
unmetered = overall_duration - grand_total
log.info(
"Unmetered time: {:.3f} s ({:.2f}%)",
unmetered.total_seconds(),
100 * unmetered.total_seconds() / overall_duration.total_seconds()
)
log.info("Total time: {:.3f} s", grand_total.total_seconds()) | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L137-L179 | train | 53,015 |
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)
lonlat *= -1
n = len(lonlat)
if sheet == 'lower':
lonlat = lonlat[::-1]
vertices += list(lonlat)
codes.append(Path.MOVETO)
codes += [Path.LINETO]*(n-1)
plot_patch(ax, vertices, codes, **kwargs) | 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)
lonlat *= -1
n = len(lonlat)
if sheet == 'lower':
lonlat = lonlat[::-1]
vertices += list(lonlat)
codes.append(Path.MOVETO)
codes += [Path.LINETO]*(n-1)
plot_patch(ax, vertices, codes, **kwargs) | [
"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",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/stereonet.py#L21-L39 | train | 53,016 |
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)
plot_patch(ax, vertices, codes, **kwargs) | 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)
plot_patch(ax, vertices, codes, **kwargs) | [
"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",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/stereonet.py#L41-L53 | train | 53,017 |
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
args = [
"ping",
hostname,
"-n", "1", # ping count
"-w", str(timeout_ms), # timeout
]
elif sys.platform.startswith('linux'):
args = [
"ping",
hostname,
"-c", "1", # ping count
"-w", str(timeout_s), # timeout
]
else:
raise AssertionError("Don't know how to ping on this operating system")
proc = subprocess.Popen(args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.communicate()
retcode = proc.returncode
return retcode == 0 | 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
args = [
"ping",
hostname,
"-n", "1", # ping count
"-w", str(timeout_ms), # timeout
]
elif sys.platform.startswith('linux'):
args = [
"ping",
hostname,
"-c", "1", # ping count
"-w", str(timeout_s), # timeout
]
else:
raise AssertionError("Don't know how to ping on this operating system")
proc = subprocess.Popen(args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.communicate()
retcode = proc.returncode
return retcode == 0 | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/network.py#L59-L92 | train | 53,018 |
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, filename)
# urllib.request.urlretrieve(url, filename)
# ... sometimes fails (e.g. downloading
# https://www.openssl.org/source/openssl-1.1.0g.tar.gz under Windows) with:
# ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) # noqa
# ... due to this certificate root problem (probably because OpenSSL
# [used by Python] doesn't play entirely by the same rules as others?):
# https://stackoverflow.com/questions/27804710
# So:
ctx = ssl.create_default_context() # type: ssl.SSLContext
if skip_cert_verify:
log.debug("Skipping SSL certificate check for " + url)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
with urllib.request.urlopen(url, context=ctx) as u, open(filename,
'wb') as f: # noqa
f.write(u.read()) | 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, filename)
# urllib.request.urlretrieve(url, filename)
# ... sometimes fails (e.g. downloading
# https://www.openssl.org/source/openssl-1.1.0g.tar.gz under Windows) with:
# ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) # noqa
# ... due to this certificate root problem (probably because OpenSSL
# [used by Python] doesn't play entirely by the same rules as others?):
# https://stackoverflow.com/questions/27804710
# So:
ctx = ssl.create_default_context() # type: ssl.SSLContext
if skip_cert_verify:
log.debug("Skipping SSL certificate check for " + url)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
with urllib.request.urlopen(url, context=ctx) as u, open(filename,
'wb') as f: # noqa
f.write(u.read()) | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/network.py#L99-L127 | train | 53,019 |
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"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L61-L66 | train | 53,020 |
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)
.encode('ascii', 'ignore') # gets rid of accents
.decode('ascii') # back to a string
) | 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)
.encode('ascii', 'ignore') # gets rid of accents
.decode('ascii') # back to a string
) | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L110-L123 | train | 53,021 |
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_adjust(hspace=0, wspace=0.1)
kw = dict(c="#555555", s=40, alpha=0.5)
#lengths = attitude.pca.singular_values[::-1]
lengths = (A[:,i].max()-A[:,i].min() for i in range(3))
titles = (
"Long cross-section (axis 3 vs. axis 1)",
"Short cross-section (axis 3 vs. axis 2)")
for title,ax,(a,b) in zip(titles,axes,
[(0,2),(1,2)]):
seaborn.regplot(A[:,a], A[:,b], ax=ax)
ax.text(0,1,title,
verticalalignment='top',
transform=ax.transAxes)
ax.autoscale(tight=True)
for spine in ax.spines.itervalues():
spine.set_visible(False)
ax.set_xlabel("Meters")
return fig | 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_adjust(hspace=0, wspace=0.1)
kw = dict(c="#555555", s=40, alpha=0.5)
#lengths = attitude.pca.singular_values[::-1]
lengths = (A[:,i].max()-A[:,i].min() for i in range(3))
titles = (
"Long cross-section (axis 3 vs. axis 1)",
"Short cross-section (axis 3 vs. axis 2)")
for title,ax,(a,b) in zip(titles,axes,
[(0,2),(1,2)]):
seaborn.regplot(A[:,a], A[:,b], ax=ax)
ax.text(0,1,title,
verticalalignment='top',
transform=ax.transAxes)
ax.autoscale(tight=True)
for spine in ax.spines.itervalues():
spine.set_visible(False)
ax.set_xlabel("Meters")
return fig | [
"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",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/misc.py#L6-L37 | train | 53,022 |
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"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/metro_wordcount.py#L96-L99 | train | 53,023 |
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"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/metro_wordcount.py#L124-L130 | train | 53,024 |
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 one side of the relationship when adding a peer.
"""
relationship, created = IntersectRelationship.objects.update_or_create(
from_division=self,
to_division=division,
defaults={"intersection": intersection},
)
if symm:
division.add_intersecting(self, None, False)
return relationship | 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 one side of the relationship when adding a peer.
"""
relationship, created = IntersectRelationship.objects.update_or_create(
from_division=self,
to_division=division,
defaults={"intersection": intersection},
)
if symm:
division.add_intersecting(self, None, False)
return relationship | [
"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",
"."
] | 032b3ee773b50b65cfe672f230dda772df0f89e0 | https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L84-L99 | train | 53,025 |
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"
] | 032b3ee773b50b65cfe672f230dda772df0f89e0 | https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L101-L107 | train | 53,026 |
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",
"."
] | 032b3ee773b50b65cfe672f230dda772df0f89e0 | https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L109-L113 | train | 53,027 |
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("No intersecting relationship with that division.") | 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("No intersecting relationship with that division.") | [
"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",
"."
] | 032b3ee773b50b65cfe672f230dda772df0f89e0 | https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L115-L122 | train | 53,028 |
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_name, include_categories=include_categories)
if drug is not None:
return drug.generic_name
return default if unknown_to_default else drug_name | 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_name, include_categories=include_categories)
if drug is not None:
return drug.generic_name
return default if unknown_to_default else drug_name | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1324-L1334 | train | 53,029 |
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 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. the ``default`` parameter and storing
results in a ``data.table()`` character column:
.. code-block:: none
------------------------------ ----------------
To Python Back from Python
------------------------------ ----------------
[not passed, so Python None] "NULL"
NULL "NULL"
NA_character_ "NA"
NA TRUE (logical)
------------------------------ ----------------
"""
return [
drug_name_to_generic(drug,
unknown_to_default=unknown_to_default,
default=default,
include_categories=include_categories)
for drug in drugs
] | 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 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. the ``default`` parameter and storing
results in a ``data.table()`` character column:
.. code-block:: none
------------------------------ ----------------
To Python Back from Python
------------------------------ ----------------
[not passed, so Python None] "NULL"
NULL "NULL"
NA_character_ "NA"
NA TRUE (logical)
------------------------------ ----------------
"""
return [
drug_name_to_generic(drug,
unknown_to_default=unknown_to_default,
default=default,
include_categories=include_categories)
for drug in drugs
] | [
"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. the ``default`` parameter and storing
results in a ``data.table()`` character column:
.. code-block:: none
------------------------------ ----------------
To Python Back from Python
------------------------------ ----------------
[not passed, so Python None] "NULL"
NULL "NULL"
NA_character_ "NA"
NA TRUE (logical)
------------------------------ ---------------- | [
"Converts",
"a",
"list",
"of",
"drug",
"names",
"to",
"their",
"generic",
"equivalents",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1337-L1369 | train | 53,030 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L519-L526 | train | 53,031 |
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 works for current built-in regular expressions.
Args:
regex_text: regular expression text to work with
single_wildcard: SQL single wildcard, typically an underscore
zero_or_more_wildcard: SQL "zero/one/many" wildcard, probably always
a percent symbol
Returns:
string for an SQL string literal
Raises:
:exc:`ValueError` for some regex text that it doesn't understand
properly
"""
def append_to_all(new_content: str) -> None:
nonlocal results
results = [r + new_content for r in results]
def split_and_append(new_options: List[str]) -> None:
nonlocal results
newresults = [] # type: List[str]
for option in new_options:
newresults.extend([r + option for r in results])
results = newresults
def deduplicate_wildcards(text: str) -> str:
while zero_or_more_wildcard + zero_or_more_wildcard in text:
text = text.replace(
zero_or_more_wildcard + zero_or_more_wildcard,
zero_or_more_wildcard)
return text
# Basic processing
working = regex_text # strings are immutable
results = [zero_or_more_wildcard] # start with a wildcard
while working:
if working.startswith(".*"):
# e.g. ".*ozapi"
append_to_all(zero_or_more_wildcard)
working = working[2:]
elif working.startswith("["):
# e.g. "[io]peridol"
close_bracket = working.index("]") # may raise
bracketed = working[1:close_bracket]
option_groups = bracketed.split("|")
options = [c for group in option_groups for c in group]
split_and_append(options)
working = working[close_bracket + 1:]
elif len(working) > 1 and working[1] == "?":
# e.g. "r?azole"
split_and_append(["", working[0]])
# ... regex "optional character"
# ... SQL: some results with a single wildcard, some without
working = working[2:]
elif working.startswith("."):
# single character wildcard
append_to_all(single_wildcard)
working = working[1:]
else:
append_to_all(working[0])
working = working[1:]
append_to_all(zero_or_more_wildcard) # end with a wildcard
# Remove any duplicate (consecutive) % wildcards:
results = [deduplicate_wildcards(r) for r in results]
# Done
return results | 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 works for current built-in regular expressions.
Args:
regex_text: regular expression text to work with
single_wildcard: SQL single wildcard, typically an underscore
zero_or_more_wildcard: SQL "zero/one/many" wildcard, probably always
a percent symbol
Returns:
string for an SQL string literal
Raises:
:exc:`ValueError` for some regex text that it doesn't understand
properly
"""
def append_to_all(new_content: str) -> None:
nonlocal results
results = [r + new_content for r in results]
def split_and_append(new_options: List[str]) -> None:
nonlocal results
newresults = [] # type: List[str]
for option in new_options:
newresults.extend([r + option for r in results])
results = newresults
def deduplicate_wildcards(text: str) -> str:
while zero_or_more_wildcard + zero_or_more_wildcard in text:
text = text.replace(
zero_or_more_wildcard + zero_or_more_wildcard,
zero_or_more_wildcard)
return text
# Basic processing
working = regex_text # strings are immutable
results = [zero_or_more_wildcard] # start with a wildcard
while working:
if working.startswith(".*"):
# e.g. ".*ozapi"
append_to_all(zero_or_more_wildcard)
working = working[2:]
elif working.startswith("["):
# e.g. "[io]peridol"
close_bracket = working.index("]") # may raise
bracketed = working[1:close_bracket]
option_groups = bracketed.split("|")
options = [c for group in option_groups for c in group]
split_and_append(options)
working = working[close_bracket + 1:]
elif len(working) > 1 and working[1] == "?":
# e.g. "r?azole"
split_and_append(["", working[0]])
# ... regex "optional character"
# ... SQL: some results with a single wildcard, some without
working = working[2:]
elif working.startswith("."):
# single character wildcard
append_to_all(single_wildcard)
working = working[1:]
else:
append_to_all(working[0])
working = working[1:]
append_to_all(zero_or_more_wildcard) # end with a wildcard
# Remove any duplicate (consecutive) % wildcards:
results = [deduplicate_wildcards(r) for r in results]
# Done
return results | [
"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 underscore
zero_or_more_wildcard: SQL "zero/one/many" wildcard, probably always
a percent symbol
Returns:
string for an SQL string literal
Raises:
:exc:`ValueError` for some regex text that it doesn't understand
properly | [
"Converts",
"regular",
"expression",
"text",
"to",
"a",
"reasonably",
"close",
"fragment",
"for",
"the",
"SQL",
"LIKE",
"operator",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L529-L605 | train | 53,032 |
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 ``%``.
"""
if self._sql_like_fragments is None:
self._sql_like_fragments = []
for p in list(set(self.all_generics + self.alternatives)):
self._sql_like_fragments.extend(self.regex_to_sql_like(p))
return self._sql_like_fragments | 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 ``%``.
"""
if self._sql_like_fragments is None:
self._sql_like_fragments = []
for p in list(set(self.all_generics + self.alternatives)):
self._sql_like_fragments.extend(self.regex_to_sql_like(p))
return self._sql_like_fragments | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L608-L621 | train | 53,033 |
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: column name, pre-escaped if necessary
Returns:
SQL fragment as above
"""
clauses = [
"{col} LIKE {fragment}".format(
col=column_name,
fragment=sql_string_literal(f))
for f in self.sql_like_fragments
]
return "({})".format(" OR ".join(clauses)) | 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: column name, pre-escaped if necessary
Returns:
SQL fragment as above
"""
clauses = [
"{col} LIKE {fragment}".format(
col=column_name,
fragment=sql_string_literal(f))
for f in self.sql_like_fragments
]
return "({})".format(" OR ".join(clauses)) | [
"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 fragment as above | [
"Returns",
"SQL",
"like"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L633-L657 | train | 53,034 |
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"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L7-L11 | train | 53,035 |
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 circle
return N.array([N.cos(u),N.sin(u)]).T | 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 circle
return N.array([N.cos(u),N.sin(u)]).T | [
"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",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L13-L23 | train | 53,036 |
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"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L33-L40 | train | 53,037 |
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 *= -1
# Not sure where this factor comes from but it
# seems to make things work better
c1 = 2
axis_lengths = d[:2]
f = N.linalg.norm(
ell*axis_lengths,axis=1)
e0 = -ell.T*d[2]*c1
e = N.vstack((e0,f))
_ = dot(e.T,axes).T
if traditional_layout:
lon,lat = stereonet_math.cart2sph(_[2],_[0],-_[1])
else:
lon,lat = stereonet_math.cart2sph(-_[1],_[0],_[2])
return list(zip(lon,lat)) | 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 *= -1
# Not sure where this factor comes from but it
# seems to make things work better
c1 = 2
axis_lengths = d[:2]
f = N.linalg.norm(
ell*axis_lengths,axis=1)
e0 = -ell.T*d[2]*c1
e = N.vstack((e0,f))
_ = dot(e.T,axes).T
if traditional_layout:
lon,lat = stereonet_math.cart2sph(_[2],_[0],-_[1])
else:
lon,lat = stereonet_math.cart2sph(-_[1],_[0],_[2])
return list(zip(lon,lat)) | [
"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"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L42-L70 | train | 53,038 |
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_matrix))
u = N.linspace(0, 2*N.pi, n)
scales = dict(upper=1,lower=-1,nominal=0)
c1 = scales[sheet]
c1 *= -1 # We assume upper hemisphere
if axes[2,2] < 0:
c1 *= -1
def sdot(a,b):
return sum([i*j for i,j in zip(a,b)])
def step_func(a):
e = [
N.cos(a)*cov[0],
N.sin(a)*cov[1],
c1*cov[2]]
d = [sdot(e,i)
for i in axes.T]
x,y,z = d[2],d[0],d[1]
r = N.sqrt(x**2 + y**2 + z**2)
lat = N.arcsin(z/r)
lon = N.arctan2(y, x)
return lon,lat
# Get a bundle of vectors defining
# a full rotation around the unit circle
return N.array([step_func(i)
for i in u]) | 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_matrix))
u = N.linspace(0, 2*N.pi, n)
scales = dict(upper=1,lower=-1,nominal=0)
c1 = scales[sheet]
c1 *= -1 # We assume upper hemisphere
if axes[2,2] < 0:
c1 *= -1
def sdot(a,b):
return sum([i*j for i,j in zip(a,b)])
def step_func(a):
e = [
N.cos(a)*cov[0],
N.sin(a)*cov[1],
c1*cov[2]]
d = [sdot(e,i)
for i in axes.T]
x,y,z = d[2],d[0],d[1]
r = N.sqrt(x**2 + y**2 + z**2)
lat = N.arcsin(z/r)
lon = N.arctan2(y, x)
return lon,lat
# Get a bundle of vectors defining
# a full rotation around the unit circle
return N.array([step_func(i)
for i in u]) | [
"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",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L156-L193 | train | 53,039 |
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(topojson) | 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(topojson) | [
"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",
"."
] | 032b3ee773b50b65cfe672f230dda772df0f89e0 | https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/geometry.py#L124-L131 | train | 53,040 |
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.group('port')
_scheme, _netloc, path, query, _fragment = tuple(py_urlsplit(url))
return scheme, host, port, path, query | 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.group('port')
_scheme, _netloc, path, query, _fragment = tuple(py_urlsplit(url))
return scheme, host, port, path, query | [
"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"
] | 7ba4273a05c40e2e338f49f2dd564920ed98fcab | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/urls.py#L6-L21 | train | 53,041 |
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
if host is not None:
url += host
if port is not None:
url += ":%s" % str(port)
if path is not None:
url += ensure_url_path_starts_with_slash(path)
if query is not None:
url += "?%s" % (urlencode(query))
return url | 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
if host is not None:
url += host
if port is not None:
url += ":%s" % str(port)
if path is not None:
url += ensure_url_path_starts_with_slash(path)
if query is not None:
url += "?%s" % (urlencode(query))
return url | [
"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",
"."
] | 7ba4273a05c40e2e338f49f2dd564920ed98fcab | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/urls.py#L60-L82 | train | 53,042 |
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, url))
tmp = self.download(self.output, url, self.overwrite)
self.s3.store(self.extract(tmp, self.tmp2poi(tmp))) | 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, url))
tmp = self.download(self.output, url, self.overwrite)
self.s3.store(self.extract(tmp, self.tmp2poi(tmp))) | [
"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"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L37-L45 | train | 53,043 |
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):
for node in nodes:
node_id, tags, coordinates = node
# if any tags have a matching key then write record
if any([t in tags for t in POI_TAGS]):
f.write(json.dumps(dict(tags=tags, coordinates=coordinates)))
f.write('\n')
parser = OSMParser(concurrency=4, nodes_callback=nodes_callback)
parser.parse(pbf)
return output | 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):
for node in nodes:
node_id, tags, coordinates = node
# if any tags have a matching key then write record
if any([t in tags for t in POI_TAGS]):
f.write(json.dumps(dict(tags=tags, coordinates=coordinates)))
f.write('\n')
parser = OSMParser(concurrency=4, nodes_callback=nodes_callback)
parser.parse(pbf)
return output | [
"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"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L67-L81 | train | 53,044 |
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"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L86-L89 | train | 53,045 |
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 default | 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 default | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/ui.py#L44-L53 | train | 53,046 |
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 positive int".format(value))
return ivalue | 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 positive int".format(value))
return ivalue | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/argparse_func.py#L135-L146 | train | 53,047 |
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"
] | 05e3cbf4e531cc51b4777912eb98a4f006893f5e | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L69-L75 | train | 53,048 |
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, timeout) | 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, timeout) | [
"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"
] | 05e3cbf4e531cc51b4777912eb98a4f006893f5e | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L131-L137 | train | 53,049 |
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)
defer.returnValue(json.loads(body)) | 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)
defer.returnValue(json.loads(body)) | [
"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"
] | 05e3cbf4e531cc51b4777912eb98a4f006893f5e | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L141-L149 | train | 53,050 |
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"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/__init__.py#L7-L15 | train | 53,051 |
davenquinn/Attitude | attitude/geom/__init__.py | fit_angle | def fit_angle(fit1, fit2, degrees=True):
"""
Finds the angle between the nominal vectors
"""
return N.degrees(angle(fit1.normal,fit2.normal)) | python | def fit_angle(fit1, fit2, degrees=True):
"""
Finds the angle between the nominal vectors
"""
return N.degrees(angle(fit1.normal,fit2.normal)) | [
"def",
"fit_angle",
"(",
"fit1",
",",
"fit2",
",",
"degrees",
"=",
"True",
")",
":",
"return",
"N",
".",
"degrees",
"(",
"angle",
"(",
"fit1",
".",
"normal",
",",
"fit2",
".",
"normal",
")",
")"
] | Finds the angle between the nominal vectors | [
"Finds",
"the",
"angle",
"between",
"the",
"nominal",
"vectors"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/__init__.py#L17-L21 | train | 53,052 |
davenquinn/Attitude | attitude/geom/__init__.py | fit_similarity | def fit_similarity(fit1, fit2):
"""
Distance apart for vectors, given in
standard deviations
"""
cov1 = aligned_covariance(fit1)
cov2 = aligned_covariance(fit2)
if fit2.axes[2,2] < 0:
cov2 *= -1
v0 = fit1.normal-fit2.normal
cov0 = cov1+cov2 # Axes are aligned, so no covariances
# Find distance of point from center
# Decompose covariance matrix
U,s,V = N.linalg.svd(cov0)
rotated = dot(V,v0) # rotate vector into PCA space
val = rotated**2/N.sqrt(s)
return N.sqrt(val.sum()) | python | def fit_similarity(fit1, fit2):
"""
Distance apart for vectors, given in
standard deviations
"""
cov1 = aligned_covariance(fit1)
cov2 = aligned_covariance(fit2)
if fit2.axes[2,2] < 0:
cov2 *= -1
v0 = fit1.normal-fit2.normal
cov0 = cov1+cov2 # Axes are aligned, so no covariances
# Find distance of point from center
# Decompose covariance matrix
U,s,V = N.linalg.svd(cov0)
rotated = dot(V,v0) # rotate vector into PCA space
val = rotated**2/N.sqrt(s)
return N.sqrt(val.sum()) | [
"def",
"fit_similarity",
"(",
"fit1",
",",
"fit2",
")",
":",
"cov1",
"=",
"aligned_covariance",
"(",
"fit1",
")",
"cov2",
"=",
"aligned_covariance",
"(",
"fit2",
")",
"if",
"fit2",
".",
"axes",
"[",
"2",
",",
"2",
"]",
"<",
"0",
":",
"cov2",
"*=",
... | Distance apart for vectors, given in
standard deviations | [
"Distance",
"apart",
"for",
"vectors",
"given",
"in",
"standard",
"deviations"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/__init__.py#L23-L41 | train | 53,053 |
RudolfCardinal/pythonlib | cardinal_pythonlib/plot.py | png_img_html_from_pyplot_figure | def png_img_html_from_pyplot_figure(fig: "Figure",
dpi: int = 100,
extra_html_class: str = None) -> str:
"""
Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG.
"""
if fig is None:
return ""
# Make a file-like object
memfile = io.BytesIO()
# In general, can do
# fig.savefig(filename/file-like-object/backend, format=...)
# or
# backend.savefig(fig):
# see e.g. http://matplotlib.org/api/backend_pdf_api.html
fig.savefig(memfile, format="png", dpi=dpi)
memfile.seek(0)
pngblob = memoryview(memfile.read())
return rnc_web.get_png_img_html(pngblob, extra_html_class) | python | def png_img_html_from_pyplot_figure(fig: "Figure",
dpi: int = 100,
extra_html_class: str = None) -> str:
"""
Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG.
"""
if fig is None:
return ""
# Make a file-like object
memfile = io.BytesIO()
# In general, can do
# fig.savefig(filename/file-like-object/backend, format=...)
# or
# backend.savefig(fig):
# see e.g. http://matplotlib.org/api/backend_pdf_api.html
fig.savefig(memfile, format="png", dpi=dpi)
memfile.seek(0)
pngblob = memoryview(memfile.read())
return rnc_web.get_png_img_html(pngblob, extra_html_class) | [
"def",
"png_img_html_from_pyplot_figure",
"(",
"fig",
":",
"\"Figure\"",
",",
"dpi",
":",
"int",
"=",
"100",
",",
"extra_html_class",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"fig",
"is",
"None",
":",
"return",
"\"\"",
"# Make a file-like object... | Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG. | [
"Converts",
"a",
"pyplot",
"figure",
"to",
"an",
"HTML",
"IMG",
"tag",
"with",
"encapsulated",
"PNG",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/plot.py#L52-L70 | train | 53,054 |
RudolfCardinal/pythonlib | cardinal_pythonlib/plot.py | svg_html_from_pyplot_figure | def svg_html_from_pyplot_figure(fig: "Figure") -> str:
"""
Converts a ``pyplot`` figure to an SVG tag.
"""
if fig is None:
return ""
memfile = io.BytesIO() # StringIO doesn't like mixing str/unicode
fig.savefig(memfile, format="svg")
return memfile.getvalue().decode("utf-8") | python | def svg_html_from_pyplot_figure(fig: "Figure") -> str:
"""
Converts a ``pyplot`` figure to an SVG tag.
"""
if fig is None:
return ""
memfile = io.BytesIO() # StringIO doesn't like mixing str/unicode
fig.savefig(memfile, format="svg")
return memfile.getvalue().decode("utf-8") | [
"def",
"svg_html_from_pyplot_figure",
"(",
"fig",
":",
"\"Figure\"",
")",
"->",
"str",
":",
"if",
"fig",
"is",
"None",
":",
"return",
"\"\"",
"memfile",
"=",
"io",
".",
"BytesIO",
"(",
")",
"# StringIO doesn't like mixing str/unicode",
"fig",
".",
"savefig",
"... | Converts a ``pyplot`` figure to an SVG tag. | [
"Converts",
"a",
"pyplot",
"figure",
"to",
"an",
"SVG",
"tag",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/plot.py#L73-L81 | train | 53,055 |
RudolfCardinal/pythonlib | cardinal_pythonlib/plot.py | set_matplotlib_fontsize | def set_matplotlib_fontsize(matplotlib: ModuleType,
fontsize: Union[int, float] = 12) -> None:
"""
Sets the current font size within the ``matplotlib`` library.
**WARNING:** not an appropriate method for multithreaded environments, as
it writes (indirectly) to ``matplotlib`` global objects. See CamCOPS for
alternative methods.
"""
font = {
# http://stackoverflow.com/questions/3899980
# http://matplotlib.org/users/customizing.html
'family': 'sans-serif',
# ... serif, sans-serif, cursive, fantasy, monospace
'style': 'normal', # normal (roman), italic, oblique
'variant': 'normal', # normal, small-caps
'weight': 'normal',
# ... normal [=400], bold [=700], bolder [relative to current],
# lighter [relative], 100, 200, 300, ..., 900
'size': fontsize # in pt (default 12)
}
# noinspection PyUnresolvedReferences
matplotlib.rc('font', **font)
legend = {
# http://stackoverflow.com/questions/7125009
'fontsize': fontsize
}
# noinspection PyUnresolvedReferences
matplotlib.rc('legend', **legend) | python | def set_matplotlib_fontsize(matplotlib: ModuleType,
fontsize: Union[int, float] = 12) -> None:
"""
Sets the current font size within the ``matplotlib`` library.
**WARNING:** not an appropriate method for multithreaded environments, as
it writes (indirectly) to ``matplotlib`` global objects. See CamCOPS for
alternative methods.
"""
font = {
# http://stackoverflow.com/questions/3899980
# http://matplotlib.org/users/customizing.html
'family': 'sans-serif',
# ... serif, sans-serif, cursive, fantasy, monospace
'style': 'normal', # normal (roman), italic, oblique
'variant': 'normal', # normal, small-caps
'weight': 'normal',
# ... normal [=400], bold [=700], bolder [relative to current],
# lighter [relative], 100, 200, 300, ..., 900
'size': fontsize # in pt (default 12)
}
# noinspection PyUnresolvedReferences
matplotlib.rc('font', **font)
legend = {
# http://stackoverflow.com/questions/7125009
'fontsize': fontsize
}
# noinspection PyUnresolvedReferences
matplotlib.rc('legend', **legend) | [
"def",
"set_matplotlib_fontsize",
"(",
"matplotlib",
":",
"ModuleType",
",",
"fontsize",
":",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"12",
")",
"->",
"None",
":",
"font",
"=",
"{",
"# http://stackoverflow.com/questions/3899980",
"# http://matplotlib.org/users/... | Sets the current font size within the ``matplotlib`` library.
**WARNING:** not an appropriate method for multithreaded environments, as
it writes (indirectly) to ``matplotlib`` global objects. See CamCOPS for
alternative methods. | [
"Sets",
"the",
"current",
"font",
"size",
"within",
"the",
"matplotlib",
"library",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/plot.py#L89-L117 | train | 53,056 |
Autodesk/cryptorito | cryptorito/cli.py | encrypt_file | def encrypt_file(src, dest, csv_keys):
"""Encrypt a file with the specific GPG keys and write out
to the specified path"""
keys = massage_keys(csv_keys.split(','))
cryptorito.encrypt(src, dest, keys) | python | def encrypt_file(src, dest, csv_keys):
"""Encrypt a file with the specific GPG keys and write out
to the specified path"""
keys = massage_keys(csv_keys.split(','))
cryptorito.encrypt(src, dest, keys) | [
"def",
"encrypt_file",
"(",
"src",
",",
"dest",
",",
"csv_keys",
")",
":",
"keys",
"=",
"massage_keys",
"(",
"csv_keys",
".",
"split",
"(",
"','",
")",
")",
"cryptorito",
".",
"encrypt",
"(",
"src",
",",
"dest",
",",
"keys",
")"
] | Encrypt a file with the specific GPG keys and write out
to the specified path | [
"Encrypt",
"a",
"file",
"with",
"the",
"specific",
"GPG",
"keys",
"and",
"write",
"out",
"to",
"the",
"specified",
"path"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L21-L25 | train | 53,057 |
Autodesk/cryptorito | cryptorito/cli.py | encrypt_var | def encrypt_var(csv_keys):
"""Encrypt what comes in from stdin and return base64
encrypted against the specified keys, returning on stdout"""
keys = massage_keys(csv_keys.split(','))
data = sys.stdin.read()
encrypted = cryptorito.encrypt_var(data, keys)
print(cryptorito.portable_b64encode(encrypted)) | python | def encrypt_var(csv_keys):
"""Encrypt what comes in from stdin and return base64
encrypted against the specified keys, returning on stdout"""
keys = massage_keys(csv_keys.split(','))
data = sys.stdin.read()
encrypted = cryptorito.encrypt_var(data, keys)
print(cryptorito.portable_b64encode(encrypted)) | [
"def",
"encrypt_var",
"(",
"csv_keys",
")",
":",
"keys",
"=",
"massage_keys",
"(",
"csv_keys",
".",
"split",
"(",
"','",
")",
")",
"data",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"encrypted",
"=",
"cryptorito",
".",
"encrypt_var",
"(",
"data",... | Encrypt what comes in from stdin and return base64
encrypted against the specified keys, returning on stdout | [
"Encrypt",
"what",
"comes",
"in",
"from",
"stdin",
"and",
"return",
"base64",
"encrypted",
"against",
"the",
"specified",
"keys",
"returning",
"on",
"stdout"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L33-L39 | train | 53,058 |
Autodesk/cryptorito | cryptorito/cli.py | import_keybase | def import_keybase(useropt):
"""Imports a public GPG key from Keybase"""
public_key = None
u_bits = useropt.split(':')
username = u_bits[0]
if len(u_bits) == 1:
public_key = cryptorito.key_from_keybase(username)
else:
fingerprint = u_bits[1]
public_key = cryptorito.key_from_keybase(username, fingerprint)
if cryptorito.has_gpg_key(public_key['fingerprint']):
sys.exit(2)
cryptorito.import_gpg_key(public_key['bundle'].encode('ascii'))
sys.exit(0) | python | def import_keybase(useropt):
"""Imports a public GPG key from Keybase"""
public_key = None
u_bits = useropt.split(':')
username = u_bits[0]
if len(u_bits) == 1:
public_key = cryptorito.key_from_keybase(username)
else:
fingerprint = u_bits[1]
public_key = cryptorito.key_from_keybase(username, fingerprint)
if cryptorito.has_gpg_key(public_key['fingerprint']):
sys.exit(2)
cryptorito.import_gpg_key(public_key['bundle'].encode('ascii'))
sys.exit(0) | [
"def",
"import_keybase",
"(",
"useropt",
")",
":",
"public_key",
"=",
"None",
"u_bits",
"=",
"useropt",
".",
"split",
"(",
"':'",
")",
"username",
"=",
"u_bits",
"[",
"0",
"]",
"if",
"len",
"(",
"u_bits",
")",
"==",
"1",
":",
"public_key",
"=",
"cryp... | Imports a public GPG key from Keybase | [
"Imports",
"a",
"public",
"GPG",
"key",
"from",
"Keybase"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L57-L72 | train | 53,059 |
Autodesk/cryptorito | cryptorito/cli.py | do_thing | def do_thing():
"""Execute command line cryptorito actions"""
if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file":
encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4])
elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file":
decrypt_file(sys.argv[2], sys.argv[3])
elif len(sys.argv) == 3 and sys.argv[1] == "encrypt":
encrypt_var(sys.argv[2])
elif len(sys.argv) == 2 and sys.argv[1] == "decrypt":
decrypt_var()
elif len(sys.argv) == 3 and sys.argv[1] == "decrypt":
decrypt_var(passphrase=sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "has_key":
has_key(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "import_keybase":
import_keybase(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "export":
export_key(sys.argv[2])
else:
print("Cryptorito testing wrapper. Not suitable for routine use.",
file=sys.stderr)
sys.exit(1) | python | def do_thing():
"""Execute command line cryptorito actions"""
if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file":
encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4])
elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file":
decrypt_file(sys.argv[2], sys.argv[3])
elif len(sys.argv) == 3 and sys.argv[1] == "encrypt":
encrypt_var(sys.argv[2])
elif len(sys.argv) == 2 and sys.argv[1] == "decrypt":
decrypt_var()
elif len(sys.argv) == 3 and sys.argv[1] == "decrypt":
decrypt_var(passphrase=sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "has_key":
has_key(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "import_keybase":
import_keybase(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "export":
export_key(sys.argv[2])
else:
print("Cryptorito testing wrapper. Not suitable for routine use.",
file=sys.stderr)
sys.exit(1) | [
"def",
"do_thing",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"5",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"encrypt_file\"",
":",
"encrypt_file",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
",",
"sys",
".",
"argv",
"[... | Execute command line cryptorito actions | [
"Execute",
"command",
"line",
"cryptorito",
"actions"
] | 277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85 | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L81-L102 | train | 53,060 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_monochrome_handler | def get_monochrome_handler(
extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a monochrome log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler`
"""
fmt = "%(asctime)s.%(msecs)03d"
if with_process_id or with_thread_id:
procinfo = [] # type: List[str]
if with_process_id:
procinfo.append("p%(process)d")
if with_thread_id:
procinfo.append("t%(thread)d")
fmt += " [{}]".format(".".join(procinfo))
extras = ":" + ":".join(extranames) if extranames else ""
fmt += " %(name)s{extras}:%(levelname)s: ".format(extras=extras)
fmt += "%(message)s"
f = logging.Formatter(fmt, datefmt=LOG_DATEFMT, style='%')
h = logging.StreamHandler(stream)
h.setFormatter(f)
return h | python | def get_monochrome_handler(
extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a monochrome log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler`
"""
fmt = "%(asctime)s.%(msecs)03d"
if with_process_id or with_thread_id:
procinfo = [] # type: List[str]
if with_process_id:
procinfo.append("p%(process)d")
if with_thread_id:
procinfo.append("t%(thread)d")
fmt += " [{}]".format(".".join(procinfo))
extras = ":" + ":".join(extranames) if extranames else ""
fmt += " %(name)s{extras}:%(levelname)s: ".format(extras=extras)
fmt += "%(message)s"
f = logging.Formatter(fmt, datefmt=LOG_DATEFMT, style='%')
h = logging.StreamHandler(stream)
h.setFormatter(f)
return h | [
"def",
"get_monochrome_handler",
"(",
"extranames",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"with_process_id",
":",
"bool",
"=",
"False",
",",
"with_thread_id",
":",
"bool",
"=",
"False",
",",
"stream",
":",
"TextIO",
"=",
"None",
")",
"->",
"log... | Gets a monochrome log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler` | [
"Gets",
"a",
"monochrome",
"log",
"handler",
"using",
"a",
"standard",
"format",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L105-L137 | train | 53,061 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_colour_handler | def get_colour_handler(extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a colour log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler`
"""
fmt = "%(white)s%(asctime)s.%(msecs)03d" # this is dim white = grey
if with_process_id or with_thread_id:
procinfo = [] # type: List[str]
if with_process_id:
procinfo.append("p%(process)d")
if with_thread_id:
procinfo.append("t%(thread)d")
fmt += " [{}]".format(".".join(procinfo))
extras = ":" + ":".join(extranames) if extranames else ""
fmt += " %(name)s{extras}:%(levelname)s: ".format(extras=extras)
fmt += "%(reset)s%(log_color)s%(message)s"
cf = ColoredFormatter(fmt,
datefmt=LOG_DATEFMT,
reset=True,
log_colors=LOG_COLORS,
secondary_log_colors={},
style='%')
ch = logging.StreamHandler(stream)
ch.setFormatter(cf)
return ch | python | def get_colour_handler(extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a colour log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler`
"""
fmt = "%(white)s%(asctime)s.%(msecs)03d" # this is dim white = grey
if with_process_id or with_thread_id:
procinfo = [] # type: List[str]
if with_process_id:
procinfo.append("p%(process)d")
if with_thread_id:
procinfo.append("t%(thread)d")
fmt += " [{}]".format(".".join(procinfo))
extras = ":" + ":".join(extranames) if extranames else ""
fmt += " %(name)s{extras}:%(levelname)s: ".format(extras=extras)
fmt += "%(reset)s%(log_color)s%(message)s"
cf = ColoredFormatter(fmt,
datefmt=LOG_DATEFMT,
reset=True,
log_colors=LOG_COLORS,
secondary_log_colors={},
style='%')
ch = logging.StreamHandler(stream)
ch.setFormatter(cf)
return ch | [
"def",
"get_colour_handler",
"(",
"extranames",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"with_process_id",
":",
"bool",
"=",
"False",
",",
"with_thread_id",
":",
"bool",
"=",
"False",
",",
"stream",
":",
"TextIO",
"=",
"None",
")",
"->",
"logging... | Gets a colour log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler` | [
"Gets",
"a",
"colour",
"log",
"handler",
"using",
"a",
"standard",
"format",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L140-L176 | train | 53,062 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | main_only_quicksetup_rootlogger | def main_only_quicksetup_rootlogger(level: int = logging.DEBUG,
with_process_id: bool = False,
with_thread_id: bool = False) -> None:
"""
Quick function to set up the root logger for colour.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
level: log level to set
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
"""
# Nasty. Only call from "if __name__ == '__main__'" clauses!
rootlogger = logging.getLogger()
configure_logger_for_colour(rootlogger, level, remove_existing=True,
with_process_id=with_process_id,
with_thread_id=with_thread_id) | python | def main_only_quicksetup_rootlogger(level: int = logging.DEBUG,
with_process_id: bool = False,
with_thread_id: bool = False) -> None:
"""
Quick function to set up the root logger for colour.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
level: log level to set
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
"""
# Nasty. Only call from "if __name__ == '__main__'" clauses!
rootlogger = logging.getLogger()
configure_logger_for_colour(rootlogger, level, remove_existing=True,
with_process_id=with_process_id,
with_thread_id=with_thread_id) | [
"def",
"main_only_quicksetup_rootlogger",
"(",
"level",
":",
"int",
"=",
"logging",
".",
"DEBUG",
",",
"with_process_id",
":",
"bool",
"=",
"False",
",",
"with_thread_id",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"# Nasty. Only call from \"if __name__ ==... | Quick function to set up the root logger for colour.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
level: log level to set
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name? | [
"Quick",
"function",
"to",
"set",
"up",
"the",
"root",
"logger",
"for",
"colour",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L209-L227 | train | 53,063 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | remove_all_logger_handlers | def remove_all_logger_handlers(logger: logging.Logger) -> None:
"""
Remove all handlers from a logger.
Args:
logger: logger to modify
"""
while logger.handlers:
h = logger.handlers[0]
logger.removeHandler(h) | python | def remove_all_logger_handlers(logger: logging.Logger) -> None:
"""
Remove all handlers from a logger.
Args:
logger: logger to modify
"""
while logger.handlers:
h = logger.handlers[0]
logger.removeHandler(h) | [
"def",
"remove_all_logger_handlers",
"(",
"logger",
":",
"logging",
".",
"Logger",
")",
"->",
"None",
":",
"while",
"logger",
".",
"handlers",
":",
"h",
"=",
"logger",
".",
"handlers",
"[",
"0",
"]",
"logger",
".",
"removeHandler",
"(",
"h",
")"
] | Remove all handlers from a logger.
Args:
logger: logger to modify | [
"Remove",
"all",
"handlers",
"from",
"a",
"logger",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L235-L244 | train | 53,064 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | reset_logformat | def reset_logformat(logger: logging.Logger,
fmt: str,
datefmt: str = '%Y-%m-%d %H:%M:%S') -> None:
"""
Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the formatter like this.
Args:
logger: logger to modify
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter`
"""
handler = logging.StreamHandler()
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
handler.setFormatter(formatter)
remove_all_logger_handlers(logger)
logger.addHandler(handler)
logger.propagate = False | python | def reset_logformat(logger: logging.Logger,
fmt: str,
datefmt: str = '%Y-%m-%d %H:%M:%S') -> None:
"""
Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the formatter like this.
Args:
logger: logger to modify
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter`
"""
handler = logging.StreamHandler()
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
handler.setFormatter(formatter)
remove_all_logger_handlers(logger)
logger.addHandler(handler)
logger.propagate = False | [
"def",
"reset_logformat",
"(",
"logger",
":",
"logging",
".",
"Logger",
",",
"fmt",
":",
"str",
",",
"datefmt",
":",
"str",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
"->",
"None",
":",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"... | Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the formatter like this.
Args:
logger: logger to modify
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter` | [
"Create",
"a",
"new",
"formatter",
"and",
"apply",
"it",
"to",
"the",
"logger",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L247-L267 | train | 53,065 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | reset_logformat_timestamped | def reset_logformat_timestamped(logger: logging.Logger,
extraname: str = "",
level: int = logging.INFO) -> None:
"""
Apply a simple time-stamped log format to an existing logger, and set
its loglevel to either ``logging.DEBUG`` or ``logging.INFO``.
Args:
logger: logger to modify
extraname: additional name to append to the logger's name
level: log level to set
"""
namebit = extraname + ":" if extraname else ""
fmt = ("%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:" + namebit +
"%(message)s")
# logger.info(fmt)
reset_logformat(logger, fmt=fmt)
# logger.info(fmt)
logger.setLevel(level) | python | def reset_logformat_timestamped(logger: logging.Logger,
extraname: str = "",
level: int = logging.INFO) -> None:
"""
Apply a simple time-stamped log format to an existing logger, and set
its loglevel to either ``logging.DEBUG`` or ``logging.INFO``.
Args:
logger: logger to modify
extraname: additional name to append to the logger's name
level: log level to set
"""
namebit = extraname + ":" if extraname else ""
fmt = ("%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:" + namebit +
"%(message)s")
# logger.info(fmt)
reset_logformat(logger, fmt=fmt)
# logger.info(fmt)
logger.setLevel(level) | [
"def",
"reset_logformat_timestamped",
"(",
"logger",
":",
"logging",
".",
"Logger",
",",
"extraname",
":",
"str",
"=",
"\"\"",
",",
"level",
":",
"int",
"=",
"logging",
".",
"INFO",
")",
"->",
"None",
":",
"namebit",
"=",
"extraname",
"+",
"\":\"",
"if",... | Apply a simple time-stamped log format to an existing logger, and set
its loglevel to either ``logging.DEBUG`` or ``logging.INFO``.
Args:
logger: logger to modify
extraname: additional name to append to the logger's name
level: log level to set | [
"Apply",
"a",
"simple",
"time",
"-",
"stamped",
"log",
"format",
"to",
"an",
"existing",
"logger",
"and",
"set",
"its",
"loglevel",
"to",
"either",
"logging",
".",
"DEBUG",
"or",
"logging",
".",
"INFO",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L270-L288 | train | 53,066 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_formatter_report | def get_formatter_report(f: logging.Formatter) -> Optional[Dict[str, str]]:
"""
Returns information on a log formatter, as a dictionary.
For debugging.
"""
if f is None:
return None
return {
'_fmt': f._fmt,
'datefmt': f.datefmt,
'_style': str(f._style),
} | python | def get_formatter_report(f: logging.Formatter) -> Optional[Dict[str, str]]:
"""
Returns information on a log formatter, as a dictionary.
For debugging.
"""
if f is None:
return None
return {
'_fmt': f._fmt,
'datefmt': f.datefmt,
'_style': str(f._style),
} | [
"def",
"get_formatter_report",
"(",
"f",
":",
"logging",
".",
"Formatter",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"if",
"f",
"is",
"None",
":",
"return",
"None",
"return",
"{",
"'_fmt'",
":",
"f",
".",
"_fmt",
",... | Returns information on a log formatter, as a dictionary.
For debugging. | [
"Returns",
"information",
"on",
"a",
"log",
"formatter",
"as",
"a",
"dictionary",
".",
"For",
"debugging",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L392-L403 | train | 53,067 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_handler_report | def get_handler_report(h: logging.Handler) -> Dict[str, Any]:
"""
Returns information on a log handler, as a dictionary.
For debugging.
"""
return {
'get_name()': h.get_name(),
'level': h.level,
'formatter': get_formatter_report(h.formatter),
'filters': h.filters,
} | python | def get_handler_report(h: logging.Handler) -> Dict[str, Any]:
"""
Returns information on a log handler, as a dictionary.
For debugging.
"""
return {
'get_name()': h.get_name(),
'level': h.level,
'formatter': get_formatter_report(h.formatter),
'filters': h.filters,
} | [
"def",
"get_handler_report",
"(",
"h",
":",
"logging",
".",
"Handler",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"'get_name()'",
":",
"h",
".",
"get_name",
"(",
")",
",",
"'level'",
":",
"h",
".",
"level",
",",
"'formatter'"... | Returns information on a log handler, as a dictionary.
For debugging. | [
"Returns",
"information",
"on",
"a",
"log",
"handler",
"as",
"a",
"dictionary",
".",
"For",
"debugging",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L406-L416 | train | 53,068 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_log_report | def get_log_report(log: Union[logging.Logger,
logging.PlaceHolder]) -> Dict[str, Any]:
"""
Returns information on a log, as a dictionary. For debugging.
"""
if isinstance(log, logging.Logger):
# suppress invalid error for Logger.manager:
# noinspection PyUnresolvedReferences
return {
'(object)': str(log),
'level': log.level,
'disabled': log.disabled,
'propagate': log.propagate,
'parent': str(log.parent),
'manager': str(log.manager),
'handlers': [get_handler_report(h) for h in log.handlers],
}
elif isinstance(log, logging.PlaceHolder):
return {
"(object)": str(log),
}
else:
raise ValueError("Unknown object type: {!r}".format(log)) | python | def get_log_report(log: Union[logging.Logger,
logging.PlaceHolder]) -> Dict[str, Any]:
"""
Returns information on a log, as a dictionary. For debugging.
"""
if isinstance(log, logging.Logger):
# suppress invalid error for Logger.manager:
# noinspection PyUnresolvedReferences
return {
'(object)': str(log),
'level': log.level,
'disabled': log.disabled,
'propagate': log.propagate,
'parent': str(log.parent),
'manager': str(log.manager),
'handlers': [get_handler_report(h) for h in log.handlers],
}
elif isinstance(log, logging.PlaceHolder):
return {
"(object)": str(log),
}
else:
raise ValueError("Unknown object type: {!r}".format(log)) | [
"def",
"get_log_report",
"(",
"log",
":",
"Union",
"[",
"logging",
".",
"Logger",
",",
"logging",
".",
"PlaceHolder",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"isinstance",
"(",
"log",
",",
"logging",
".",
"Logger",
")",
":",
... | Returns information on a log, as a dictionary. For debugging. | [
"Returns",
"information",
"on",
"a",
"log",
"as",
"a",
"dictionary",
".",
"For",
"debugging",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L419-L441 | train | 53,069 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | set_level_for_logger_and_its_handlers | def set_level_for_logger_and_its_handlers(log: logging.Logger,
level: int) -> None:
"""
Set a log level for a log and all its handlers.
Args:
log: log to modify
level: log level to set
"""
log.setLevel(level)
for h in log.handlers: # type: logging.Handler
h.setLevel(level) | python | def set_level_for_logger_and_its_handlers(log: logging.Logger,
level: int) -> None:
"""
Set a log level for a log and all its handlers.
Args:
log: log to modify
level: log level to set
"""
log.setLevel(level)
for h in log.handlers: # type: logging.Handler
h.setLevel(level) | [
"def",
"set_level_for_logger_and_its_handlers",
"(",
"log",
":",
"logging",
".",
"Logger",
",",
"level",
":",
"int",
")",
"->",
"None",
":",
"log",
".",
"setLevel",
"(",
"level",
")",
"for",
"h",
"in",
"log",
".",
"handlers",
":",
"# type: logging.Handler",
... | Set a log level for a log and all its handlers.
Args:
log: log to modify
level: log level to set | [
"Set",
"a",
"log",
"level",
"for",
"a",
"log",
"and",
"all",
"its",
"handlers",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L457-L468 | train | 53,070 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_column_names | def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)] | python | def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)] | [
"def",
"get_column_names",
"(",
"engine",
":",
"Engine",
",",
"tablename",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"info",
".",
"name",
"for",
"info",
"in",
"gen_columns_info",
"(",
"engine",
",",
"tablename",
")",
"]"
] | Get all the database column names for the specified table. | [
"Get",
"all",
"the",
"database",
"column",
"names",
"for",
"the",
"specified",
"table",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L179-L183 | train | 53,071 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_single_int_autoincrement_colname | def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]:
"""
If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's
``AUTOINCREMENT``.
- Verify against SQL Server:
.. code-block:: sql
SELECT table_name, column_name
FROM information_schema.columns
WHERE COLUMNPROPERTY(OBJECT_ID(table_schema + '.' + table_name),
column_name,
'IsIdentity') = 1
ORDER BY table_name;
... http://stackoverflow.com/questions/87747
- Also:
.. code-block:: sql
sp_columns 'tablename';
... which is what SQLAlchemy does (``dialects/mssql/base.py``, in
:func:`get_columns`).
"""
n_autoinc = 0
int_autoinc_names = []
for col in table_.columns:
if col.autoincrement:
n_autoinc += 1
if is_sqlatype_integer(col.type):
int_autoinc_names.append(col.name)
if n_autoinc > 1:
log.warning("Table {!r} has {} autoincrement columns",
table_.name, n_autoinc)
if n_autoinc == 1 and len(int_autoinc_names) == 1:
return int_autoinc_names[0]
return None | python | def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]:
"""
If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's
``AUTOINCREMENT``.
- Verify against SQL Server:
.. code-block:: sql
SELECT table_name, column_name
FROM information_schema.columns
WHERE COLUMNPROPERTY(OBJECT_ID(table_schema + '.' + table_name),
column_name,
'IsIdentity') = 1
ORDER BY table_name;
... http://stackoverflow.com/questions/87747
- Also:
.. code-block:: sql
sp_columns 'tablename';
... which is what SQLAlchemy does (``dialects/mssql/base.py``, in
:func:`get_columns`).
"""
n_autoinc = 0
int_autoinc_names = []
for col in table_.columns:
if col.autoincrement:
n_autoinc += 1
if is_sqlatype_integer(col.type):
int_autoinc_names.append(col.name)
if n_autoinc > 1:
log.warning("Table {!r} has {} autoincrement columns",
table_.name, n_autoinc)
if n_autoinc == 1 and len(int_autoinc_names) == 1:
return int_autoinc_names[0]
return None | [
"def",
"get_single_int_autoincrement_colname",
"(",
"table_",
":",
"Table",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"n_autoinc",
"=",
"0",
"int_autoinc_names",
"=",
"[",
"]",
"for",
"col",
"in",
"table_",
".",
"columns",
":",
"if",
"col",
".",
"autoin... | If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's
``AUTOINCREMENT``.
- Verify against SQL Server:
.. code-block:: sql
SELECT table_name, column_name
FROM information_schema.columns
WHERE COLUMNPROPERTY(OBJECT_ID(table_schema + '.' + table_name),
column_name,
'IsIdentity') = 1
ORDER BY table_name;
... http://stackoverflow.com/questions/87747
- Also:
.. code-block:: sql
sp_columns 'tablename';
... which is what SQLAlchemy does (``dialects/mssql/base.py``, in
:func:`get_columns`). | [
"If",
"a",
"table",
"has",
"a",
"single",
"integer",
"AUTOINCREMENT",
"column",
"this",
"will",
"return",
"its",
"name",
";",
"otherwise",
"None",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L223-L266 | train | 53,072 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | index_exists | def index_exists(engine: Engine, tablename: str, indexname: str) -> bool:
"""
Does the specified index exist for the specified table?
"""
insp = Inspector.from_engine(engine)
return any(i['name'] == indexname for i in insp.get_indexes(tablename)) | python | def index_exists(engine: Engine, tablename: str, indexname: str) -> bool:
"""
Does the specified index exist for the specified table?
"""
insp = Inspector.from_engine(engine)
return any(i['name'] == indexname for i in insp.get_indexes(tablename)) | [
"def",
"index_exists",
"(",
"engine",
":",
"Engine",
",",
"tablename",
":",
"str",
",",
"indexname",
":",
"str",
")",
"->",
"bool",
":",
"insp",
"=",
"Inspector",
".",
"from_engine",
"(",
"engine",
")",
"return",
"any",
"(",
"i",
"[",
"'name'",
"]",
... | Does the specified index exist for the specified table? | [
"Does",
"the",
"specified",
"index",
"exist",
"for",
"the",
"specified",
"table?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L285-L290 | train | 53,073 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | column_creation_ddl | def column_creation_ddl(sqla_column: Column, dialect: Dialect) -> str:
"""
Returns DDL to create a column, using the specified dialect.
The column should already be bound to a table (because e.g. the SQL Server
dialect requires this for DDL generation).
Manual testing:
.. code-block:: python
from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence, Table
from sqlalchemy.sql.sqltypes import BigInteger
from sqlalchemy.dialects.mssql.base import MSDialect
dialect = MSDialect()
col1 = Column('hello', BigInteger, nullable=True)
col2 = Column('world', BigInteger, autoincrement=True) # does NOT generate IDENTITY
col3 = Column('you', BigInteger, Sequence('dummy_name', start=1, increment=1))
metadata = MetaData()
t = Table('mytable', metadata)
t.append_column(col1)
t.append_column(col2)
t.append_column(col3)
print(str(CreateColumn(col1).compile(dialect=dialect))) # hello BIGINT NULL
print(str(CreateColumn(col2).compile(dialect=dialect))) # world BIGINT NULL
print(str(CreateColumn(col3).compile(dialect=dialect))) # you BIGINT NOT NULL IDENTITY(1,1)
If you don't append the column to a Table object, the DDL generation step
gives:
.. code-block:: none
sqlalchemy.exc.CompileError: mssql requires Table-bound columns in order to generate DDL
""" # noqa
return str(CreateColumn(sqla_column).compile(dialect=dialect)) | python | def column_creation_ddl(sqla_column: Column, dialect: Dialect) -> str:
"""
Returns DDL to create a column, using the specified dialect.
The column should already be bound to a table (because e.g. the SQL Server
dialect requires this for DDL generation).
Manual testing:
.. code-block:: python
from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence, Table
from sqlalchemy.sql.sqltypes import BigInteger
from sqlalchemy.dialects.mssql.base import MSDialect
dialect = MSDialect()
col1 = Column('hello', BigInteger, nullable=True)
col2 = Column('world', BigInteger, autoincrement=True) # does NOT generate IDENTITY
col3 = Column('you', BigInteger, Sequence('dummy_name', start=1, increment=1))
metadata = MetaData()
t = Table('mytable', metadata)
t.append_column(col1)
t.append_column(col2)
t.append_column(col3)
print(str(CreateColumn(col1).compile(dialect=dialect))) # hello BIGINT NULL
print(str(CreateColumn(col2).compile(dialect=dialect))) # world BIGINT NULL
print(str(CreateColumn(col3).compile(dialect=dialect))) # you BIGINT NOT NULL IDENTITY(1,1)
If you don't append the column to a Table object, the DDL generation step
gives:
.. code-block:: none
sqlalchemy.exc.CompileError: mssql requires Table-bound columns in order to generate DDL
""" # noqa
return str(CreateColumn(sqla_column).compile(dialect=dialect)) | [
"def",
"column_creation_ddl",
"(",
"sqla_column",
":",
"Column",
",",
"dialect",
":",
"Dialect",
")",
"->",
"str",
":",
"# noqa",
"return",
"str",
"(",
"CreateColumn",
"(",
"sqla_column",
")",
".",
"compile",
"(",
"dialect",
"=",
"dialect",
")",
")"
] | Returns DDL to create a column, using the specified dialect.
The column should already be bound to a table (because e.g. the SQL Server
dialect requires this for DDL generation).
Manual testing:
.. code-block:: python
from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence, Table
from sqlalchemy.sql.sqltypes import BigInteger
from sqlalchemy.dialects.mssql.base import MSDialect
dialect = MSDialect()
col1 = Column('hello', BigInteger, nullable=True)
col2 = Column('world', BigInteger, autoincrement=True) # does NOT generate IDENTITY
col3 = Column('you', BigInteger, Sequence('dummy_name', start=1, increment=1))
metadata = MetaData()
t = Table('mytable', metadata)
t.append_column(col1)
t.append_column(col2)
t.append_column(col3)
print(str(CreateColumn(col1).compile(dialect=dialect))) # hello BIGINT NULL
print(str(CreateColumn(col2).compile(dialect=dialect))) # world BIGINT NULL
print(str(CreateColumn(col3).compile(dialect=dialect))) # you BIGINT NOT NULL IDENTITY(1,1)
If you don't append the column to a Table object, the DDL generation step
gives:
.. code-block:: none
sqlalchemy.exc.CompileError: mssql requires Table-bound columns in order to generate DDL | [
"Returns",
"DDL",
"to",
"create",
"a",
"column",
"using",
"the",
"specified",
"dialect",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L557-L591 | train | 53,074 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | giant_text_sqltype | def giant_text_sqltype(dialect: Dialect) -> str:
"""
Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server.
"""
if dialect.name == SqlaDialectName.SQLSERVER:
return 'NVARCHAR(MAX)'
elif dialect.name == SqlaDialectName.MYSQL:
return 'LONGTEXT'
else:
raise ValueError("Unknown dialect: {}".format(dialect.name)) | python | def giant_text_sqltype(dialect: Dialect) -> str:
"""
Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server.
"""
if dialect.name == SqlaDialectName.SQLSERVER:
return 'NVARCHAR(MAX)'
elif dialect.name == SqlaDialectName.MYSQL:
return 'LONGTEXT'
else:
raise ValueError("Unknown dialect: {}".format(dialect.name)) | [
"def",
"giant_text_sqltype",
"(",
"dialect",
":",
"Dialect",
")",
"->",
"str",
":",
"if",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"SQLSERVER",
":",
"return",
"'NVARCHAR(MAX)'",
"elif",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MYSQL"... | Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server. | [
"Returns",
"the",
"SQL",
"column",
"type",
"used",
"to",
"make",
"very",
"large",
"text",
"columns",
"for",
"a",
"given",
"dialect",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L595-L611 | train | 53,075 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | _get_sqla_coltype_class_from_str | def _get_sqla_coltype_class_from_str(coltype: str,
dialect: Dialect) -> Type[TypeEngine]:
"""
Returns the SQLAlchemy class corresponding to a particular SQL column
type in a given dialect.
Performs an upper- and lower-case search.
For example, the SQLite dialect uses upper case, and the
MySQL dialect uses lower case.
"""
# noinspection PyUnresolvedReferences
ischema_names = dialect.ischema_names
try:
return ischema_names[coltype.upper()]
except KeyError:
return ischema_names[coltype.lower()] | python | def _get_sqla_coltype_class_from_str(coltype: str,
dialect: Dialect) -> Type[TypeEngine]:
"""
Returns the SQLAlchemy class corresponding to a particular SQL column
type in a given dialect.
Performs an upper- and lower-case search.
For example, the SQLite dialect uses upper case, and the
MySQL dialect uses lower case.
"""
# noinspection PyUnresolvedReferences
ischema_names = dialect.ischema_names
try:
return ischema_names[coltype.upper()]
except KeyError:
return ischema_names[coltype.lower()] | [
"def",
"_get_sqla_coltype_class_from_str",
"(",
"coltype",
":",
"str",
",",
"dialect",
":",
"Dialect",
")",
"->",
"Type",
"[",
"TypeEngine",
"]",
":",
"# noinspection PyUnresolvedReferences",
"ischema_names",
"=",
"dialect",
".",
"ischema_names",
"try",
":",
"return... | Returns the SQLAlchemy class corresponding to a particular SQL column
type in a given dialect.
Performs an upper- and lower-case search.
For example, the SQLite dialect uses upper case, and the
MySQL dialect uses lower case. | [
"Returns",
"the",
"SQLAlchemy",
"class",
"corresponding",
"to",
"a",
"particular",
"SQL",
"column",
"type",
"in",
"a",
"given",
"dialect",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L632-L647 | train | 53,076 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | remove_collation | def remove_collation(coltype: TypeEngine) -> TypeEngine:
"""
Returns a copy of the specific column type with any ``COLLATION`` removed.
"""
if not getattr(coltype, 'collation', None):
return coltype
newcoltype = copy.copy(coltype)
newcoltype.collation = None
return newcoltype | python | def remove_collation(coltype: TypeEngine) -> TypeEngine:
"""
Returns a copy of the specific column type with any ``COLLATION`` removed.
"""
if not getattr(coltype, 'collation', None):
return coltype
newcoltype = copy.copy(coltype)
newcoltype.collation = None
return newcoltype | [
"def",
"remove_collation",
"(",
"coltype",
":",
"TypeEngine",
")",
"->",
"TypeEngine",
":",
"if",
"not",
"getattr",
"(",
"coltype",
",",
"'collation'",
",",
"None",
")",
":",
"return",
"coltype",
"newcoltype",
"=",
"copy",
".",
"copy",
"(",
"coltype",
")",... | Returns a copy of the specific column type with any ``COLLATION`` removed. | [
"Returns",
"a",
"copy",
"of",
"the",
"specific",
"column",
"type",
"with",
"any",
"COLLATION",
"removed",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L813-L821 | train | 53,077 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | convert_sqla_type_for_dialect | def convert_sqla_type_for_dialect(
coltype: TypeEngine,
dialect: Dialect,
strip_collation: bool = True,
convert_mssql_timestamp: bool = True,
expand_for_scrubbing: bool = False) -> TypeEngine:
"""
Converts an SQLAlchemy column type from one SQL dialect to another.
Args:
coltype: SQLAlchemy column type in the source dialect
dialect: destination :class:`Dialect`
strip_collation: remove any ``COLLATION`` information?
convert_mssql_timestamp:
since you cannot write to a SQL Server ``TIMESTAMP`` field, setting
this option to ``True`` (the default) converts such types to
something equivalent but writable.
expand_for_scrubbing:
The purpose of expand_for_scrubbing is that, for example, a
``VARCHAR(200)`` field containing one or more instances of
``Jones``, where ``Jones`` is to be replaced with ``[XXXXXX]``,
will get longer (by an unpredictable amount). So, better to expand
to unlimited length.
Returns:
an SQLAlchemy column type instance, in the destination dialect
"""
assert coltype is not None
# noinspection PyUnresolvedReferences
to_mysql = dialect.name == SqlaDialectName.MYSQL
# noinspection PyUnresolvedReferences
to_mssql = dialect.name == SqlaDialectName.MSSQL
typeclass = type(coltype)
# -------------------------------------------------------------------------
# Text
# -------------------------------------------------------------------------
if isinstance(coltype, sqltypes.Enum):
return sqltypes.String(length=coltype.length)
if isinstance(coltype, sqltypes.UnicodeText):
# Unbounded Unicode text.
# Includes derived classes such as mssql.base.NTEXT.
return sqltypes.UnicodeText()
if isinstance(coltype, sqltypes.Text):
# Unbounded text, more generally. (UnicodeText inherits from Text.)
# Includes sqltypes.TEXT.
return sqltypes.Text()
# Everything inheriting from String has a length property, but can be None.
# There are types that can be unlimited in SQL Server, e.g. VARCHAR(MAX)
# and NVARCHAR(MAX), that MySQL needs a length for. (Failure to convert
# gives e.g.: 'NVARCHAR requires a length on dialect mysql'.)
if isinstance(coltype, sqltypes.Unicode):
# Includes NVARCHAR(MAX) in SQL -> NVARCHAR() in SQLAlchemy.
if (coltype.length is None and to_mysql) or expand_for_scrubbing:
return sqltypes.UnicodeText()
# The most general case; will pick up any other string types.
if isinstance(coltype, sqltypes.String):
# Includes VARCHAR(MAX) in SQL -> VARCHAR() in SQLAlchemy
if (coltype.length is None and to_mysql) or expand_for_scrubbing:
return sqltypes.Text()
if strip_collation:
return remove_collation(coltype)
return coltype
# -------------------------------------------------------------------------
# Binary
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# BIT
# -------------------------------------------------------------------------
if typeclass == mssql.base.BIT and to_mysql:
# MySQL BIT objects have a length attribute.
return mysql.base.BIT()
# -------------------------------------------------------------------------
# TIMESTAMP
# -------------------------------------------------------------------------
is_mssql_timestamp = isinstance(coltype, MSSQL_TIMESTAMP)
if is_mssql_timestamp and to_mssql and convert_mssql_timestamp:
# You cannot write explicitly to a TIMESTAMP field in SQL Server; it's
# used for autogenerated values only.
# - http://stackoverflow.com/questions/10262426/sql-server-cannot-insert-an-explicit-value-into-a-timestamp-column # noqa
# - https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5167204b-ef32-4662-8e01-00c9f0f362c2/how-to-tranfer-a-column-with-timestamp-datatype?forum=transactsql # noqa
# ... suggesting BINARY(8) to store the value.
# MySQL is more helpful:
# - http://stackoverflow.com/questions/409286/should-i-use-field-datetime-or-timestamp # noqa
return mssql.base.BINARY(8)
# -------------------------------------------------------------------------
# Some other type
# -------------------------------------------------------------------------
return coltype | python | def convert_sqla_type_for_dialect(
coltype: TypeEngine,
dialect: Dialect,
strip_collation: bool = True,
convert_mssql_timestamp: bool = True,
expand_for_scrubbing: bool = False) -> TypeEngine:
"""
Converts an SQLAlchemy column type from one SQL dialect to another.
Args:
coltype: SQLAlchemy column type in the source dialect
dialect: destination :class:`Dialect`
strip_collation: remove any ``COLLATION`` information?
convert_mssql_timestamp:
since you cannot write to a SQL Server ``TIMESTAMP`` field, setting
this option to ``True`` (the default) converts such types to
something equivalent but writable.
expand_for_scrubbing:
The purpose of expand_for_scrubbing is that, for example, a
``VARCHAR(200)`` field containing one or more instances of
``Jones``, where ``Jones`` is to be replaced with ``[XXXXXX]``,
will get longer (by an unpredictable amount). So, better to expand
to unlimited length.
Returns:
an SQLAlchemy column type instance, in the destination dialect
"""
assert coltype is not None
# noinspection PyUnresolvedReferences
to_mysql = dialect.name == SqlaDialectName.MYSQL
# noinspection PyUnresolvedReferences
to_mssql = dialect.name == SqlaDialectName.MSSQL
typeclass = type(coltype)
# -------------------------------------------------------------------------
# Text
# -------------------------------------------------------------------------
if isinstance(coltype, sqltypes.Enum):
return sqltypes.String(length=coltype.length)
if isinstance(coltype, sqltypes.UnicodeText):
# Unbounded Unicode text.
# Includes derived classes such as mssql.base.NTEXT.
return sqltypes.UnicodeText()
if isinstance(coltype, sqltypes.Text):
# Unbounded text, more generally. (UnicodeText inherits from Text.)
# Includes sqltypes.TEXT.
return sqltypes.Text()
# Everything inheriting from String has a length property, but can be None.
# There are types that can be unlimited in SQL Server, e.g. VARCHAR(MAX)
# and NVARCHAR(MAX), that MySQL needs a length for. (Failure to convert
# gives e.g.: 'NVARCHAR requires a length on dialect mysql'.)
if isinstance(coltype, sqltypes.Unicode):
# Includes NVARCHAR(MAX) in SQL -> NVARCHAR() in SQLAlchemy.
if (coltype.length is None and to_mysql) or expand_for_scrubbing:
return sqltypes.UnicodeText()
# The most general case; will pick up any other string types.
if isinstance(coltype, sqltypes.String):
# Includes VARCHAR(MAX) in SQL -> VARCHAR() in SQLAlchemy
if (coltype.length is None and to_mysql) or expand_for_scrubbing:
return sqltypes.Text()
if strip_collation:
return remove_collation(coltype)
return coltype
# -------------------------------------------------------------------------
# Binary
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# BIT
# -------------------------------------------------------------------------
if typeclass == mssql.base.BIT and to_mysql:
# MySQL BIT objects have a length attribute.
return mysql.base.BIT()
# -------------------------------------------------------------------------
# TIMESTAMP
# -------------------------------------------------------------------------
is_mssql_timestamp = isinstance(coltype, MSSQL_TIMESTAMP)
if is_mssql_timestamp and to_mssql and convert_mssql_timestamp:
# You cannot write explicitly to a TIMESTAMP field in SQL Server; it's
# used for autogenerated values only.
# - http://stackoverflow.com/questions/10262426/sql-server-cannot-insert-an-explicit-value-into-a-timestamp-column # noqa
# - https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5167204b-ef32-4662-8e01-00c9f0f362c2/how-to-tranfer-a-column-with-timestamp-datatype?forum=transactsql # noqa
# ... suggesting BINARY(8) to store the value.
# MySQL is more helpful:
# - http://stackoverflow.com/questions/409286/should-i-use-field-datetime-or-timestamp # noqa
return mssql.base.BINARY(8)
# -------------------------------------------------------------------------
# Some other type
# -------------------------------------------------------------------------
return coltype | [
"def",
"convert_sqla_type_for_dialect",
"(",
"coltype",
":",
"TypeEngine",
",",
"dialect",
":",
"Dialect",
",",
"strip_collation",
":",
"bool",
"=",
"True",
",",
"convert_mssql_timestamp",
":",
"bool",
"=",
"True",
",",
"expand_for_scrubbing",
":",
"bool",
"=",
... | Converts an SQLAlchemy column type from one SQL dialect to another.
Args:
coltype: SQLAlchemy column type in the source dialect
dialect: destination :class:`Dialect`
strip_collation: remove any ``COLLATION`` information?
convert_mssql_timestamp:
since you cannot write to a SQL Server ``TIMESTAMP`` field, setting
this option to ``True`` (the default) converts such types to
something equivalent but writable.
expand_for_scrubbing:
The purpose of expand_for_scrubbing is that, for example, a
``VARCHAR(200)`` field containing one or more instances of
``Jones``, where ``Jones`` is to be replaced with ``[XXXXXX]``,
will get longer (by an unpredictable amount). So, better to expand
to unlimited length.
Returns:
an SQLAlchemy column type instance, in the destination dialect | [
"Converts",
"an",
"SQLAlchemy",
"column",
"type",
"from",
"one",
"SQL",
"dialect",
"to",
"another",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L825-L923 | train | 53,078 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_binary | def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a binary type?
"""
# Several binary types inherit internally from _Binary, making that the
# easiest to check.
coltype = _coltype_to_typeengine(coltype)
# noinspection PyProtectedMember
return isinstance(coltype, sqltypes._Binary) | python | def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a binary type?
"""
# Several binary types inherit internally from _Binary, making that the
# easiest to check.
coltype = _coltype_to_typeengine(coltype)
# noinspection PyProtectedMember
return isinstance(coltype, sqltypes._Binary) | [
"def",
"is_sqlatype_binary",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"# Several binary types inherit internally from _Binary, making that the",
"# easiest to check.",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
... | Is the SQLAlchemy column type a binary type? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"binary",
"type?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L956-L964 | train | 53,079 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_date | def is_sqlatype_date(coltype: TypeEngine) -> bool:
"""
Is the SQLAlchemy column type a date type?
"""
coltype = _coltype_to_typeengine(coltype)
# No longer valid in SQLAlchemy 1.2.11:
# return isinstance(coltype, sqltypes._DateAffinity)
return (
isinstance(coltype, sqltypes.DateTime) or
isinstance(coltype, sqltypes.Date)
) | python | def is_sqlatype_date(coltype: TypeEngine) -> bool:
"""
Is the SQLAlchemy column type a date type?
"""
coltype = _coltype_to_typeengine(coltype)
# No longer valid in SQLAlchemy 1.2.11:
# return isinstance(coltype, sqltypes._DateAffinity)
return (
isinstance(coltype, sqltypes.DateTime) or
isinstance(coltype, sqltypes.Date)
) | [
"def",
"is_sqlatype_date",
"(",
"coltype",
":",
"TypeEngine",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"# No longer valid in SQLAlchemy 1.2.11:",
"# return isinstance(coltype, sqltypes._DateAffinity)",
"return",
"(",
"isinstance",... | Is the SQLAlchemy column type a date type? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"date",
"type?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L967-L977 | train | 53,080 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_integer | def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type an integer type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Integer) | python | def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type an integer type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Integer) | [
"def",
"is_sqlatype_integer",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Inte... | Is the SQLAlchemy column type an integer type? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"an",
"integer",
"type?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L980-L985 | train | 53,081 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_string | def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.String) | python | def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.String) | [
"def",
"is_sqlatype_string",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Strin... | Is the SQLAlchemy column type a string type? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"string",
"type?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L997-L1002 | train | 53,082 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_text_of_length_at_least | def is_sqlatype_text_of_length_at_least(
coltype: Union[TypeEngine, VisitableType],
min_length: int = 1000) -> bool:
"""
Is the SQLAlchemy column type a string type that's at least the specified
length?
"""
coltype = _coltype_to_typeengine(coltype)
if not isinstance(coltype, sqltypes.String):
return False # not a string/text type at all
if coltype.length is None:
return True # string of unlimited length
return coltype.length >= min_length | python | def is_sqlatype_text_of_length_at_least(
coltype: Union[TypeEngine, VisitableType],
min_length: int = 1000) -> bool:
"""
Is the SQLAlchemy column type a string type that's at least the specified
length?
"""
coltype = _coltype_to_typeengine(coltype)
if not isinstance(coltype, sqltypes.String):
return False # not a string/text type at all
if coltype.length is None:
return True # string of unlimited length
return coltype.length >= min_length | [
"def",
"is_sqlatype_text_of_length_at_least",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
",",
"min_length",
":",
"int",
"=",
"1000",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"if",
"... | Is the SQLAlchemy column type a string type that's at least the specified
length? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"string",
"type",
"that",
"s",
"at",
"least",
"the",
"specified",
"length?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1005-L1017 | train | 53,083 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_text_over_one_char | def is_sqlatype_text_over_one_char(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type that's more than one character
long?
"""
coltype = _coltype_to_typeengine(coltype)
return is_sqlatype_text_of_length_at_least(coltype, 2) | python | def is_sqlatype_text_over_one_char(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type that's more than one character
long?
"""
coltype = _coltype_to_typeengine(coltype)
return is_sqlatype_text_of_length_at_least(coltype, 2) | [
"def",
"is_sqlatype_text_over_one_char",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"is_sqlatype_text_of_length_at_least",
"(",
"coltype",... | Is the SQLAlchemy column type a string type that's more than one character
long? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"string",
"type",
"that",
"s",
"more",
"than",
"one",
"character",
"long?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1020-L1027 | train | 53,084 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | does_sqlatype_require_index_len | def does_sqlatype_require_index_len(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that requires its indexes to have a
length specified?
(MySQL, at least, requires index length to be specified for ``BLOB`` and
``TEXT`` columns:
http://dev.mysql.com/doc/refman/5.7/en/create-index.html.)
"""
coltype = _coltype_to_typeengine(coltype)
if isinstance(coltype, sqltypes.Text):
return True
if isinstance(coltype, sqltypes.LargeBinary):
return True
return False | python | def does_sqlatype_require_index_len(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that requires its indexes to have a
length specified?
(MySQL, at least, requires index length to be specified for ``BLOB`` and
``TEXT`` columns:
http://dev.mysql.com/doc/refman/5.7/en/create-index.html.)
"""
coltype = _coltype_to_typeengine(coltype)
if isinstance(coltype, sqltypes.Text):
return True
if isinstance(coltype, sqltypes.LargeBinary):
return True
return False | [
"def",
"does_sqlatype_require_index_len",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"if",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",... | Is the SQLAlchemy column type one that requires its indexes to have a
length specified?
(MySQL, at least, requires index length to be specified for ``BLOB`` and
``TEXT`` columns:
http://dev.mysql.com/doc/refman/5.7/en/create-index.html.) | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"one",
"that",
"requires",
"its",
"indexes",
"to",
"have",
"a",
"length",
"specified?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1041-L1056 | train | 53,085 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | signed_to_twos_comp | def signed_to_twos_comp(val: int, n_bits: int) -> int:
"""
Convert a signed integer to its "two's complement" representation.
Args:
val: signed integer
n_bits: number of bits (which must reflect a whole number of bytes)
Returns:
unsigned integer: two's complement version
"""
assert n_bits % 8 == 0, "Must specify a whole number of bytes"
n_bytes = n_bits // 8
b = val.to_bytes(n_bytes, byteorder=sys.byteorder, signed=True)
return int.from_bytes(b, byteorder=sys.byteorder, signed=False) | python | def signed_to_twos_comp(val: int, n_bits: int) -> int:
"""
Convert a signed integer to its "two's complement" representation.
Args:
val: signed integer
n_bits: number of bits (which must reflect a whole number of bytes)
Returns:
unsigned integer: two's complement version
"""
assert n_bits % 8 == 0, "Must specify a whole number of bytes"
n_bytes = n_bits // 8
b = val.to_bytes(n_bytes, byteorder=sys.byteorder, signed=True)
return int.from_bytes(b, byteorder=sys.byteorder, signed=False) | [
"def",
"signed_to_twos_comp",
"(",
"val",
":",
"int",
",",
"n_bits",
":",
"int",
")",
"->",
"int",
":",
"assert",
"n_bits",
"%",
"8",
"==",
"0",
",",
"\"Must specify a whole number of bytes\"",
"n_bytes",
"=",
"n_bits",
"//",
"8",
"b",
"=",
"val",
".",
"... | Convert a signed integer to its "two's complement" representation.
Args:
val: signed integer
n_bits: number of bits (which must reflect a whole number of bytes)
Returns:
unsigned integer: two's complement version | [
"Convert",
"a",
"signed",
"integer",
"to",
"its",
"two",
"s",
"complement",
"representation",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L347-L362 | train | 53,086 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | bytes_to_long | def bytes_to_long(bytesdata: bytes) -> int:
"""
Converts an 8-byte sequence to a long integer.
Args:
bytesdata: 8 consecutive bytes, as a ``bytes`` object, in
little-endian format (least significant byte [LSB] first)
Returns:
integer
"""
assert len(bytesdata) == 8
return sum((b << (k * 8) for k, b in enumerate(bytesdata))) | python | def bytes_to_long(bytesdata: bytes) -> int:
"""
Converts an 8-byte sequence to a long integer.
Args:
bytesdata: 8 consecutive bytes, as a ``bytes`` object, in
little-endian format (least significant byte [LSB] first)
Returns:
integer
"""
assert len(bytesdata) == 8
return sum((b << (k * 8) for k, b in enumerate(bytesdata))) | [
"def",
"bytes_to_long",
"(",
"bytesdata",
":",
"bytes",
")",
"->",
"int",
":",
"assert",
"len",
"(",
"bytesdata",
")",
"==",
"8",
"return",
"sum",
"(",
"(",
"b",
"<<",
"(",
"k",
"*",
"8",
")",
"for",
"k",
",",
"b",
"in",
"enumerate",
"(",
"bytesd... | Converts an 8-byte sequence to a long integer.
Args:
bytesdata: 8 consecutive bytes, as a ``bytes`` object, in
little-endian format (least significant byte [LSB] first)
Returns:
integer | [
"Converts",
"an",
"8",
"-",
"byte",
"sequence",
"to",
"a",
"long",
"integer",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L365-L378 | train | 53,087 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | pymmh3_hash128 | def pymmh3_hash128(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> int:
"""
Implements 128bit murmur3 hash, as per ``pymmh3``.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
integer hash
"""
if x64arch:
return pymmh3_hash128_x64(key, seed)
else:
return pymmh3_hash128_x86(key, seed) | python | def pymmh3_hash128(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> int:
"""
Implements 128bit murmur3 hash, as per ``pymmh3``.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
integer hash
"""
if x64arch:
return pymmh3_hash128_x64(key, seed)
else:
return pymmh3_hash128_x86(key, seed) | [
"def",
"pymmh3_hash128",
"(",
"key",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
",",
"seed",
":",
"int",
"=",
"0",
",",
"x64arch",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"if",
"x64arch",
":",
"return",
"pymmh3_hash128_x64",
"(",
"ke... | Implements 128bit murmur3 hash, as per ``pymmh3``.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
integer hash | [
"Implements",
"128bit",
"murmur3",
"hash",
"as",
"per",
"pymmh3",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L849-L867 | train | 53,088 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | pymmh3_hash64 | def pymmh3_hash64(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> Tuple[int, int]:
"""
Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
tuple: tuple of integers, ``(signed_val1, signed_val2)``
"""
hash_128 = pymmh3_hash128(key, seed, x64arch)
unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF # low half
if unsigned_val1 & 0x8000000000000000 == 0:
signed_val1 = unsigned_val1
else:
signed_val1 = -((unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF) + 1)
unsigned_val2 = (hash_128 >> 64) & 0xFFFFFFFFFFFFFFFF # high half
if unsigned_val2 & 0x8000000000000000 == 0:
signed_val2 = unsigned_val2
else:
signed_val2 = -((unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1)
return signed_val1, signed_val2 | python | def pymmh3_hash64(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> Tuple[int, int]:
"""
Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
tuple: tuple of integers, ``(signed_val1, signed_val2)``
"""
hash_128 = pymmh3_hash128(key, seed, x64arch)
unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF # low half
if unsigned_val1 & 0x8000000000000000 == 0:
signed_val1 = unsigned_val1
else:
signed_val1 = -((unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF) + 1)
unsigned_val2 = (hash_128 >> 64) & 0xFFFFFFFFFFFFFFFF # high half
if unsigned_val2 & 0x8000000000000000 == 0:
signed_val2 = unsigned_val2
else:
signed_val2 = -((unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1)
return signed_val1, signed_val2 | [
"def",
"pymmh3_hash64",
"(",
"key",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
",",
"seed",
":",
"int",
"=",
"0",
",",
"x64arch",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"hash_128",
"=",
"pymmh3_hash1... | Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
tuple: tuple of integers, ``(signed_val1, signed_val2)`` | [
"Implements",
"64bit",
"murmur3",
"hash",
"as",
"per",
"pymmh3",
".",
"Returns",
"a",
"tuple",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L870-L900 | train | 53,089 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | compare_python_to_reference_murmur3_32 | def compare_python_to_reference_murmur3_32(data: Any, seed: int = 0) -> None:
"""
Checks the pure Python implementation of 32-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match
"""
assert mmh3, "Need mmh3 module"
c_data = to_str(data)
c_signed = mmh3.hash(c_data, seed=seed) # 32 bit
py_data = to_bytes(c_data)
py_unsigned = murmur3_x86_32(py_data, seed=seed)
py_signed = twos_comp_to_signed(py_unsigned, n_bits=32)
preamble = "Hashing {data} with MurmurHash3/32-bit/seed={seed}".format(
data=repr(data), seed=seed)
if c_signed == py_signed:
print(preamble + " -> {result}: OK".format(result=c_signed))
else:
raise AssertionError(
preamble + "; mmh3 says "
"{c_data} -> {c_signed}, Python version says {py_data} -> "
"{py_unsigned} = {py_signed}".format(
c_data=repr(c_data),
c_signed=c_signed,
py_data=repr(py_data),
py_unsigned=py_unsigned,
py_signed=py_signed)) | python | def compare_python_to_reference_murmur3_32(data: Any, seed: int = 0) -> None:
"""
Checks the pure Python implementation of 32-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match
"""
assert mmh3, "Need mmh3 module"
c_data = to_str(data)
c_signed = mmh3.hash(c_data, seed=seed) # 32 bit
py_data = to_bytes(c_data)
py_unsigned = murmur3_x86_32(py_data, seed=seed)
py_signed = twos_comp_to_signed(py_unsigned, n_bits=32)
preamble = "Hashing {data} with MurmurHash3/32-bit/seed={seed}".format(
data=repr(data), seed=seed)
if c_signed == py_signed:
print(preamble + " -> {result}: OK".format(result=c_signed))
else:
raise AssertionError(
preamble + "; mmh3 says "
"{c_data} -> {c_signed}, Python version says {py_data} -> "
"{py_unsigned} = {py_signed}".format(
c_data=repr(c_data),
c_signed=c_signed,
py_data=repr(py_data),
py_unsigned=py_unsigned,
py_signed=py_signed)) | [
"def",
"compare_python_to_reference_murmur3_32",
"(",
"data",
":",
"Any",
",",
"seed",
":",
"int",
"=",
"0",
")",
"->",
"None",
":",
"assert",
"mmh3",
",",
"\"Need mmh3 module\"",
"c_data",
"=",
"to_str",
"(",
"data",
")",
"c_signed",
"=",
"mmh3",
".",
"ha... | Checks the pure Python implementation of 32-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match | [
"Checks",
"the",
"pure",
"Python",
"implementation",
"of",
"32",
"-",
"bit",
"murmur3",
"against",
"the",
"mmh3",
"C",
"-",
"based",
"module",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L907-L939 | train | 53,090 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | compare_python_to_reference_murmur3_64 | def compare_python_to_reference_murmur3_64(data: Any, seed: int = 0) -> None:
"""
Checks the pure Python implementation of 64-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match
"""
assert mmh3, "Need mmh3 module"
c_data = to_str(data)
c_signed_low, c_signed_high = mmh3.hash64(c_data, seed=seed,
x64arch=IS_64_BIT)
py_data = to_bytes(c_data)
py_signed_low, py_signed_high = pymmh3_hash64(py_data, seed=seed)
preamble = "Hashing {data} with MurmurHash3/64-bit values from 128-bit " \
"hash/seed={seed}".format(data=repr(data), seed=seed)
if c_signed_low == py_signed_low and c_signed_high == py_signed_high:
print(preamble + " -> (low={low}, high={high}): OK".format(
low=c_signed_low, high=c_signed_high))
else:
raise AssertionError(
preamble +
"; mmh3 says {c_data} -> (low={c_low}, high={c_high}), Python "
"version says {py_data} -> (low={py_low}, high={py_high})".format(
c_data=repr(c_data),
c_low=c_signed_low,
c_high=c_signed_high,
py_data=repr(py_data),
py_low=py_signed_low,
py_high=py_signed_high)) | python | def compare_python_to_reference_murmur3_64(data: Any, seed: int = 0) -> None:
"""
Checks the pure Python implementation of 64-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match
"""
assert mmh3, "Need mmh3 module"
c_data = to_str(data)
c_signed_low, c_signed_high = mmh3.hash64(c_data, seed=seed,
x64arch=IS_64_BIT)
py_data = to_bytes(c_data)
py_signed_low, py_signed_high = pymmh3_hash64(py_data, seed=seed)
preamble = "Hashing {data} with MurmurHash3/64-bit values from 128-bit " \
"hash/seed={seed}".format(data=repr(data), seed=seed)
if c_signed_low == py_signed_low and c_signed_high == py_signed_high:
print(preamble + " -> (low={low}, high={high}): OK".format(
low=c_signed_low, high=c_signed_high))
else:
raise AssertionError(
preamble +
"; mmh3 says {c_data} -> (low={c_low}, high={c_high}), Python "
"version says {py_data} -> (low={py_low}, high={py_high})".format(
c_data=repr(c_data),
c_low=c_signed_low,
c_high=c_signed_high,
py_data=repr(py_data),
py_low=py_signed_low,
py_high=py_signed_high)) | [
"def",
"compare_python_to_reference_murmur3_64",
"(",
"data",
":",
"Any",
",",
"seed",
":",
"int",
"=",
"0",
")",
"->",
"None",
":",
"assert",
"mmh3",
",",
"\"Need mmh3 module\"",
"c_data",
"=",
"to_str",
"(",
"data",
")",
"c_signed_low",
",",
"c_signed_high",... | Checks the pure Python implementation of 64-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match | [
"Checks",
"the",
"pure",
"Python",
"implementation",
"of",
"64",
"-",
"bit",
"murmur3",
"against",
"the",
"mmh3",
"C",
"-",
"based",
"module",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L942-L976 | train | 53,091 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | main | def main() -> None:
"""
Command-line validation checks.
"""
_ = """
print(twos_comp_to_signed(0, n_bits=32)) # 0
print(twos_comp_to_signed(2 ** 31 - 1, n_bits=32)) # 2147483647
print(twos_comp_to_signed(2 ** 31, n_bits=32)) # -2147483648 == -(2 ** 31)
print(twos_comp_to_signed(2 ** 32 - 1, n_bits=32)) # -1
print(signed_to_twos_comp(-1, n_bits=32)) # 4294967295 = 2 ** 32 - 1
print(signed_to_twos_comp(-(2 ** 31), n_bits=32)) # 2147483648 = 2 ** 31 - 1
""" # noqa
testdata = [
"hello",
1,
["bongos", "today"],
]
for data in testdata:
compare_python_to_reference_murmur3_32(data, seed=0)
compare_python_to_reference_murmur3_64(data, seed=0)
print("All OK") | python | def main() -> None:
"""
Command-line validation checks.
"""
_ = """
print(twos_comp_to_signed(0, n_bits=32)) # 0
print(twos_comp_to_signed(2 ** 31 - 1, n_bits=32)) # 2147483647
print(twos_comp_to_signed(2 ** 31, n_bits=32)) # -2147483648 == -(2 ** 31)
print(twos_comp_to_signed(2 ** 32 - 1, n_bits=32)) # -1
print(signed_to_twos_comp(-1, n_bits=32)) # 4294967295 = 2 ** 32 - 1
print(signed_to_twos_comp(-(2 ** 31), n_bits=32)) # 2147483648 = 2 ** 31 - 1
""" # noqa
testdata = [
"hello",
1,
["bongos", "today"],
]
for data in testdata:
compare_python_to_reference_murmur3_32(data, seed=0)
compare_python_to_reference_murmur3_64(data, seed=0)
print("All OK") | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"_",
"=",
"\"\"\"\n print(twos_comp_to_signed(0, n_bits=32)) # 0\n print(twos_comp_to_signed(2 ** 31 - 1, n_bits=32)) # 2147483647\n print(twos_comp_to_signed(2 ** 31, n_bits=32)) # -2147483648 == -(2 ** 31)\n print(twos_comp_to_signed(2 *... | Command-line validation checks. | [
"Command",
"-",
"line",
"validation",
"checks",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L1042-L1062 | train | 53,092 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | GenericHmacHasher.hash | def hash(self, raw: Any) -> str:
"""
Returns the hex digest of a HMAC-encoded version of the input.
"""
with MultiTimerContext(timer, TIMING_HASH):
raw_bytes = str(raw).encode('utf-8')
hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes,
digestmod=self.digestmod)
return hmac_obj.hexdigest() | python | def hash(self, raw: Any) -> str:
"""
Returns the hex digest of a HMAC-encoded version of the input.
"""
with MultiTimerContext(timer, TIMING_HASH):
raw_bytes = str(raw).encode('utf-8')
hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes,
digestmod=self.digestmod)
return hmac_obj.hexdigest() | [
"def",
"hash",
"(",
"self",
",",
"raw",
":",
"Any",
")",
"->",
"str",
":",
"with",
"MultiTimerContext",
"(",
"timer",
",",
"TIMING_HASH",
")",
":",
"raw_bytes",
"=",
"str",
"(",
"raw",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"hmac_obj",
"=",
"hmac",... | Returns the hex digest of a HMAC-encoded version of the input. | [
"Returns",
"the",
"hex",
"digest",
"of",
"a",
"HMAC",
"-",
"encoded",
"version",
"of",
"the",
"input",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L188-L196 | train | 53,093 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_py.py | mean | def mean(values: Sequence[Union[int, float, None]]) -> Optional[float]:
"""
Returns the mean of a list of numbers.
Args:
values: values to mean, ignoring any values that are ``None``
Returns:
the mean, or ``None`` if :math:`n = 0`
"""
total = 0.0 # starting with "0.0" causes automatic conversion to float
n = 0
for x in values:
if x is not None:
total += x
n += 1
return total / n if n > 0 else None | python | def mean(values: Sequence[Union[int, float, None]]) -> Optional[float]:
"""
Returns the mean of a list of numbers.
Args:
values: values to mean, ignoring any values that are ``None``
Returns:
the mean, or ``None`` if :math:`n = 0`
"""
total = 0.0 # starting with "0.0" causes automatic conversion to float
n = 0
for x in values:
if x is not None:
total += x
n += 1
return total / n if n > 0 else None | [
"def",
"mean",
"(",
"values",
":",
"Sequence",
"[",
"Union",
"[",
"int",
",",
"float",
",",
"None",
"]",
"]",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"total",
"=",
"0.0",
"# starting with \"0.0\" causes automatic conversion to float",
"n",
"=",
"0",
... | Returns the mean of a list of numbers.
Args:
values: values to mean, ignoring any values that are ``None``
Returns:
the mean, or ``None`` if :math:`n = 0` | [
"Returns",
"the",
"mean",
"of",
"a",
"list",
"of",
"numbers",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_py.py#L41-L58 | train | 53,094 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_py.py | normal_round_float | def normal_round_float(x: float, dp: int = 0) -> float:
"""
Hmpf. Shouldn't need to have to implement this, but...
Conventional rounding to integer via the "round half away from zero"
method, e.g.
.. code-block:: none
1.1 -> 1
1.5 -> 2
1.6 -> 2
2.0 -> 2
-1.6 -> -2
etc.
... or the equivalent for a certain number of decimal places.
Note that round() implements "banker's rounding", which is never what
we want:
- https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python # noqa
"""
if not math.isfinite(x):
return x
factor = pow(10, dp)
x = x * factor
if x >= 0:
x = math.floor(x + 0.5)
else:
x = math.ceil(x - 0.5)
x = x / factor
return x | python | def normal_round_float(x: float, dp: int = 0) -> float:
"""
Hmpf. Shouldn't need to have to implement this, but...
Conventional rounding to integer via the "round half away from zero"
method, e.g.
.. code-block:: none
1.1 -> 1
1.5 -> 2
1.6 -> 2
2.0 -> 2
-1.6 -> -2
etc.
... or the equivalent for a certain number of decimal places.
Note that round() implements "banker's rounding", which is never what
we want:
- https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python # noqa
"""
if not math.isfinite(x):
return x
factor = pow(10, dp)
x = x * factor
if x >= 0:
x = math.floor(x + 0.5)
else:
x = math.ceil(x - 0.5)
x = x / factor
return x | [
"def",
"normal_round_float",
"(",
"x",
":",
"float",
",",
"dp",
":",
"int",
"=",
"0",
")",
"->",
"float",
":",
"if",
"not",
"math",
".",
"isfinite",
"(",
"x",
")",
":",
"return",
"x",
"factor",
"=",
"pow",
"(",
"10",
",",
"dp",
")",
"x",
"=",
... | Hmpf. Shouldn't need to have to implement this, but...
Conventional rounding to integer via the "round half away from zero"
method, e.g.
.. code-block:: none
1.1 -> 1
1.5 -> 2
1.6 -> 2
2.0 -> 2
-1.6 -> -2
etc.
... or the equivalent for a certain number of decimal places.
Note that round() implements "banker's rounding", which is never what
we want:
- https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python # noqa | [
"Hmpf",
".",
"Shouldn",
"t",
"need",
"to",
"have",
"to",
"implement",
"this",
"but",
"..."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_py.py#L93-L125 | train | 53,095 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tools/backup_mysql_database.py | cmdargs | def cmdargs(mysqldump: str,
username: str,
password: str,
database: str,
verbose: bool,
with_drop_create_database: bool,
max_allowed_packet: str,
hide_password: bool = False) -> List[str]:
"""
Returns command arguments for a ``mysqldump`` call.
Args:
mysqldump: ``mysqldump`` executable filename
username: user name
password: password
database: database name
verbose: verbose output?
with_drop_create_database: produce commands to ``DROP`` the database
and recreate it?
max_allowed_packet: passed to ``mysqldump``
hide_password: obscure the password (will break the arguments but
provide a safe version to show the user)?
Returns:
list of command-line arguments
"""
ca = [
mysqldump,
"-u", username,
"-p{}".format("*****" if hide_password else password),
"--max_allowed_packet={}".format(max_allowed_packet),
"--hex-blob", # preferable to raw binary in our .sql file
]
if verbose:
ca.append("--verbose")
if with_drop_create_database:
ca.extend([
"--add-drop-database",
"--databases",
database
])
else:
ca.append(database)
pass
return ca | python | def cmdargs(mysqldump: str,
username: str,
password: str,
database: str,
verbose: bool,
with_drop_create_database: bool,
max_allowed_packet: str,
hide_password: bool = False) -> List[str]:
"""
Returns command arguments for a ``mysqldump`` call.
Args:
mysqldump: ``mysqldump`` executable filename
username: user name
password: password
database: database name
verbose: verbose output?
with_drop_create_database: produce commands to ``DROP`` the database
and recreate it?
max_allowed_packet: passed to ``mysqldump``
hide_password: obscure the password (will break the arguments but
provide a safe version to show the user)?
Returns:
list of command-line arguments
"""
ca = [
mysqldump,
"-u", username,
"-p{}".format("*****" if hide_password else password),
"--max_allowed_packet={}".format(max_allowed_packet),
"--hex-blob", # preferable to raw binary in our .sql file
]
if verbose:
ca.append("--verbose")
if with_drop_create_database:
ca.extend([
"--add-drop-database",
"--databases",
database
])
else:
ca.append(database)
pass
return ca | [
"def",
"cmdargs",
"(",
"mysqldump",
":",
"str",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"database",
":",
"str",
",",
"verbose",
":",
"bool",
",",
"with_drop_create_database",
":",
"bool",
",",
"max_allowed_packet",
":",
"str",
",",
... | Returns command arguments for a ``mysqldump`` call.
Args:
mysqldump: ``mysqldump`` executable filename
username: user name
password: password
database: database name
verbose: verbose output?
with_drop_create_database: produce commands to ``DROP`` the database
and recreate it?
max_allowed_packet: passed to ``mysqldump``
hide_password: obscure the password (will break the arguments but
provide a safe version to show the user)?
Returns:
list of command-line arguments | [
"Returns",
"command",
"arguments",
"for",
"a",
"mysqldump",
"call",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/backup_mysql_database.py#L46-L90 | train | 53,096 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dialect.py | get_dialect | def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect:
"""
Finds the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy :class:`Dialect` being used
"""
if isinstance(mixed, Dialect):
return mixed
elif isinstance(mixed, Engine):
return mixed.dialect
elif isinstance(mixed, SQLCompiler):
return mixed.dialect
else:
raise ValueError("get_dialect: 'mixed' parameter of wrong type") | python | def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect:
"""
Finds the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy :class:`Dialect` being used
"""
if isinstance(mixed, Dialect):
return mixed
elif isinstance(mixed, Engine):
return mixed.dialect
elif isinstance(mixed, SQLCompiler):
return mixed.dialect
else:
raise ValueError("get_dialect: 'mixed' parameter of wrong type") | [
"def",
"get_dialect",
"(",
"mixed",
":",
"Union",
"[",
"SQLCompiler",
",",
"Engine",
",",
"Dialect",
"]",
")",
"->",
"Dialect",
":",
"if",
"isinstance",
"(",
"mixed",
",",
"Dialect",
")",
":",
"return",
"mixed",
"elif",
"isinstance",
"(",
"mixed",
",",
... | Finds the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy :class:`Dialect` being used | [
"Finds",
"the",
"SQLAlchemy",
"dialect",
"in",
"use",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dialect.py#L65-L83 | train | 53,097 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dialect.py | get_dialect_name | def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str:
"""
Finds the name of the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy dialect name being used
"""
dialect = get_dialect(mixed)
# noinspection PyUnresolvedReferences
return dialect.name | python | def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str:
"""
Finds the name of the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy dialect name being used
"""
dialect = get_dialect(mixed)
# noinspection PyUnresolvedReferences
return dialect.name | [
"def",
"get_dialect_name",
"(",
"mixed",
":",
"Union",
"[",
"SQLCompiler",
",",
"Engine",
",",
"Dialect",
"]",
")",
"->",
"str",
":",
"dialect",
"=",
"get_dialect",
"(",
"mixed",
")",
"# noinspection PyUnresolvedReferences",
"return",
"dialect",
".",
"name"
] | Finds the name of the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy dialect name being used | [
"Finds",
"the",
"name",
"of",
"the",
"SQLAlchemy",
"dialect",
"in",
"use",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dialect.py#L86-L98 | train | 53,098 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dialect.py | quote_identifier | def quote_identifier(identifier: str,
mixed: Union[SQLCompiler, Engine, Dialect]) -> str:
"""
Converts an SQL identifier to a quoted version, via the SQL dialect in
use.
Args:
identifier: the identifier to be quoted
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns:
the quoted identifier
"""
# See also http://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/orm.html # noqa
return get_preparer(mixed).quote(identifier) | python | def quote_identifier(identifier: str,
mixed: Union[SQLCompiler, Engine, Dialect]) -> str:
"""
Converts an SQL identifier to a quoted version, via the SQL dialect in
use.
Args:
identifier: the identifier to be quoted
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns:
the quoted identifier
"""
# See also http://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/orm.html # noqa
return get_preparer(mixed).quote(identifier) | [
"def",
"quote_identifier",
"(",
"identifier",
":",
"str",
",",
"mixed",
":",
"Union",
"[",
"SQLCompiler",
",",
"Engine",
",",
"Dialect",
"]",
")",
"->",
"str",
":",
"# See also http://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/orm.html # ... | Converts an SQL identifier to a quoted version, via the SQL dialect in
use.
Args:
identifier: the identifier to be quoted
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns:
the quoted identifier | [
"Converts",
"an",
"SQL",
"identifier",
"to",
"a",
"quoted",
"version",
"via",
"the",
"SQL",
"dialect",
"in",
"use",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dialect.py#L119-L135 | train | 53,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.