repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
dictlist_convert_to_float
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a float. If that fails, convert it to ``None``. """ for d in dict_list: try: d[key] = float(d[key]) ...
python
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a float. If that fails, convert it to ``None``. """ for d in dict_list: try: d[key] = float(d[key]) ...
[ "def", "dictlist_convert_to_float", "(", "dict_list", ":", "Iterable", "[", "Dict", "]", ",", "key", ":", "str", ")", "->", "None", ":", "for", "d", "in", "dict_list", ":", "try", ":", "d", "[", "key", "]", "=", "float", "(", "d", "[", "key", "]", ...
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a float. If that fails, convert it to ``None``.
[ "Process", "an", "iterable", "of", "dictionaries", ".", "For", "each", "dictionary", "d", "convert", "(", "in", "place", ")", "d", "[", "key", "]", "to", "a", "float", ".", "If", "that", "fails", "convert", "it", "to", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L540-L549
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
dictlist_convert_to_bool
def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a bool. If that fails, convert it to ``None``. """ for d in dict_list: # d[key] = True if d[key] == "Y" else False ...
python
def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a bool. If that fails, convert it to ``None``. """ for d in dict_list: # d[key] = True if d[key] == "Y" else False ...
[ "def", "dictlist_convert_to_bool", "(", "dict_list", ":", "Iterable", "[", "Dict", "]", ",", "key", ":", "str", ")", "->", "None", ":", "for", "d", "in", "dict_list", ":", "# d[key] = True if d[key] == \"Y\" else False", "d", "[", "key", "]", "=", "1", "if",...
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a bool. If that fails, convert it to ``None``.
[ "Process", "an", "iterable", "of", "dictionaries", ".", "For", "each", "dictionary", "d", "convert", "(", "in", "place", ")", "d", "[", "key", "]", "to", "a", "bool", ".", "If", "that", "fails", "convert", "it", "to", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L552-L559
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
dictlist_replace
def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, change (in place) ``d[key]`` to ``value``. """ for d in dict_list: d[key] = value
python
def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, change (in place) ``d[key]`` to ``value``. """ for d in dict_list: d[key] = value
[ "def", "dictlist_replace", "(", "dict_list", ":", "Iterable", "[", "Dict", "]", ",", "key", ":", "str", ",", "value", ":", "Any", ")", "->", "None", ":", "for", "d", "in", "dict_list", ":", "d", "[", "key", "]", "=", "value" ]
Process an iterable of dictionaries. For each dictionary ``d``, change (in place) ``d[key]`` to ``value``.
[ "Process", "an", "iterable", "of", "dictionaries", ".", "For", "each", "dictionary", "d", "change", "(", "in", "place", ")", "d", "[", "key", "]", "to", "value", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L562-L568
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
dictlist_wipe_key
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, delete ``d[key]`` if it exists. """ for d in dict_list: d.pop(key, None)
python
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, delete ``d[key]`` if it exists. """ for d in dict_list: d.pop(key, None)
[ "def", "dictlist_wipe_key", "(", "dict_list", ":", "Iterable", "[", "Dict", "]", ",", "key", ":", "str", ")", "->", "None", ":", "for", "d", "in", "dict_list", ":", "d", ".", "pop", "(", "key", ",", "None", ")" ]
Process an iterable of dictionaries. For each dictionary ``d``, delete ``d[key]`` if it exists.
[ "Process", "an", "iterable", "of", "dictionaries", ".", "For", "each", "dictionary", "d", "delete", "d", "[", "key", "]", "if", "it", "exists", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L571-L577
RudolfCardinal/pythonlib
cardinal_pythonlib/django/function_cache.py
get_call_signature
def get_call_signature(fn: FunctionType, args: ArgsType, kwargs: KwargsType, debug_cache: bool = False) -> str: """ Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable ...
python
def get_call_signature(fn: FunctionType, args: ArgsType, kwargs: KwargsType, debug_cache: bool = False) -> str: """ Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable ...
[ "def", "get_call_signature", "(", "fn", ":", "FunctionType", ",", "args", ":", "ArgsType", ",", "kwargs", ":", "KwargsType", ",", "debug_cache", ":", "bool", "=", "False", ")", "->", "str", ":", "# Note that the function won't have the __self__ argument (as in", "# ...
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use indirectly as a cache key. The string is a JSON representation. See ``make_cache_key`` for a more suitable actual cache key.
[ "Takes", "a", "function", "and", "its", "args", "/", "kwargs", "and", "produces", "a", "string", "description", "of", "the", "function", "call", "(", "the", "call", "signature", ")", "suitable", "for", "use", "indirectly", "as", "a", "cache", "key", ".", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/function_cache.py#L47-L70
RudolfCardinal/pythonlib
cardinal_pythonlib/django/function_cache.py
make_cache_key
def make_cache_key(call_signature: str, debug_cache: bool = False) -> str: """ Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use as a cache key. The string is an MD5 hash of the JSON-encoded call signatur...
python
def make_cache_key(call_signature: str, debug_cache: bool = False) -> str: """ Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use as a cache key. The string is an MD5 hash of the JSON-encoded call signatur...
[ "def", "make_cache_key", "(", "call_signature", ":", "str", ",", "debug_cache", ":", "bool", "=", "False", ")", "->", "str", ":", "key", "=", "hashlib", ".", "md5", "(", "call_signature", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ...
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use as a cache key. The string is an MD5 hash of the JSON-encoded call signature. The logic behind these decisions is as follows: - We have a bunch of components of arbitrary t...
[ "Takes", "a", "function", "and", "its", "args", "/", "kwargs", "and", "produces", "a", "string", "description", "of", "the", "function", "call", "(", "the", "call", "signature", ")", "suitable", "for", "use", "as", "a", "cache", "key", ".", "The", "strin...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/function_cache.py#L73-L110
RudolfCardinal/pythonlib
cardinal_pythonlib/django/function_cache.py
django_cache_function
def django_cache_function(timeout: int = 5 * 60, cache_key: str = '', debug_cache: bool = False): """ Decorator to add caching to a function in Django. Uses the Django default cache. Args: timeout: timeout in seconds; use None for "never expi...
python
def django_cache_function(timeout: int = 5 * 60, cache_key: str = '', debug_cache: bool = False): """ Decorator to add caching to a function in Django. Uses the Django default cache. Args: timeout: timeout in seconds; use None for "never expi...
[ "def", "django_cache_function", "(", "timeout", ":", "int", "=", "5", "*", "60", ",", "cache_key", ":", "str", "=", "''", ",", "debug_cache", ":", "bool", "=", "False", ")", ":", "cache_key", "=", "cache_key", "or", "None", "def", "decorator", "(", "fn...
Decorator to add caching to a function in Django. Uses the Django default cache. Args: timeout: timeout in seconds; use None for "never expire", as 0 means "do not cache". cache_key: optional cache key to use (if falsy, we'll invent one) debug_cache: show hits/misses?
[ "Decorator", "to", "add", "caching", "to", "a", "function", "in", "Django", ".", "Uses", "the", "Django", "default", "cache", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/function_cache.py#L113-L179
davenquinn/Attitude
attitude/coordinates/rotations.py
transform
def transform(v1, v2): """ Create an affine transformation matrix that maps vector 1 onto vector 2 https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another """ theta = angle(v1,v2) x = N.cross(v1,v2) x = x / N.linalg.norm(x) A = N.array([ [0, -x[2],...
python
def transform(v1, v2): """ Create an affine transformation matrix that maps vector 1 onto vector 2 https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another """ theta = angle(v1,v2) x = N.cross(v1,v2) x = x / N.linalg.norm(x) A = N.array([ [0, -x[2],...
[ "def", "transform", "(", "v1", ",", "v2", ")", ":", "theta", "=", "angle", "(", "v1", ",", "v2", ")", "x", "=", "N", ".", "cross", "(", "v1", ",", "v2", ")", "x", "=", "x", "/", "N", ".", "linalg", ".", "norm", "(", "x", ")", "A", "=", ...
Create an affine transformation matrix that maps vector 1 onto vector 2 https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another
[ "Create", "an", "affine", "transformation", "matrix", "that", "maps", "vector", "1", "onto", "vector", "2" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/coordinates/rotations.py#L11-L28
davenquinn/Attitude
attitude/coordinates/rotations.py
cartesian
def cartesian(lon, lat): """ Converts spherical positions in (lon, lat) to cartesian coordiantes [x,y,z]. For the purposes of this library's focus on orientations, this operates in a *north = vertical* framework. That is, positions around the equator are in the [x,y] plane, and dipping planes occur ...
python
def cartesian(lon, lat): """ Converts spherical positions in (lon, lat) to cartesian coordiantes [x,y,z]. For the purposes of this library's focus on orientations, this operates in a *north = vertical* framework. That is, positions around the equator are in the [x,y] plane, and dipping planes occur ...
[ "def", "cartesian", "(", "lon", ",", "lat", ")", ":", "return", "N", ".", "array", "(", "[", "N", ".", "cos", "(", "lat", ")", "*", "N", ".", "cos", "(", "lon", ")", ",", "N", ".", "cos", "(", "lat", ")", "*", "N", ".", "sin", "(", "lon",...
Converts spherical positions in (lon, lat) to cartesian coordiantes [x,y,z]. For the purposes of this library's focus on orientations, this operates in a *north = vertical* framework. That is, positions around the equator are in the [x,y] plane, and dipping planes occur with higher latitudes. This is i...
[ "Converts", "spherical", "positions", "in", "(", "lon", "lat", ")", "to", "cartesian", "coordiantes", "[", "x", "y", "z", "]", ".", "For", "the", "purposes", "of", "this", "library", "s", "focus", "on", "orientations", "this", "operates", "in", "a", "*",...
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/coordinates/rotations.py#L40-L56
ivanprjcts/sdklib
sdklib/http/authorization.py
x_11paths_authorization
def x_11paths_authorization(app_id, secret, context, utc=None): """ Calculate the authentication headers to be sent with a request to the API. :param app_id: :param secret: :param context :param utc: :return: array a map with the Authorization and Date headers needed to sign a Latch API req...
python
def x_11paths_authorization(app_id, secret, context, utc=None): """ Calculate the authentication headers to be sent with a request to the API. :param app_id: :param secret: :param context :param utc: :return: array a map with the Authorization and Date headers needed to sign a Latch API req...
[ "def", "x_11paths_authorization", "(", "app_id", ",", "secret", ",", "context", ",", "utc", "=", "None", ")", ":", "utc", "=", "utc", "or", "context", ".", "headers", "[", "X_11PATHS_DATE_HEADER_NAME", "]", "url_path", "=", "ensure_url_path_starts_with_slash", "...
Calculate the authentication headers to be sent with a request to the API. :param app_id: :param secret: :param context :param utc: :return: array a map with the Authorization and Date headers needed to sign a Latch API request
[ "Calculate", "the", "authentication", "headers", "to", "be", "sent", "with", "a", "request", "to", "the", "API", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/authorization.py#L35-L63
ivanprjcts/sdklib
sdklib/http/authorization.py
_sign_data
def _sign_data(secret, data): """ Sign data. :param data: the string to sign :return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key. """ sha1_hash = hmac.new(secret.encode(), data.encode(), sha1) return binascii.b2a_base64(sha1_hash...
python
def _sign_data(secret, data): """ Sign data. :param data: the string to sign :return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key. """ sha1_hash = hmac.new(secret.encode(), data.encode(), sha1) return binascii.b2a_base64(sha1_hash...
[ "def", "_sign_data", "(", "secret", ",", "data", ")", ":", "sha1_hash", "=", "hmac", ".", "new", "(", "secret", ".", "encode", "(", ")", ",", "data", ".", "encode", "(", ")", ",", "sha1", ")", "return", "binascii", ".", "b2a_base64", "(", "sha1_hash"...
Sign data. :param data: the string to sign :return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key.
[ "Sign", "data", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/authorization.py#L66-L74
ivanprjcts/sdklib
sdklib/http/authorization.py
_get_11paths_serialized_headers
def _get_11paths_serialized_headers(x_headers): """ Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an...
python
def _get_11paths_serialized_headers(x_headers): """ Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an...
[ "def", "_get_11paths_serialized_headers", "(", "x_headers", ")", ":", "if", "x_headers", ":", "headers", "=", "to_key_val_list", "(", "x_headers", ",", "sort", "=", "True", ",", "insensitive", "=", "True", ")", "serialized_headers", "=", "\"\"", "for", "key", ...
Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an empty string if no headers are passed, or None if there's a...
[ "Prepares", "and", "returns", "a", "string", "ready", "to", "be", "signed", "from", "the", "11", "-", "paths", "specific", "HTTP", "headers", "received", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/authorization.py#L96-L113
davenquinn/Attitude
attitude/geom/transform.py
rotate_2D
def rotate_2D(angle): """ Returns a 2x2 transformation matrix to rotate by an angle in two dimensions """ return N.array([[N.cos(angle),-N.sin(angle)], [N.sin(angle),N.cos(angle)]])
python
def rotate_2D(angle): """ Returns a 2x2 transformation matrix to rotate by an angle in two dimensions """ return N.array([[N.cos(angle),-N.sin(angle)], [N.sin(angle),N.cos(angle)]])
[ "def", "rotate_2D", "(", "angle", ")", ":", "return", "N", ".", "array", "(", "[", "[", "N", ".", "cos", "(", "angle", ")", ",", "-", "N", ".", "sin", "(", "angle", ")", "]", ",", "[", "N", ".", "sin", "(", "angle", ")", ",", "N", ".", "c...
Returns a 2x2 transformation matrix to rotate by an angle in two dimensions
[ "Returns", "a", "2x2", "transformation", "matrix", "to", "rotate", "by", "an", "angle", "in", "two", "dimensions" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/transform.py#L3-L9
davenquinn/Attitude
attitude/display/hyperbola.py
apparent_dip_correction
def apparent_dip_correction(axes): """ Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip """ a1 = axes[0].copy() a1[-1] = 0 cosa = angle(axes[0],a1,cos=True) _ = 1-cosa**2 if _ > 1e-12: sina = N.sqrt(_) if cosa < 0...
python
def apparent_dip_correction(axes): """ Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip """ a1 = axes[0].copy() a1[-1] = 0 cosa = angle(axes[0],a1,cos=True) _ = 1-cosa**2 if _ > 1e-12: sina = N.sqrt(_) if cosa < 0...
[ "def", "apparent_dip_correction", "(", "axes", ")", ":", "a1", "=", "axes", "[", "0", "]", ".", "copy", "(", ")", "a1", "[", "-", "1", "]", "=", "0", "cosa", "=", "angle", "(", "axes", "[", "0", "]", ",", "a1", ",", "cos", "=", "True", ")", ...
Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip
[ "Produces", "a", "two", "-", "dimensional", "rotation", "matrix", "that", "rotates", "a", "projected", "dataset", "to", "correct", "for", "apparent", "dip" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/hyperbola.py#L9-L31
davenquinn/Attitude
attitude/display/hyperbola.py
hyperbolic_errors
def hyperbolic_errors(hyp_axes, xvals, transformation=None, axes=None, means=None, correct_apparent_dip=True, reverse=False): """ Returns a function that can be used to create a view of the hyperbolic error ellipse from a specific direction. ...
python
def hyperbolic_errors(hyp_axes, xvals, transformation=None, axes=None, means=None, correct_apparent_dip=True, reverse=False): """ Returns a function that can be used to create a view of the hyperbolic error ellipse from a specific direction. ...
[ "def", "hyperbolic_errors", "(", "hyp_axes", ",", "xvals", ",", "transformation", "=", "None", ",", "axes", "=", "None", ",", "means", "=", "None", ",", "correct_apparent_dip", "=", "True", ",", "reverse", "=", "False", ")", ":", "if", "means", "is", "No...
Returns a function that can be used to create a view of the hyperbolic error ellipse from a specific direction. This creates a hyperbolic quadric and slices it to form a conic on a 2d cartesian plane aligned with the requested direction. A function is returned that takes x values (distance along nomin...
[ "Returns", "a", "function", "that", "can", "be", "used", "to", "create", "a", "view", "of", "the", "hyperbolic", "error", "ellipse", "from", "a", "specific", "direction", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/hyperbola.py#L33-L103
davenquinn/Attitude
attitude/display/hyperbola.py
hyperbola_values
def hyperbola_values(hyp_axes, xvals): """ kwargs: transformation rotation to apply to quadric prior to slicing (e.g. transformation into 'world' coordinates axes axes on which to slice the data """ A = N.sqrt(hyp_axes) return A[1]*N.cosh(N.arcsinh...
python
def hyperbola_values(hyp_axes, xvals): """ kwargs: transformation rotation to apply to quadric prior to slicing (e.g. transformation into 'world' coordinates axes axes on which to slice the data """ A = N.sqrt(hyp_axes) return A[1]*N.cosh(N.arcsinh...
[ "def", "hyperbola_values", "(", "hyp_axes", ",", "xvals", ")", ":", "A", "=", "N", ".", "sqrt", "(", "hyp_axes", ")", "return", "A", "[", "1", "]", "*", "N", ".", "cosh", "(", "N", ".", "arcsinh", "(", "xvals", "/", "A", "[", "0", "]", ")", "...
kwargs: transformation rotation to apply to quadric prior to slicing (e.g. transformation into 'world' coordinates axes axes on which to slice the data
[ "kwargs", ":", "transformation", "rotation", "to", "apply", "to", "quadric", "prior", "to", "slicing", "(", "e", ".", "g", ".", "transformation", "into", "world", "coordinates", "axes", "axes", "on", "which", "to", "slice", "the", "data" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/hyperbola.py#L193-L201
RudolfCardinal/pythonlib
cardinal_pythonlib/sizeformatter.py
sizeof_fmt
def sizeof_fmt(num: float, suffix: str = 'B') -> str: """ Formats a number of bytes in a human-readable binary format (e.g. ``2048`` becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841. """ for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'): if abs(num) < 1024.0: ...
python
def sizeof_fmt(num: float, suffix: str = 'B') -> str: """ Formats a number of bytes in a human-readable binary format (e.g. ``2048`` becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841. """ for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'): if abs(num) < 1024.0: ...
[ "def", "sizeof_fmt", "(", "num", ":", "float", ",", "suffix", ":", "str", "=", "'B'", ")", "->", "str", ":", "for", "unit", "in", "(", "''", ",", "'Ki'", ",", "'Mi'", ",", "'Gi'", ",", "'Ti'", ",", "'Pi'", ",", "'Ei'", ",", "'Zi'", ")", ":", ...
Formats a number of bytes in a human-readable binary format (e.g. ``2048`` becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
[ "Formats", "a", "number", "of", "bytes", "in", "a", "human", "-", "readable", "binary", "format", "(", "e", ".", "g", ".", "2048", "becomes", "2", "KiB", ")", ";", "from", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "109484...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sizeformatter.py#L29-L38
RudolfCardinal/pythonlib
cardinal_pythonlib/sizeformatter.py
bytes2human
def bytes2human(n: Union[int, float], format: str = '%(value).1f %(symbol)s', symbols: str = 'customary') -> str: """ Converts a number of bytes into a human-readable format. From http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/. Ar...
python
def bytes2human(n: Union[int, float], format: str = '%(value).1f %(symbol)s', symbols: str = 'customary') -> str: """ Converts a number of bytes into a human-readable format. From http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/. Ar...
[ "def", "bytes2human", "(", "n", ":", "Union", "[", "int", ",", "float", "]", ",", "format", ":", "str", "=", "'%(value).1f %(symbol)s'", ",", "symbols", ":", "str", "=", "'customary'", ")", "->", "str", ":", "# noqa", "n", "=", "int", "(", "n", ")", ...
Converts a number of bytes into a human-readable format. From http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/. Args: n: number of bytes format: a format specification string symbols: can be one of ``"customary"``, ``"customary_ext"``, ``"iec"`` ...
[ "Converts", "a", "number", "of", "bytes", "into", "a", "human", "-", "readable", "format", ".", "From", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "recipes", "/", "578019", "-", "bytes", "-", "to", "-", "human", "-", "human", "-"...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sizeformatter.py#L52-L113
RudolfCardinal/pythonlib
cardinal_pythonlib/sizeformatter.py
human2bytes
def human2bytes(s: str) -> int: """ Modified from http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/. Attempts to guess the string format based on default symbols set and return the corresponding bytes as an integer. When unable to recognize the format, :exc...
python
def human2bytes(s: str) -> int: """ Modified from http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/. Attempts to guess the string format based on default symbols set and return the corresponding bytes as an integer. When unable to recognize the format, :exc...
[ "def", "human2bytes", "(", "s", ":", "str", ")", "->", "int", ":", "# noqa", "if", "not", "s", ":", "raise", "ValueError", "(", "\"Can't interpret {!r} as integer\"", ".", "format", "(", "s", ")", ")", "try", ":", "return", "int", "(", "s", ")", "excep...
Modified from http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/. Attempts to guess the string format based on default symbols set and return the corresponding bytes as an integer. When unable to recognize the format, :exc:`ValueError` is raised. >>> human2by...
[ "Modified", "from", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "recipes", "/", "578019", "-", "bytes", "-", "to", "-", "human", "-", "human", "-", "to", "-", "bytes", "-", "converter", "/", ".", "Attempts", "to", "guess", "the", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sizeformatter.py#L116-L173
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
get_all_dependencies
def get_all_dependencies(metadata: MetaData, extra_dependencies: List[TableDependency] = None, sort: bool = True) \ -> List[TableDependency]: """ Describes how the tables found in the metadata depend on each other. (If table B contains a foreign key ...
python
def get_all_dependencies(metadata: MetaData, extra_dependencies: List[TableDependency] = None, sort: bool = True) \ -> List[TableDependency]: """ Describes how the tables found in the metadata depend on each other. (If table B contains a foreign key ...
[ "def", "get_all_dependencies", "(", "metadata", ":", "MetaData", ",", "extra_dependencies", ":", "List", "[", "TableDependency", "]", "=", "None", ",", "sort", ":", "bool", "=", "True", ")", "->", "List", "[", "TableDependency", "]", ":", "extra_dependencies",...
Describes how the tables found in the metadata depend on each other. (If table B contains a foreign key to table A, for example, then B depends on A.) Args: metadata: the metadata to inspect extra_dependencies: additional table dependencies to specify manually sort: sort into alphab...
[ "Describes", "how", "the", "tables", "found", "in", "the", "metadata", "depend", "on", "each", "other", ".", "(", "If", "table", "B", "contains", "a", "foreign", "key", "to", "table", "A", "for", "example", "then", "B", "depends", "on", "A", ".", ")" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L207-L256
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
classify_tables_by_dependency_type
def classify_tables_by_dependency_type( metadata: MetaData, extra_dependencies: List[TableDependency] = None, sort: bool = True) \ -> List[TableDependencyClassification]: """ Inspects a metadata object (optionally adding other specified dependencies) and returns a list of obj...
python
def classify_tables_by_dependency_type( metadata: MetaData, extra_dependencies: List[TableDependency] = None, sort: bool = True) \ -> List[TableDependencyClassification]: """ Inspects a metadata object (optionally adding other specified dependencies) and returns a list of obj...
[ "def", "classify_tables_by_dependency_type", "(", "metadata", ":", "MetaData", ",", "extra_dependencies", ":", "List", "[", "TableDependency", "]", "=", "None", ",", "sort", ":", "bool", "=", "True", ")", "->", "List", "[", "TableDependencyClassification", "]", ...
Inspects a metadata object (optionally adding other specified dependencies) and returns a list of objects describing their dependencies. Args: metadata: the :class:`MetaData` to inspect extra_dependencies: additional dependencies sort: sort the results by table name? Returns: ...
[ "Inspects", "a", "metadata", "object", "(", "optionally", "adding", "other", "specified", "dependencies", ")", "and", "returns", "a", "list", "of", "objects", "describing", "their", "dependencies", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L369-L438
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
merge_db
def merge_db(base_class: Type, src_engine: Engine, dst_session: Session, allow_missing_src_tables: bool = True, allow_missing_src_columns: bool = True, translate_fn: Callable[[TranslationContext], None] = None, skip_tables: List[TableIdentity...
python
def merge_db(base_class: Type, src_engine: Engine, dst_session: Session, allow_missing_src_tables: bool = True, allow_missing_src_columns: bool = True, translate_fn: Callable[[TranslationContext], None] = None, skip_tables: List[TableIdentity...
[ "def", "merge_db", "(", "base_class", ":", "Type", ",", "src_engine", ":", "Engine", ",", "dst_session", ":", "Session", ",", "allow_missing_src_tables", ":", "bool", "=", "True", ",", "allow_missing_src_columns", ":", "bool", "=", "True", ",", "translate_fn", ...
Copies an entire database as far as it is described by ``metadata`` and ``base_class``, from SQLAlchemy ORM session ``src_session`` to ``dst_session``, and in the process: - creates new primary keys at the destination, or raises an error if it doesn't know how (typically something like: ``Field 'name...
[ "Copies", "an", "entire", "database", "as", "far", "as", "it", "is", "described", "by", "metadata", "and", "base_class", "from", "SQLAlchemy", "ORM", "session", "src_session", "to", "dst_session", "and", "in", "the", "process", ":" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L541-L945
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
TableDependency.set_metadata
def set_metadata(self, metadata: MetaData) -> None: """ Sets the metadata for the parent and child tables. """ self._parent.set_metadata(metadata) self._child.set_metadata(metadata)
python
def set_metadata(self, metadata: MetaData) -> None: """ Sets the metadata for the parent and child tables. """ self._parent.set_metadata(metadata) self._child.set_metadata(metadata)
[ "def", "set_metadata", "(", "self", ",", "metadata", ":", "MetaData", ")", "->", "None", ":", "self", ".", "_parent", ".", "set_metadata", "(", "metadata", ")", "self", ".", "_child", ".", "set_metadata", "(", "metadata", ")" ]
Sets the metadata for the parent and child tables.
[ "Sets", "the", "metadata", "for", "the", "parent", "and", "child", "tables", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L156-L161
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
TableDependency.set_metadata_if_none
def set_metadata_if_none(self, metadata: MetaData) -> None: """ Sets the metadata for the parent and child tables, unless they were set already. """ self._parent.set_metadata_if_none(metadata) self._child.set_metadata_if_none(metadata)
python
def set_metadata_if_none(self, metadata: MetaData) -> None: """ Sets the metadata for the parent and child tables, unless they were set already. """ self._parent.set_metadata_if_none(metadata) self._child.set_metadata_if_none(metadata)
[ "def", "set_metadata_if_none", "(", "self", ",", "metadata", ":", "MetaData", ")", "->", "None", ":", "self", ".", "_parent", ".", "set_metadata_if_none", "(", "metadata", ")", "self", ".", "_child", ".", "set_metadata_if_none", "(", "metadata", ")" ]
Sets the metadata for the parent and child tables, unless they were set already.
[ "Sets", "the", "metadata", "for", "the", "parent", "and", "child", "tables", "unless", "they", "were", "set", "already", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L163-L169
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
TableDependencyClassification.set_circular
def set_circular(self, circular: bool, chain: List[Table] = None) -> None: """ Mark this table as circular (or not). Args: circular: is it circular? chain: if it's circular, this should be the list of tables participating in the circular chain """...
python
def set_circular(self, circular: bool, chain: List[Table] = None) -> None: """ Mark this table as circular (or not). Args: circular: is it circular? chain: if it's circular, this should be the list of tables participating in the circular chain """...
[ "def", "set_circular", "(", "self", ",", "circular", ":", "bool", ",", "chain", ":", "List", "[", "Table", "]", "=", "None", ")", "->", "None", ":", "self", ".", "circular", "=", "circular", "self", ".", "circular_chain", "=", "chain", "or", "[", "]"...
Mark this table as circular (or not). Args: circular: is it circular? chain: if it's circular, this should be the list of tables participating in the circular chain
[ "Mark", "this", "table", "as", "circular", "(", "or", "not", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L325-L335
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
TableDependencyClassification.description
def description(self) -> str: """ Short description. """ if self.is_parent and self.is_child: desc = "parent+child" elif self.is_parent: desc = "parent" elif self.is_child: desc = "child" else: desc = "standalone" ...
python
def description(self) -> str: """ Short description. """ if self.is_parent and self.is_child: desc = "parent+child" elif self.is_parent: desc = "parent" elif self.is_child: desc = "child" else: desc = "standalone" ...
[ "def", "description", "(", "self", ")", "->", "str", ":", "if", "self", ".", "is_parent", "and", "self", ".", "is_child", ":", "desc", "=", "\"parent+child\"", "elif", "self", ".", "is_parent", ":", "desc", "=", "\"parent\"", "elif", "self", ".", "is_chi...
Short description.
[ "Short", "description", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L345-L359
RudolfCardinal/pythonlib
cardinal_pythonlib/excel.py
excel_to_bytes
def excel_to_bytes(wb: Workbook) -> bytes: """ Obtain a binary version of an :class:`openpyxl.Workbook` representation of an Excel file. """ memfile = io.BytesIO() wb.save(memfile) return memfile.getvalue()
python
def excel_to_bytes(wb: Workbook) -> bytes: """ Obtain a binary version of an :class:`openpyxl.Workbook` representation of an Excel file. """ memfile = io.BytesIO() wb.save(memfile) return memfile.getvalue()
[ "def", "excel_to_bytes", "(", "wb", ":", "Workbook", ")", "->", "bytes", ":", "memfile", "=", "io", ".", "BytesIO", "(", ")", "wb", ".", "save", "(", "memfile", ")", "return", "memfile", ".", "getvalue", "(", ")" ]
Obtain a binary version of an :class:`openpyxl.Workbook` representation of an Excel file.
[ "Obtain", "a", "binary", "version", "of", "an", ":", "class", ":", "openpyxl", ".", "Workbook", "representation", "of", "an", "Excel", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/excel.py#L35-L42
davenquinn/Attitude
attitude/coordinates/__init__.py
spherical
def spherical(coordinates): """No error is propagated""" c = coordinates r = N.linalg.norm(c,axis=0) theta = N.arccos(c[2]/r) phi = N.arctan2(c[1],c[0]) return N.column_stack((r,theta,phi))
python
def spherical(coordinates): """No error is propagated""" c = coordinates r = N.linalg.norm(c,axis=0) theta = N.arccos(c[2]/r) phi = N.arctan2(c[1],c[0]) return N.column_stack((r,theta,phi))
[ "def", "spherical", "(", "coordinates", ")", ":", "c", "=", "coordinates", "r", "=", "N", ".", "linalg", ".", "norm", "(", "c", ",", "axis", "=", "0", ")", "theta", "=", "N", ".", "arccos", "(", "c", "[", "2", "]", "/", "r", ")", "phi", "=", ...
No error is propagated
[ "No", "error", "is", "propagated" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/coordinates/__init__.py#L3-L9
davenquinn/Attitude
attitude/coordinates/__init__.py
centered
def centered(coordinates): """ Centers coordinate distribution with respect to its mean on all three axes. This is used as the input to the regression model, so it can be converted easily into radial coordinates. """ coordinates = N.array(coordinates) means = N.mean(coordinates,axis=0) ...
python
def centered(coordinates): """ Centers coordinate distribution with respect to its mean on all three axes. This is used as the input to the regression model, so it can be converted easily into radial coordinates. """ coordinates = N.array(coordinates) means = N.mean(coordinates,axis=0) ...
[ "def", "centered", "(", "coordinates", ")", ":", "coordinates", "=", "N", ".", "array", "(", "coordinates", ")", "means", "=", "N", ".", "mean", "(", "coordinates", ",", "axis", "=", "0", ")", "return", "coordinates", "-", "means" ]
Centers coordinate distribution with respect to its mean on all three axes. This is used as the input to the regression model, so it can be converted easily into radial coordinates.
[ "Centers", "coordinate", "distribution", "with", "respect", "to", "its", "mean", "on", "all", "three", "axes", ".", "This", "is", "used", "as", "the", "input", "to", "the", "regression", "model", "so", "it", "can", "be", "converted", "easily", "into", "rad...
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/coordinates/__init__.py#L19-L28
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
add_http_headers_for_attachment
def add_http_headers_for_attachment(response: HttpResponse, offered_filename: str = None, content_type: str = None, as_attachment: bool = False, as_inline: bool = False, ...
python
def add_http_headers_for_attachment(response: HttpResponse, offered_filename: str = None, content_type: str = None, as_attachment: bool = False, as_inline: bool = False, ...
[ "def", "add_http_headers_for_attachment", "(", "response", ":", "HttpResponse", ",", "offered_filename", ":", "str", "=", "None", ",", "content_type", ":", "str", "=", "None", ",", "as_attachment", ":", "bool", "=", "False", ",", "as_inline", ":", "bool", "=",...
Add HTTP headers to a Django response class object. Args: response: ``HttpResponse`` instance offered_filename: filename that the client browser will suggest content_type: HTTP content type as_attachment: if True, browsers will generally save to disk. If False, they may...
[ "Add", "HTTP", "headers", "to", "a", "Django", "response", "class", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L58-L93
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
serve_file
def serve_file(path_to_file: str, offered_filename: str = None, content_type: str = None, as_attachment: bool = False, as_inline: bool = False) -> HttpResponseBase: """ Serve up a file from disk. Two methods (chosen by ``settings.XSENDFILE``): ...
python
def serve_file(path_to_file: str, offered_filename: str = None, content_type: str = None, as_attachment: bool = False, as_inline: bool = False) -> HttpResponseBase: """ Serve up a file from disk. Two methods (chosen by ``settings.XSENDFILE``): ...
[ "def", "serve_file", "(", "path_to_file", ":", "str", ",", "offered_filename", ":", "str", "=", "None", ",", "content_type", ":", "str", "=", "None", ",", "as_attachment", ":", "bool", "=", "False", ",", "as_inline", ":", "bool", "=", "False", ")", "->",...
Serve up a file from disk. Two methods (chosen by ``settings.XSENDFILE``): (a) serve directly (b) serve by asking the web server to do so via the X-SendFile directive.
[ "Serve", "up", "a", "file", "from", "disk", ".", "Two", "methods", "(", "chosen", "by", "settings", ".", "XSENDFILE", ")", ":", "(", "a", ")", "serve", "directly", "(", "b", ")", "serve", "by", "asking", "the", "web", "server", "to", "do", "so", "v...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L96-L125
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
serve_buffer
def serve_buffer(data: bytes, offered_filename: str = None, content_type: str = None, as_attachment: bool = True, as_inline: bool = False) -> HttpResponse: """ Serve up binary data from a buffer. Options as for ``serve_file()``. """ ...
python
def serve_buffer(data: bytes, offered_filename: str = None, content_type: str = None, as_attachment: bool = True, as_inline: bool = False) -> HttpResponse: """ Serve up binary data from a buffer. Options as for ``serve_file()``. """ ...
[ "def", "serve_buffer", "(", "data", ":", "bytes", ",", "offered_filename", ":", "str", "=", "None", ",", "content_type", ":", "str", "=", "None", ",", "as_attachment", ":", "bool", "=", "True", ",", "as_inline", ":", "bool", "=", "False", ")", "->", "H...
Serve up binary data from a buffer. Options as for ``serve_file()``.
[ "Serve", "up", "binary", "data", "from", "a", "buffer", ".", "Options", "as", "for", "serve_file", "()", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L132-L148
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
add_download_filename
def add_download_filename(response: HttpResponse, filename: str) -> None: """ Adds a ``Content-Disposition`` header to the HTTP response to say that there is an attachment with the specified filename. """ # https://docs.djangoproject.com/en/1.9/howto/outputting-csv/ add_http_headers_for_attachme...
python
def add_download_filename(response: HttpResponse, filename: str) -> None: """ Adds a ``Content-Disposition`` header to the HTTP response to say that there is an attachment with the specified filename. """ # https://docs.djangoproject.com/en/1.9/howto/outputting-csv/ add_http_headers_for_attachme...
[ "def", "add_download_filename", "(", "response", ":", "HttpResponse", ",", "filename", ":", "str", ")", "->", "None", ":", "# https://docs.djangoproject.com/en/1.9/howto/outputting-csv/", "add_http_headers_for_attachment", "(", "response", ")", "response", "[", "'Content-Di...
Adds a ``Content-Disposition`` header to the HTTP response to say that there is an attachment with the specified filename.
[ "Adds", "a", "Content", "-", "Disposition", "header", "to", "the", "HTTP", "response", "to", "say", "that", "there", "is", "an", "attachment", "with", "the", "specified", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L155-L163
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
file_response
def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd content_type: str, filename: str) -> HttpResponse: """ Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment. """ re...
python
def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd content_type: str, filename: str) -> HttpResponse: """ Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment. """ re...
[ "def", "file_response", "(", "data", ":", "Union", "[", "bytes", ",", "str", "]", ",", "# HttpResponse encodes str if req'd", "content_type", ":", "str", ",", "filename", ":", "str", ")", "->", "HttpResponse", ":", "response", "=", "HttpResponse", "(", "data",...
Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment.
[ "Returns", "an", "HttpResponse", "with", "an", "attachment", "containing", "the", "specified", "data", "with", "the", "specified", "filename", "as", "an", "attachment", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L166-L175
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
serve_concatenated_pdf_from_disk
def serve_concatenated_pdf_from_disk( filenames: Iterable[str], offered_filename: str = "crate_download.pdf", **kwargs) -> HttpResponse: """ Concatenates PDFs from disk and serves them. """ pdf = get_concatenated_pdf_from_disk(filenames, **kwargs) return serve_buffer(pdf, ...
python
def serve_concatenated_pdf_from_disk( filenames: Iterable[str], offered_filename: str = "crate_download.pdf", **kwargs) -> HttpResponse: """ Concatenates PDFs from disk and serves them. """ pdf = get_concatenated_pdf_from_disk(filenames, **kwargs) return serve_buffer(pdf, ...
[ "def", "serve_concatenated_pdf_from_disk", "(", "filenames", ":", "Iterable", "[", "str", "]", ",", "offered_filename", ":", "str", "=", "\"crate_download.pdf\"", ",", "*", "*", "kwargs", ")", "->", "HttpResponse", ":", "pdf", "=", "get_concatenated_pdf_from_disk", ...
Concatenates PDFs from disk and serves them.
[ "Concatenates", "PDFs", "from", "disk", "and", "serves", "them", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L182-L194
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
serve_pdf_from_html
def serve_pdf_from_html(html: str, offered_filename: str = "test.pdf", **kwargs) -> HttpResponse: """ Same args as ``pdf_from_html()``. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish. """ pdf = get_pdf_from_html(html, **kwargs) ret...
python
def serve_pdf_from_html(html: str, offered_filename: str = "test.pdf", **kwargs) -> HttpResponse: """ Same args as ``pdf_from_html()``. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish. """ pdf = get_pdf_from_html(html, **kwargs) ret...
[ "def", "serve_pdf_from_html", "(", "html", ":", "str", ",", "offered_filename", ":", "str", "=", "\"test.pdf\"", ",", "*", "*", "kwargs", ")", "->", "HttpResponse", ":", "pdf", "=", "get_pdf_from_html", "(", "html", ",", "*", "*", "kwargs", ")", "return", ...
Same args as ``pdf_from_html()``. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
[ "Same", "args", "as", "pdf_from_html", "()", ".", "WATCH", "OUT", ":", "may", "not", "apply", "e", ".", "g", ".", "wkhtmltopdf", "options", "as", "you", "d", "wish", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L197-L209
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
serve_concatenated_pdf_from_memory
def serve_concatenated_pdf_from_memory( pdf_plans: Iterable[PdfPlan], start_recto: bool = True, offered_filename: str = "crate_download.pdf") -> HttpResponse: """ Concatenates PDFs into memory and serves it. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish. """ ...
python
def serve_concatenated_pdf_from_memory( pdf_plans: Iterable[PdfPlan], start_recto: bool = True, offered_filename: str = "crate_download.pdf") -> HttpResponse: """ Concatenates PDFs into memory and serves it. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish. """ ...
[ "def", "serve_concatenated_pdf_from_memory", "(", "pdf_plans", ":", "Iterable", "[", "PdfPlan", "]", ",", "start_recto", ":", "bool", "=", "True", ",", "offered_filename", ":", "str", "=", "\"crate_download.pdf\"", ")", "->", "HttpResponse", ":", "pdf", "=", "ge...
Concatenates PDFs into memory and serves it. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
[ "Concatenates", "PDFs", "into", "memory", "and", "serves", "it", ".", "WATCH", "OUT", ":", "may", "not", "apply", "e", ".", "g", ".", "wkhtmltopdf", "options", "as", "you", "d", "wish", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L212-L225
RudolfCardinal/pythonlib
cardinal_pythonlib/django/files.py
auto_delete_files_on_instance_delete
def auto_delete_files_on_instance_delete(instance: Any, fieldnames: Iterable[str]) -> None: """ Deletes files from filesystem when object is deleted. """ for fieldname in fieldnames: filefield = getattr(instance, fieldname, None) if filefield: ...
python
def auto_delete_files_on_instance_delete(instance: Any, fieldnames: Iterable[str]) -> None: """ Deletes files from filesystem when object is deleted. """ for fieldname in fieldnames: filefield = getattr(instance, fieldname, None) if filefield: ...
[ "def", "auto_delete_files_on_instance_delete", "(", "instance", ":", "Any", ",", "fieldnames", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "fieldname", "in", "fieldnames", ":", "filefield", "=", "getattr", "(", "instance", ",", "fieldname"...
Deletes files from filesystem when object is deleted.
[ "Deletes", "files", "from", "filesystem", "when", "object", "is", "deleted", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/files.py#L43-L52
RudolfCardinal/pythonlib
cardinal_pythonlib/django/files.py
auto_delete_files_on_instance_change
def auto_delete_files_on_instance_change( instance: Any, fieldnames: Iterable[str], model_class) -> None: """ Deletes files from filesystem when object is changed. model_class: ``Type[Model]`` ... only the type checker in Py3.5 is broken; v.s. """ if not instance.pk: ...
python
def auto_delete_files_on_instance_change( instance: Any, fieldnames: Iterable[str], model_class) -> None: """ Deletes files from filesystem when object is changed. model_class: ``Type[Model]`` ... only the type checker in Py3.5 is broken; v.s. """ if not instance.pk: ...
[ "def", "auto_delete_files_on_instance_change", "(", "instance", ":", "Any", ",", "fieldnames", ":", "Iterable", "[", "str", "]", ",", "model_class", ")", "->", "None", ":", "if", "not", "instance", ".", "pk", ":", "return", "# instance not yet saved in database", ...
Deletes files from filesystem when object is changed. model_class: ``Type[Model]`` ... only the type checker in Py3.5 is broken; v.s.
[ "Deletes", "files", "from", "filesystem", "when", "object", "is", "changed", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/files.py#L73-L100
davenquinn/Attitude
attitude/orientation/pca.py
axis_transform
def axis_transform(pca_axes): """ Creates an affine transformation matrix to rotate data in PCA axes into Cartesian plane """ from_ = N.identity(3) to_ = pca_axes # Find inverse transform for forward transform # y = M x -> M = y (x)^(-1) # We don't need to do least-squares since ...
python
def axis_transform(pca_axes): """ Creates an affine transformation matrix to rotate data in PCA axes into Cartesian plane """ from_ = N.identity(3) to_ = pca_axes # Find inverse transform for forward transform # y = M x -> M = y (x)^(-1) # We don't need to do least-squares since ...
[ "def", "axis_transform", "(", "pca_axes", ")", ":", "from_", "=", "N", ".", "identity", "(", "3", ")", "to_", "=", "pca_axes", "# Find inverse transform for forward transform", "# y = M x -> M = y (x)^(-1)", "# We don't need to do least-squares since", "# there is a simple tr...
Creates an affine transformation matrix to rotate data in PCA axes into Cartesian plane
[ "Creates", "an", "affine", "transformation", "matrix", "to", "rotate", "data", "in", "PCA", "axes", "into", "Cartesian", "plane" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L57-L70
davenquinn/Attitude
attitude/orientation/pca.py
covariance_matrix
def covariance_matrix(self): """ Constructs the covariance matrix of input data from the singular value decomposition. Note that this is different than a covariance matrix of residuals, which is what we want for calculating fit errors. Using SVD output to compute covariance matrix X...
python
def covariance_matrix(self): """ Constructs the covariance matrix of input data from the singular value decomposition. Note that this is different than a covariance matrix of residuals, which is what we want for calculating fit errors. Using SVD output to compute covariance matrix X...
[ "def", "covariance_matrix", "(", "self", ")", ":", "a", "=", "N", ".", "dot", "(", "self", ".", "U", ",", "self", ".", "sigma", ")", "cv", "=", "N", ".", "dot", "(", "a", ",", "a", ".", "T", ")", "# This yields the covariance matrix in Cartesian", "#...
Constructs the covariance matrix of input data from the singular value decomposition. Note that this is different than a covariance matrix of residuals, which is what we want for calculating fit errors. Using SVD output to compute covariance matrix X=UΣV⊤ XX⊤XX⊤=(UΣV⊤)(UΣV⊤)⊤=(UΣV⊤)(VΣU...
[ "Constructs", "the", "covariance", "matrix", "of", "input", "data", "from", "the", "singular", "value", "decomposition", ".", "Note", "that", "this", "is", "different", "than", "a", "covariance", "matrix", "of", "residuals", "which", "is", "what", "we", "want"...
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L83-L108
davenquinn/Attitude
attitude/orientation/pca.py
PCAOrientation.U
def U(self): """ Property to support lazy evaluation of residuals """ if self._U is None: sinv = N.diag(1/self.singular_values) self._U = dot(self.arr,self.V.T,sinv) return self._U
python
def U(self): """ Property to support lazy evaluation of residuals """ if self._U is None: sinv = N.diag(1/self.singular_values) self._U = dot(self.arr,self.V.T,sinv) return self._U
[ "def", "U", "(", "self", ")", ":", "if", "self", ".", "_U", "is", "None", ":", "sinv", "=", "N", ".", "diag", "(", "1", "/", "self", ".", "singular_values", ")", "self", ".", "_U", "=", "dot", "(", "self", ".", "arr", ",", "self", ".", "V", ...
Property to support lazy evaluation of residuals
[ "Property", "to", "support", "lazy", "evaluation", "of", "residuals" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L240-L247
davenquinn/Attitude
attitude/orientation/pca.py
PCAOrientation.residuals
def residuals(self): """ Returns residuals of fit against all three data axes (singular values 1, 2, and 3). This takes the form of data along singular axis 3 (axes 1 and 2 define the plane) """ _ = self.rotated() _[:,-1] = 0 _ = N.dot(_,self.axes)...
python
def residuals(self): """ Returns residuals of fit against all three data axes (singular values 1, 2, and 3). This takes the form of data along singular axis 3 (axes 1 and 2 define the plane) """ _ = self.rotated() _[:,-1] = 0 _ = N.dot(_,self.axes)...
[ "def", "residuals", "(", "self", ")", ":", "_", "=", "self", ".", "rotated", "(", ")", "_", "[", ":", ",", "-", "1", "]", "=", "0", "_", "=", "N", ".", "dot", "(", "_", ",", "self", ".", "axes", ")", "return", "self", ".", "arr", "-", "_"...
Returns residuals of fit against all three data axes (singular values 1, 2, and 3). This takes the form of data along singular axis 3 (axes 1 and 2 define the plane)
[ "Returns", "residuals", "of", "fit", "against", "all", "three", "data", "axes", "(", "singular", "values", "1", "2", "and", "3", ")", ".", "This", "takes", "the", "form", "of", "data", "along", "singular", "axis", "3", "(", "axes", "1", "and", "2", "...
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L264-L274
davenquinn/Attitude
attitude/orientation/pca.py
PCAOrientation.angular_error
def angular_error(self, axis_length): """ The angular error for an in-plane axis of given length (either a PCA major axis or an intermediate direction). """ hyp_axes = self.method(self) return N.arctan2(hyp_axes[-1],axis_length)
python
def angular_error(self, axis_length): """ The angular error for an in-plane axis of given length (either a PCA major axis or an intermediate direction). """ hyp_axes = self.method(self) return N.arctan2(hyp_axes[-1],axis_length)
[ "def", "angular_error", "(", "self", ",", "axis_length", ")", ":", "hyp_axes", "=", "self", ".", "method", "(", "self", ")", "return", "N", ".", "arctan2", "(", "hyp_axes", "[", "-", "1", "]", ",", "axis_length", ")" ]
The angular error for an in-plane axis of given length (either a PCA major axis or an intermediate direction).
[ "The", "angular", "error", "for", "an", "in", "-", "plane", "axis", "of", "given", "length", "(", "either", "a", "PCA", "major", "axis", "or", "an", "intermediate", "direction", ")", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L288-L295
davenquinn/Attitude
attitude/orientation/pca.py
PCAOrientation.angular_errors
def angular_errors(self, degrees=True): """ Minimum and maximum angular errors corresponding to 1st and 2nd axes of PCA distribution. """ hyp_axes = self.method(self) v = angular_errors(hyp_axes) if degrees: v = N.degrees(v) return tupl...
python
def angular_errors(self, degrees=True): """ Minimum and maximum angular errors corresponding to 1st and 2nd axes of PCA distribution. """ hyp_axes = self.method(self) v = angular_errors(hyp_axes) if degrees: v = N.degrees(v) return tupl...
[ "def", "angular_errors", "(", "self", ",", "degrees", "=", "True", ")", ":", "hyp_axes", "=", "self", ".", "method", "(", "self", ")", "v", "=", "angular_errors", "(", "hyp_axes", ")", "if", "degrees", ":", "v", "=", "N", ".", "degrees", "(", "v", ...
Minimum and maximum angular errors corresponding to 1st and 2nd axes of PCA distribution.
[ "Minimum", "and", "maximum", "angular", "errors", "corresponding", "to", "1st", "and", "2nd", "axes", "of", "PCA", "distribution", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L297-L307
davenquinn/Attitude
attitude/orientation/pca.py
PCAOrientation._covariance_matrix
def _covariance_matrix(self, type='noise'): """ Constructs the covariance matrix from PCA residuals """ if type == 'sampling': return self.sigma**2/(self.n-1) elif type == 'noise': return 4*self.sigma*N.var(self.rotated(), axis=0)
python
def _covariance_matrix(self, type='noise'): """ Constructs the covariance matrix from PCA residuals """ if type == 'sampling': return self.sigma**2/(self.n-1) elif type == 'noise': return 4*self.sigma*N.var(self.rotated(), axis=0)
[ "def", "_covariance_matrix", "(", "self", ",", "type", "=", "'noise'", ")", ":", "if", "type", "==", "'sampling'", ":", "return", "self", ".", "sigma", "**", "2", "/", "(", "self", ".", "n", "-", "1", ")", "elif", "type", "==", "'noise'", ":", "ret...
Constructs the covariance matrix from PCA residuals
[ "Constructs", "the", "covariance", "matrix", "from", "PCA", "residuals" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L309-L317
davenquinn/Attitude
attitude/orientation/pca.py
PCAOrientation.explained_variance
def explained_variance(self): """ Proportion of variance that is explained by the first two principal components (which together represent the planar fit). Analogous to R^2 of linear least squares. """ v = N.diagonal(self.covariance_matrix) return v[0:2].s...
python
def explained_variance(self): """ Proportion of variance that is explained by the first two principal components (which together represent the planar fit). Analogous to R^2 of linear least squares. """ v = N.diagonal(self.covariance_matrix) return v[0:2].s...
[ "def", "explained_variance", "(", "self", ")", ":", "v", "=", "N", ".", "diagonal", "(", "self", ".", "covariance_matrix", ")", "return", "v", "[", "0", ":", "2", "]", ".", "sum", "(", ")", "/", "v", ".", "sum", "(", ")" ]
Proportion of variance that is explained by the first two principal components (which together represent the planar fit). Analogous to R^2 of linear least squares.
[ "Proportion", "of", "variance", "that", "is", "explained", "by", "the", "first", "two", "principal", "components", "(", "which", "together", "represent", "the", "planar", "fit", ")", ".", "Analogous", "to", "R^2", "of", "linear", "least", "squares", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L329-L337
davenquinn/Attitude
attitude/orientation/pca.py
PCAOrientation.strike_dip
def strike_dip(self, degrees=True): """ Computes strike and dip from a normal vector. Results are usually the same as LLSQ in strike (to a few decimal places) and close in dip. Sometimes, dips are greater by as much as 45 degrees, reflecting inclusion of errors in x-y pla...
python
def strike_dip(self, degrees=True): """ Computes strike and dip from a normal vector. Results are usually the same as LLSQ in strike (to a few decimal places) and close in dip. Sometimes, dips are greater by as much as 45 degrees, reflecting inclusion of errors in x-y pla...
[ "def", "strike_dip", "(", "self", ",", "degrees", "=", "True", ")", ":", "n", "=", "self", ".", "axes", "[", "2", "]", "r", "=", "N", ".", "linalg", ".", "norm", "(", "n", ")", "strike", "=", "N", ".", "degrees", "(", "N", ".", "arctan2", "("...
Computes strike and dip from a normal vector. Results are usually the same as LLSQ in strike (to a few decimal places) and close in dip. Sometimes, dips are greater by as much as 45 degrees, reflecting inclusion of errors in x-y plane.
[ "Computes", "strike", "and", "dip", "from", "a", "normal", "vector", ".", "Results", "are", "usually", "the", "same", "as", "LLSQ", "in", "strike", "(", "to", "a", "few", "decimal", "places", ")", "and", "close", "in", "dip", ".", "Sometimes", "dips", ...
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L361-L385
davenquinn/Attitude
attitude/orientation/pca.py
PCAOrientation.as_hyperbola
def as_hyperbola(self, rotated=False): """ Hyperbolic error area """ idx = N.diag_indices(3) _ = 1/self.covariance_matrix[idx] d = list(_) d[-1] *= -1 arr = N.identity(4)*-1 arr[idx] = d hyp = conic(arr) if rotated: R =...
python
def as_hyperbola(self, rotated=False): """ Hyperbolic error area """ idx = N.diag_indices(3) _ = 1/self.covariance_matrix[idx] d = list(_) d[-1] *= -1 arr = N.identity(4)*-1 arr[idx] = d hyp = conic(arr) if rotated: R =...
[ "def", "as_hyperbola", "(", "self", ",", "rotated", "=", "False", ")", ":", "idx", "=", "N", ".", "diag_indices", "(", "3", ")", "_", "=", "1", "/", "self", ".", "covariance_matrix", "[", "idx", "]", "d", "=", "list", "(", "_", ")", "d", "[", "...
Hyperbolic error area
[ "Hyperbolic", "error", "area" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L422-L437
meyersj/geotweet
geotweet/mapreduce/utils/words.py
WordExtractor.run
def run(self, line): """ Extract words from tweet 1. Remove non-ascii characters 2. Split line into individual words 3. Clean up puncuation characters """ words = [] for word in self.clean_unicode(line.lower()).split(): if word.starts...
python
def run(self, line): """ Extract words from tweet 1. Remove non-ascii characters 2. Split line into individual words 3. Clean up puncuation characters """ words = [] for word in self.clean_unicode(line.lower()).split(): if word.starts...
[ "def", "run", "(", "self", ",", "line", ")", ":", "words", "=", "[", "]", "for", "word", "in", "self", ".", "clean_unicode", "(", "line", ".", "lower", "(", ")", ")", ".", "split", "(", ")", ":", "if", "word", ".", "startswith", "(", "'http'", ...
Extract words from tweet 1. Remove non-ascii characters 2. Split line into individual words 3. Clean up puncuation characters
[ "Extract", "words", "from", "tweet" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/words.py#L47-L63
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_query.py
get_rows_fieldnames_from_query
def get_rows_fieldnames_from_query( session: Union[Session, Engine, Connection], query: Query) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]: """ Returns results and column names from a query. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Con...
python
def get_rows_fieldnames_from_query( session: Union[Session, Engine, Connection], query: Query) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]: """ Returns results and column names from a query. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Con...
[ "def", "get_rows_fieldnames_from_query", "(", "session", ":", "Union", "[", "Session", ",", "Engine", ",", "Connection", "]", ",", "query", ":", "Query", ")", "->", "Tuple", "[", "Sequence", "[", "Sequence", "[", "Any", "]", "]", ",", "Sequence", "[", "s...
Returns results and column names from a query. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object query: SQLAlchemy :class:`Query` Returns: ``(rows, fieldnames)`` where ``rows`` is the usual set of results and ``fieldnames`` a...
[ "Returns", "results", "and", "column", "names", "from", "a", "query", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L50-L74
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_query.py
bool_from_exists_clause
def bool_from_exists_clause(session: Session, exists_clause: Exists) -> bool: """ Database dialects are not consistent in how ``EXISTS`` clauses can be converted to a boolean answer. This function manages the inconsistencies. See: - https://bitbucket.org/zzzeek/sqla...
python
def bool_from_exists_clause(session: Session, exists_clause: Exists) -> bool: """ Database dialects are not consistent in how ``EXISTS`` clauses can be converted to a boolean answer. This function manages the inconsistencies. See: - https://bitbucket.org/zzzeek/sqla...
[ "def", "bool_from_exists_clause", "(", "session", ":", "Session", ",", "exists_clause", ":", "Exists", ")", "->", "bool", ":", "# noqa", "if", "session", ".", "get_bind", "(", ")", ".", "dialect", ".", "name", "==", "SqlaDialectName", ".", "MSSQL", ":", "#...
Database dialects are not consistent in how ``EXISTS`` clauses can be converted to a boolean answer. This function manages the inconsistencies. See: - https://bitbucket.org/zzzeek/sqlalchemy/issues/3212/misleading-documentation-for-queryexists - http://docs.sqlalchemy.org/en/latest/orm/query.html#...
[ "Database", "dialects", "are", "not", "consistent", "in", "how", "EXISTS", "clauses", "can", "be", "converted", "to", "a", "boolean", "answer", ".", "This", "function", "manages", "the", "inconsistencies", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L81-L117
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_query.py
exists_orm
def exists_orm(session: Session, ormclass: DeclarativeMeta, *criteria: Any) -> bool: """ Detects whether a database record exists for the specified ``ormclass`` and ``criteria``. Example usage: .. code-block:: python bool_exists = exists_orm(session, MyClass,...
python
def exists_orm(session: Session, ormclass: DeclarativeMeta, *criteria: Any) -> bool: """ Detects whether a database record exists for the specified ``ormclass`` and ``criteria``. Example usage: .. code-block:: python bool_exists = exists_orm(session, MyClass,...
[ "def", "exists_orm", "(", "session", ":", "Session", ",", "ormclass", ":", "DeclarativeMeta", ",", "*", "criteria", ":", "Any", ")", "->", "bool", ":", "# http://docs.sqlalchemy.org/en/latest/orm/query.html", "q", "=", "session", ".", "query", "(", "ormclass", "...
Detects whether a database record exists for the specified ``ormclass`` and ``criteria``. Example usage: .. code-block:: python bool_exists = exists_orm(session, MyClass, MyClass.myfield == value)
[ "Detects", "whether", "a", "database", "record", "exists", "for", "the", "specified", "ormclass", "and", "criteria", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L120-L139
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_query.py
get_or_create
def get_or_create(session: Session, model: DeclarativeMeta, defaults: Dict[str, Any] = None, **kwargs: Any) -> Tuple[Any, bool]: """ Fetches an ORM object from the database, or creates one if none existed. Args: session: an SQLAlchemy :class:`Se...
python
def get_or_create(session: Session, model: DeclarativeMeta, defaults: Dict[str, Any] = None, **kwargs: Any) -> Tuple[Any, bool]: """ Fetches an ORM object from the database, or creates one if none existed. Args: session: an SQLAlchemy :class:`Se...
[ "def", "get_or_create", "(", "session", ":", "Session", ",", "model", ":", "DeclarativeMeta", ",", "defaults", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Tuple", "[", "Any", ",", "bool", ...
Fetches an ORM object from the database, or creates one if none existed. Args: session: an SQLAlchemy :class:`Session` model: an SQLAlchemy ORM class defaults: default initialization arguments (in addition to relevant filter criteria) if we have to create a new instance ...
[ "Fetches", "an", "ORM", "object", "from", "the", "database", "or", "creates", "one", "if", "none", "existed", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L146-L175
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_query.py
CountStarSpecializedQuery.count_star
def count_star(self) -> int: """ Implements the ``COUNT(*)`` specialization. """ count_query = (self.statement.with_only_columns([func.count()]) .order_by(None)) return self.session.execute(count_query).scalar()
python
def count_star(self) -> int: """ Implements the ``COUNT(*)`` specialization. """ count_query = (self.statement.with_only_columns([func.count()]) .order_by(None)) return self.session.execute(count_query).scalar()
[ "def", "count_star", "(", "self", ")", "->", "int", ":", "count_query", "=", "(", "self", ".", "statement", ".", "with_only_columns", "(", "[", "func", ".", "count", "(", ")", "]", ")", ".", "order_by", "(", "None", ")", ")", "return", "self", ".", ...
Implements the ``COUNT(*)`` specialization.
[ "Implements", "the", "COUNT", "(", "*", ")", "specialization", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L202-L208
meyersj/geotweet
geotweet/mapreduce/utils/reader.py
FileReader.read
def read(self, src): """ Download GeoJSON file of US counties from url (S3 bucket) """ geojson = None if not self.is_valid_src(src): error = "File < {0} > does not exists or does start with 'http'." raise ValueError(error.format(src)) if not self.is_url(src): ...
python
def read(self, src): """ Download GeoJSON file of US counties from url (S3 bucket) """ geojson = None if not self.is_valid_src(src): error = "File < {0} > does not exists or does start with 'http'." raise ValueError(error.format(src)) if not self.is_url(src): ...
[ "def", "read", "(", "self", ",", "src", ")", ":", "geojson", "=", "None", "if", "not", "self", ".", "is_valid_src", "(", "src", ")", ":", "error", "=", "\"File < {0} > does not exists or does start with 'http'.\"", "raise", "ValueError", "(", "error", ".", "fo...
Download GeoJSON file of US counties from url (S3 bucket)
[ "Download", "GeoJSON", "file", "of", "US", "counties", "from", "url", "(", "S3", "bucket", ")" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/reader.py#L32-L51
RudolfCardinal/pythonlib
cardinal_pythonlib/randomness.py
create_base64encoded_randomness
def create_base64encoded_randomness(num_bytes: int) -> str: """ Create and return ``num_bytes`` of random data. The result is encoded in a string with URL-safe ``base64`` encoding. Used (for example) to generate session tokens. Which generator to use? See https://cryptography.io/en/latest/ran...
python
def create_base64encoded_randomness(num_bytes: int) -> str: """ Create and return ``num_bytes`` of random data. The result is encoded in a string with URL-safe ``base64`` encoding. Used (for example) to generate session tokens. Which generator to use? See https://cryptography.io/en/latest/ran...
[ "def", "create_base64encoded_randomness", "(", "num_bytes", ":", "int", ")", "->", "str", ":", "randbytes", "=", "os", ".", "urandom", "(", "num_bytes", ")", "# YES", "return", "base64", ".", "urlsafe_b64encode", "(", "randbytes", ")", ".", "decode", "(", "'...
Create and return ``num_bytes`` of random data. The result is encoded in a string with URL-safe ``base64`` encoding. Used (for example) to generate session tokens. Which generator to use? See https://cryptography.io/en/latest/random-numbers/. Do NOT use these methods: .. code-block:: python...
[ "Create", "and", "return", "num_bytes", "of", "random", "data", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/randomness.py#L33-L58
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/table_identity.py
TableIdentity.table
def table(self) -> Table: """ Returns a SQLAlchemy :class:`Table` object. This is either the :class:`Table` object that was used for initialization, or one that was constructed from the ``tablename`` plus the ``metadata``. """ if self._table is not None: retur...
python
def table(self) -> Table: """ Returns a SQLAlchemy :class:`Table` object. This is either the :class:`Table` object that was used for initialization, or one that was constructed from the ``tablename`` plus the ``metadata``. """ if self._table is not None: retur...
[ "def", "table", "(", "self", ")", "->", "Table", ":", "if", "self", ".", "_table", "is", "not", "None", ":", "return", "self", ".", "_table", "assert", "self", ".", "_metadata", ",", "(", "\"Must specify metadata (in constructor or via set_metadata()/\"", "\"set...
Returns a SQLAlchemy :class:`Table` object. This is either the :class:`Table` object that was used for initialization, or one that was constructed from the ``tablename`` plus the ``metadata``.
[ "Returns", "a", "SQLAlchemy", ":", "class", ":", "Table", "object", ".", "This", "is", "either", "the", ":", "class", ":", "Table", "object", "that", "was", "used", "for", "initialization", "or", "one", "that", "was", "constructed", "from", "the", "tablena...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/table_identity.py#L76-L93
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/table_identity.py
TableIdentity.tablename
def tablename(self) -> str: """ Returns the string name of the table. """ if self._tablename: return self._tablename return self.table.name
python
def tablename(self) -> str: """ Returns the string name of the table. """ if self._tablename: return self._tablename return self.table.name
[ "def", "tablename", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_tablename", ":", "return", "self", ".", "_tablename", "return", "self", ".", "table", ".", "name" ]
Returns the string name of the table.
[ "Returns", "the", "string", "name", "of", "the", "table", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/table_identity.py#L96-L102
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/pause_process_by_disk_space.py
is_running
def is_running(process_id: int) -> bool: """ Uses the Unix ``ps`` program to see if a process is running. """ pstr = str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encodi...
python
def is_running(process_id: int) -> bool: """ Uses the Unix ``ps`` program to see if a process is running. """ pstr = str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encodi...
[ "def", "is_running", "(", "process_id", ":", "int", ")", "->", "bool", ":", "pstr", "=", "str", "(", "process_id", ")", "encoding", "=", "sys", ".", "getdefaultencoding", "(", ")", "s", "=", "subprocess", ".", "Popen", "(", "[", "\"ps\"", ",", "\"-p\""...
Uses the Unix ``ps`` program to see if a process is running.
[ "Uses", "the", "Unix", "ps", "program", "to", "see", "if", "a", "process", "is", "running", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/pause_process_by_disk_space.py#L45-L56
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/pause_process_by_disk_space.py
main
def main() -> None: """ Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help. """ parser = ArgumentParser( description="Pauses and resumes a process by disk space; LINUX ONLY." ) parser.add_argument( "process_id", type=int, ...
python
def main() -> None: """ Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help. """ parser = ArgumentParser( description="Pauses and resumes a process by disk space; LINUX ONLY." ) parser.add_argument( "process_id", type=int, ...
[ "def", "main", "(", ")", "->", "None", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"Pauses and resumes a process by disk space; LINUX ONLY.\"", ")", "parser", ".", "add_argument", "(", "\"process_id\"", ",", "type", "=", "int", ",", "help", "=...
Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help.
[ "Command", "-", "line", "handler", "for", "the", "pause_process_by_disk_space", "tool", ".", "Use", "the", "--", "help", "option", "for", "help", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/pause_process_by_disk_space.py#L59-L142
davenquinn/Attitude
attitude/display/plot/cov_types/regressions.py
bootstrap_noise
def bootstrap_noise(data, func, n=10000, std=1, symmetric=True): """ Bootstrap by adding noise """ boot_dist = [] arr = N.zeros(data.shape) for i in range(n): if symmetric: # Noise on all three axes arr = N.random.randn(*data.shape)*std else: #...
python
def bootstrap_noise(data, func, n=10000, std=1, symmetric=True): """ Bootstrap by adding noise """ boot_dist = [] arr = N.zeros(data.shape) for i in range(n): if symmetric: # Noise on all three axes arr = N.random.randn(*data.shape)*std else: #...
[ "def", "bootstrap_noise", "(", "data", ",", "func", ",", "n", "=", "10000", ",", "std", "=", "1", ",", "symmetric", "=", "True", ")", ":", "boot_dist", "=", "[", "]", "arr", "=", "N", ".", "zeros", "(", "data", ".", "shape", ")", "for", "i", "i...
Bootstrap by adding noise
[ "Bootstrap", "by", "adding", "noise" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/cov_types/regressions.py#L43-L57
RudolfCardinal/pythonlib
cardinal_pythonlib/django/reprfunc.py
modelrepr
def modelrepr(instance) -> str: """ Default ``repr`` version of a Django model object, for debugging. """ elements = [] # noinspection PyProtectedMember for f in instance._meta.get_fields(): # https://docs.djangoproject.com/en/2.0/ref/models/meta/ if f.auto_created: c...
python
def modelrepr(instance) -> str: """ Default ``repr`` version of a Django model object, for debugging. """ elements = [] # noinspection PyProtectedMember for f in instance._meta.get_fields(): # https://docs.djangoproject.com/en/2.0/ref/models/meta/ if f.auto_created: c...
[ "def", "modelrepr", "(", "instance", ")", "->", "str", ":", "elements", "=", "[", "]", "# noinspection PyProtectedMember", "for", "f", "in", "instance", ".", "_meta", ".", "get_fields", "(", ")", ":", "# https://docs.djangoproject.com/en/2.0/ref/models/meta/", "if",...
Default ``repr`` version of a Django model object, for debugging.
[ "Default", "repr", "version", "of", "a", "Django", "model", "object", "for", "debugging", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/reprfunc.py#L32-L51
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
assert_processor_available
def assert_processor_available(processor: str) -> None: """ Assert that a specific PDF processor is available. Args: processor: a PDF processor type from :class:`Processors` Raises: AssertionError: if bad ``processor`` RuntimeError: if requested processor is unavailable """...
python
def assert_processor_available(processor: str) -> None: """ Assert that a specific PDF processor is available. Args: processor: a PDF processor type from :class:`Processors` Raises: AssertionError: if bad ``processor`` RuntimeError: if requested processor is unavailable """...
[ "def", "assert_processor_available", "(", "processor", ":", "str", ")", "->", "None", ":", "if", "processor", "not", "in", "[", "Processors", ".", "XHTML2PDF", ",", "Processors", ".", "WEASYPRINT", ",", "Processors", ".", "PDFKIT", "]", ":", "raise", "Assert...
Assert that a specific PDF processor is available. Args: processor: a PDF processor type from :class:`Processors` Raises: AssertionError: if bad ``processor`` RuntimeError: if requested processor is unavailable
[ "Assert", "that", "a", "specific", "PDF", "processor", "is", "available", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L193-L214
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
make_pdf_from_html
def make_pdf_from_html( # Mandatory parameters: on_disk: bool, html: str, # Disk options: output_path: str = None, # Shared options: header_html: str = None, footer_html: str = None, wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME, wkhtml...
python
def make_pdf_from_html( # Mandatory parameters: on_disk: bool, html: str, # Disk options: output_path: str = None, # Shared options: header_html: str = None, footer_html: str = None, wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME, wkhtml...
[ "def", "make_pdf_from_html", "(", "# Mandatory parameters:", "on_disk", ":", "bool", ",", "html", ":", "str", ",", "# Disk options:", "output_path", ":", "str", "=", "None", ",", "# Shared options:", "header_html", ":", "str", "=", "None", ",", "footer_html", ":...
Takes HTML and either returns a PDF in memory or makes one on disk. For preference, uses ``wkhtmltopdf`` (with ``pdfkit``): - faster than ``xhtml2pdf`` - tables not buggy like ``Weasyprint`` - however, doesn't support CSS Paged Media, so we have the ``header_html`` and ``footer_html`` options to...
[ "Takes", "HTML", "and", "either", "returns", "a", "PDF", "in", "memory", "or", "makes", "one", "on", "disk", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L232-L402
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
get_pdf_from_html
def get_pdf_from_html(html: str, header_html: str = None, footer_html: str = None, wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME, wkhtmltopdf_options: Dict[str, Any] = None, file_encoding: str = "utf-8", ...
python
def get_pdf_from_html(html: str, header_html: str = None, footer_html: str = None, wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME, wkhtmltopdf_options: Dict[str, Any] = None, file_encoding: str = "utf-8", ...
[ "def", "get_pdf_from_html", "(", "html", ":", "str", ",", "header_html", ":", "str", "=", "None", ",", "footer_html", ":", "str", "=", "None", ",", "wkhtmltopdf_filename", ":", "str", "=", "_WKHTMLTOPDF_FILENAME", ",", "wkhtmltopdf_options", ":", "Dict", "[", ...
Takes HTML and returns a PDF. See the arguments to :func:`make_pdf_from_html` (except ``on_disk``). Returns: the PDF binary as a ``bytes`` object
[ "Takes", "HTML", "and", "returns", "a", "PDF", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L405-L438
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
pdf_from_writer
def pdf_from_writer(writer: Union[PdfFileWriter, PdfFileMerger]) -> bytes: """ Extracts a PDF (as binary data) from a PyPDF2 writer or merger object. """ memfile = io.BytesIO() writer.write(memfile) memfile.seek(0) return memfile.read()
python
def pdf_from_writer(writer: Union[PdfFileWriter, PdfFileMerger]) -> bytes: """ Extracts a PDF (as binary data) from a PyPDF2 writer or merger object. """ memfile = io.BytesIO() writer.write(memfile) memfile.seek(0) return memfile.read()
[ "def", "pdf_from_writer", "(", "writer", ":", "Union", "[", "PdfFileWriter", ",", "PdfFileMerger", "]", ")", "->", "bytes", ":", "memfile", "=", "io", ".", "BytesIO", "(", ")", "writer", ".", "write", "(", "memfile", ")", "memfile", ".", "seek", "(", "...
Extracts a PDF (as binary data) from a PyPDF2 writer or merger object.
[ "Extracts", "a", "PDF", "(", "as", "binary", "data", ")", "from", "a", "PyPDF2", "writer", "or", "merger", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L505-L512
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
append_memory_pdf_to_writer
def append_memory_pdf_to_writer(input_pdf: bytes, writer: PdfFileWriter, start_recto: bool = True) -> None: """ Appends a PDF (as bytes in memory) to a PyPDF2 writer. Args: input_pdf: the PDF, as ``bytes`` writer: the writer ...
python
def append_memory_pdf_to_writer(input_pdf: bytes, writer: PdfFileWriter, start_recto: bool = True) -> None: """ Appends a PDF (as bytes in memory) to a PyPDF2 writer. Args: input_pdf: the PDF, as ``bytes`` writer: the writer ...
[ "def", "append_memory_pdf_to_writer", "(", "input_pdf", ":", "bytes", ",", "writer", ":", "PdfFileWriter", ",", "start_recto", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "not", "input_pdf", ":", "return", "if", "start_recto", "and", "writer", "....
Appends a PDF (as bytes in memory) to a PyPDF2 writer. Args: input_pdf: the PDF, as ``bytes`` writer: the writer start_recto: start a new right-hand page?
[ "Appends", "a", "PDF", "(", "as", "bytes", "in", "memory", ")", "to", "a", "PyPDF2", "writer", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L541-L560
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
append_pdf
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter): """ Appends a PDF to a pyPDF writer. Legacy interface. """ append_memory_pdf_to_writer(input_pdf=input_pdf, writer=output_writer)
python
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter): """ Appends a PDF to a pyPDF writer. Legacy interface. """ append_memory_pdf_to_writer(input_pdf=input_pdf, writer=output_writer)
[ "def", "append_pdf", "(", "input_pdf", ":", "bytes", ",", "output_writer", ":", "PdfFileWriter", ")", ":", "append_memory_pdf_to_writer", "(", "input_pdf", "=", "input_pdf", ",", "writer", "=", "output_writer", ")" ]
Appends a PDF to a pyPDF writer. Legacy interface.
[ "Appends", "a", "PDF", "to", "a", "pyPDF", "writer", ".", "Legacy", "interface", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L563-L568
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
get_concatenated_pdf_from_disk
def get_concatenated_pdf_from_disk(filenames: Iterable[str], start_recto: bool = True) -> bytes: """ Concatenates PDFs from disk and returns them as an in-memory binary PDF. Args: filenames: iterable of filenames of PDFs to concatenate start_recto: start a...
python
def get_concatenated_pdf_from_disk(filenames: Iterable[str], start_recto: bool = True) -> bytes: """ Concatenates PDFs from disk and returns them as an in-memory binary PDF. Args: filenames: iterable of filenames of PDFs to concatenate start_recto: start a...
[ "def", "get_concatenated_pdf_from_disk", "(", "filenames", ":", "Iterable", "[", "str", "]", ",", "start_recto", ":", "bool", "=", "True", ")", "->", "bytes", ":", "# http://stackoverflow.com/questions/17104926/pypdf-merging-multiple-pdf-files-into-one-pdf # noqa", "# https:...
Concatenates PDFs from disk and returns them as an in-memory binary PDF. Args: filenames: iterable of filenames of PDFs to concatenate start_recto: start a new right-hand page for each new PDF? Returns: concatenated PDF, as ``bytes``
[ "Concatenates", "PDFs", "from", "disk", "and", "returns", "them", "as", "an", "in", "-", "memory", "binary", "PDF", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L597-L626
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
get_concatenated_pdf_in_memory
def get_concatenated_pdf_in_memory( pdf_plans: Iterable[PdfPlan], start_recto: bool = True) -> bytes: """ Concatenates PDFs and returns them as an in-memory binary PDF. Args: pdf_plans: iterable of :class:`PdfPlan` objects start_recto: start a new right-hand page for each ne...
python
def get_concatenated_pdf_in_memory( pdf_plans: Iterable[PdfPlan], start_recto: bool = True) -> bytes: """ Concatenates PDFs and returns them as an in-memory binary PDF. Args: pdf_plans: iterable of :class:`PdfPlan` objects start_recto: start a new right-hand page for each ne...
[ "def", "get_concatenated_pdf_in_memory", "(", "pdf_plans", ":", "Iterable", "[", "PdfPlan", "]", ",", "start_recto", ":", "bool", "=", "True", ")", "->", "bytes", ":", "writer", "=", "PdfFileWriter", "(", ")", "for", "pdfplan", "in", "pdf_plans", ":", "pdfpl...
Concatenates PDFs and returns them as an in-memory binary PDF. Args: pdf_plans: iterable of :class:`PdfPlan` objects start_recto: start a new right-hand page for each new PDF? Returns: concatenated PDF, as ``bytes``
[ "Concatenates", "PDFs", "and", "returns", "them", "as", "an", "in", "-", "memory", "binary", "PDF", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L629-L646
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
PdfPlan.add_to_writer
def add_to_writer(self, writer: PdfFileWriter, start_recto: bool = True) -> None: """ Add the PDF described by this class to a PDF writer. Args: writer: a :class:`PyPDF2.PdfFileWriter` start_recto: start a new right-hand page? ...
python
def add_to_writer(self, writer: PdfFileWriter, start_recto: bool = True) -> None: """ Add the PDF described by this class to a PDF writer. Args: writer: a :class:`PyPDF2.PdfFileWriter` start_recto: start a new right-hand page? ...
[ "def", "add_to_writer", "(", "self", ",", "writer", ":", "PdfFileWriter", ",", "start_recto", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "self", ".", "is_html", ":", "pdf", "=", "get_pdf_from_html", "(", "html", "=", "self", ".", "html", "...
Add the PDF described by this class to a PDF writer. Args: writer: a :class:`PyPDF2.PdfFileWriter` start_recto: start a new right-hand page?
[ "Add", "the", "PDF", "described", "by", "this", "class", "to", "a", "PDF", "writer", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L161-L186
RudolfCardinal/pythonlib
cardinal_pythonlib/formatting.py
trunc_if_integer
def trunc_if_integer(n: Any) -> Any: """ Truncates floats that are integers to their integer representation. That is, converts ``1.0`` to ``1``, etc. Otherwise, returns the starting value. Will raise an exception if the input cannot be converted to ``int``. """ if n == int(n): return...
python
def trunc_if_integer(n: Any) -> Any: """ Truncates floats that are integers to their integer representation. That is, converts ``1.0`` to ``1``, etc. Otherwise, returns the starting value. Will raise an exception if the input cannot be converted to ``int``. """ if n == int(n): return...
[ "def", "trunc_if_integer", "(", "n", ":", "Any", ")", "->", "Any", ":", "if", "n", "==", "int", "(", "n", ")", ":", "return", "int", "(", "n", ")", "return", "n" ]
Truncates floats that are integers to their integer representation. That is, converts ``1.0`` to ``1``, etc. Otherwise, returns the starting value. Will raise an exception if the input cannot be converted to ``int``.
[ "Truncates", "floats", "that", "are", "integers", "to", "their", "integer", "representation", ".", "That", "is", "converts", "1", ".", "0", "to", "1", "etc", ".", "Otherwise", "returns", "the", "starting", "value", ".", "Will", "raise", "an", "exception", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/formatting.py#L36-L45
RudolfCardinal/pythonlib
cardinal_pythonlib/reprfunc.py
repr_result
def repr_result(obj: Any, elements: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: """ Internal function to make a :func:`repr`-style representation of an object. Args: obj: object to display elements: list of object ``attribute=value`` strings ...
python
def repr_result(obj: Any, elements: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: """ Internal function to make a :func:`repr`-style representation of an object. Args: obj: object to display elements: list of object ``attribute=value`` strings ...
[ "def", "repr_result", "(", "obj", ":", "Any", ",", "elements", ":", "List", "[", "str", "]", ",", "with_addr", ":", "bool", "=", "False", ",", "joiner", ":", "str", "=", "COMMA_SPACE", ")", "->", "str", ":", "if", "with_addr", ":", "return", "\"<{qua...
Internal function to make a :func:`repr`-style representation of an object. Args: obj: object to display elements: list of object ``attribute=value`` strings with_addr: include the memory address of ``obj`` joiner: string with which to join the elements Returns: string:...
[ "Internal", "function", "to", "make", "a", ":", "func", ":", "repr", "-", "style", "representation", "of", "an", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/reprfunc.py#L42-L65
RudolfCardinal/pythonlib
cardinal_pythonlib/reprfunc.py
auto_repr
def auto_repr(obj: Any, with_addr: bool = False, sort_attrs: bool = True, joiner: str = COMMA_SPACE) -> str: """ Convenience function for :func:`__repr__`. Works its way through the object's ``__dict__`` and reports accordingly. Args: obj: object to display with_addr: incl...
python
def auto_repr(obj: Any, with_addr: bool = False, sort_attrs: bool = True, joiner: str = COMMA_SPACE) -> str: """ Convenience function for :func:`__repr__`. Works its way through the object's ``__dict__`` and reports accordingly. Args: obj: object to display with_addr: incl...
[ "def", "auto_repr", "(", "obj", ":", "Any", ",", "with_addr", ":", "bool", "=", "False", ",", "sort_attrs", ":", "bool", "=", "True", ",", "joiner", ":", "str", "=", "COMMA_SPACE", ")", "->", "str", ":", "if", "sort_attrs", ":", "keys", "=", "sorted"...
Convenience function for :func:`__repr__`. Works its way through the object's ``__dict__`` and reports accordingly. Args: obj: object to display with_addr: include the memory address of ``obj`` sort_attrs: sort the attributes into alphabetical order? joiner: string with which to...
[ "Convenience", "function", "for", ":", "func", ":", "__repr__", ".", "Works", "its", "way", "through", "the", "object", "s", "__dict__", "and", "reports", "accordingly", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/reprfunc.py#L68-L88
RudolfCardinal/pythonlib
cardinal_pythonlib/reprfunc.py
simple_repr
def simple_repr(obj: Any, attrnames: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: """ Convenience function for :func:`__repr__`. Works its way through a list of attribute names, and creates a ``repr()`` representation assuming that parameters to the constructor ...
python
def simple_repr(obj: Any, attrnames: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: """ Convenience function for :func:`__repr__`. Works its way through a list of attribute names, and creates a ``repr()`` representation assuming that parameters to the constructor ...
[ "def", "simple_repr", "(", "obj", ":", "Any", ",", "attrnames", ":", "List", "[", "str", "]", ",", "with_addr", ":", "bool", "=", "False", ",", "joiner", ":", "str", "=", "COMMA_SPACE", ")", "->", "str", ":", "elements", "=", "[", "\"{}={}\"", ".", ...
Convenience function for :func:`__repr__`. Works its way through a list of attribute names, and creates a ``repr()`` representation assuming that parameters to the constructor have the same names. Args: obj: object to display attrnames: names of attributes to include with_addr: ...
[ "Convenience", "function", "for", ":", "func", ":", "__repr__", ".", "Works", "its", "way", "through", "a", "list", "of", "attribute", "names", "and", "creates", "a", "repr", "()", "representation", "assuming", "that", "parameters", "to", "the", "constructor",...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/reprfunc.py#L91-L111
RudolfCardinal/pythonlib
cardinal_pythonlib/reprfunc.py
mapped_repr
def mapped_repr(obj: Any, attributes: List[Tuple[str, str]], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: """ Convenience function for :func:`__repr__`. Takes attribute names and corresponding initialization parameter names (parameters to :func:`__init__`). Args: ...
python
def mapped_repr(obj: Any, attributes: List[Tuple[str, str]], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: """ Convenience function for :func:`__repr__`. Takes attribute names and corresponding initialization parameter names (parameters to :func:`__init__`). Args: ...
[ "def", "mapped_repr", "(", "obj", ":", "Any", ",", "attributes", ":", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "with_addr", ":", "bool", "=", "False", ",", "joiner", ":", "str", "=", "COMMA_SPACE", ")", "->", "str", ":", "elemen...
Convenience function for :func:`__repr__`. Takes attribute names and corresponding initialization parameter names (parameters to :func:`__init__`). Args: obj: object to display attributes: list of tuples, each ``(attr_name, init_param_name)``. with_addr: include the memory address o...
[ "Convenience", "function", "for", ":", "func", ":", "__repr__", ".", "Takes", "attribute", "names", "and", "corresponding", "initialization", "parameter", "names", "(", "parameters", "to", ":", "func", ":", "__init__", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/reprfunc.py#L114-L133
RudolfCardinal/pythonlib
cardinal_pythonlib/reprfunc.py
mapped_repr_stripping_underscores
def mapped_repr_stripping_underscores( obj: Any, attrnames: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: """ Convenience function for :func:`__repr__`. Here, you pass a list of internal attributes, and it assumes that the :func:`__init__` parameter names have th...
python
def mapped_repr_stripping_underscores( obj: Any, attrnames: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: """ Convenience function for :func:`__repr__`. Here, you pass a list of internal attributes, and it assumes that the :func:`__init__` parameter names have th...
[ "def", "mapped_repr_stripping_underscores", "(", "obj", ":", "Any", ",", "attrnames", ":", "List", "[", "str", "]", ",", "with_addr", ":", "bool", "=", "False", ",", "joiner", ":", "str", "=", "COMMA_SPACE", ")", "->", "str", ":", "attributes", "=", "[",...
Convenience function for :func:`__repr__`. Here, you pass a list of internal attributes, and it assumes that the :func:`__init__` parameter names have the leading underscore dropped. Args: obj: object to display attrnames: list of attribute names with_addr: include the memory addres...
[ "Convenience", "function", "for", ":", "func", ":", "__repr__", ".", "Here", "you", "pass", "a", "list", "of", "internal", "attributes", "and", "it", "assumes", "that", "the", ":", "func", ":", "__init__", "parameter", "names", "have", "the", "leading", "u...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/reprfunc.py#L136-L161
RudolfCardinal/pythonlib
cardinal_pythonlib/reprfunc.py
ordered_repr
def ordered_repr(obj: object, attrlist: Iterable[str], joiner: str = COMMA_SPACE) -> str: """ Shortcut to make :func:`repr` functions ordered. Define your :func:`__repr__` like this: .. code-block:: python def __repr__(self): return ordered_repr(self, ["field1", "f...
python
def ordered_repr(obj: object, attrlist: Iterable[str], joiner: str = COMMA_SPACE) -> str: """ Shortcut to make :func:`repr` functions ordered. Define your :func:`__repr__` like this: .. code-block:: python def __repr__(self): return ordered_repr(self, ["field1", "f...
[ "def", "ordered_repr", "(", "obj", ":", "object", ",", "attrlist", ":", "Iterable", "[", "str", "]", ",", "joiner", ":", "str", "=", "COMMA_SPACE", ")", "->", "str", ":", "return", "\"<{classname}({kvp})>\"", ".", "format", "(", "classname", "=", "type", ...
Shortcut to make :func:`repr` functions ordered. Define your :func:`__repr__` like this: .. code-block:: python def __repr__(self): return ordered_repr(self, ["field1", "field2", "field3"]) Args: obj: object to display attrlist: iterable of attribute names join...
[ "Shortcut", "to", "make", ":", "func", ":", "repr", "functions", "ordered", ".", "Define", "your", ":", "func", ":", "__repr__", "like", "this", ":" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/reprfunc.py#L164-L187
RudolfCardinal/pythonlib
cardinal_pythonlib/reprfunc.py
auto_str
def auto_str(obj: Any, indent: int = 4, width: int = 80, depth: int = None, compact: bool = False) -> str: """ Make a pretty :func:`str()` representation using :func:`pprint.pformat` and the object's ``__dict__`` attribute. Args: obj: object to display indent: see ...
python
def auto_str(obj: Any, indent: int = 4, width: int = 80, depth: int = None, compact: bool = False) -> str: """ Make a pretty :func:`str()` representation using :func:`pprint.pformat` and the object's ``__dict__`` attribute. Args: obj: object to display indent: see ...
[ "def", "auto_str", "(", "obj", ":", "Any", ",", "indent", ":", "int", "=", "4", ",", "width", ":", "int", "=", "80", ",", "depth", ":", "int", "=", "None", ",", "compact", ":", "bool", "=", "False", ")", "->", "str", ":", "return", "pprint", "....
Make a pretty :func:`str()` representation using :func:`pprint.pformat` and the object's ``__dict__`` attribute. Args: obj: object to display indent: see https://docs.python.org/3/library/pprint.html#pprint.PrettyPrinter width: as above depth: as above compac...
[ "Make", "a", "pretty", ":", "func", ":", "str", "()", "representation", "using", ":", "func", ":", "pprint", ".", "pformat", "and", "the", "object", "s", "__dict__", "attribute", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/reprfunc.py#L190-L209
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/treatment_resistant_depression.py
timedelta_days
def timedelta_days(days: int) -> timedelta64: """ Convert a duration in days to a NumPy ``timedelta64`` object. """ int_days = int(days) if int_days != days: raise ValueError("Fractional days passed to timedelta_days: " "{!r}".format(days)) try: # Do not ...
python
def timedelta_days(days: int) -> timedelta64: """ Convert a duration in days to a NumPy ``timedelta64`` object. """ int_days = int(days) if int_days != days: raise ValueError("Fractional days passed to timedelta_days: " "{!r}".format(days)) try: # Do not ...
[ "def", "timedelta_days", "(", "days", ":", "int", ")", "->", "timedelta64", ":", "int_days", "=", "int", "(", "days", ")", "if", "int_days", "!=", "days", ":", "raise", "ValueError", "(", "\"Fractional days passed to timedelta_days: \"", "\"{!r}\"", ".", "format...
Convert a duration in days to a NumPy ``timedelta64`` object.
[ "Convert", "a", "duration", "in", "days", "to", "a", "NumPy", "timedelta64", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/treatment_resistant_depression.py#L121-L135
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/treatment_resistant_depression.py
_get_generic_two_antidep_episodes_result
def _get_generic_two_antidep_episodes_result( rowdata: Tuple[Any, ...] = None) -> DataFrame: """ Create a results row for this application. """ # Valid data types... see: # - pandas.core.dtypes.common.pandas_dtype # - https://pandas.pydata.org/pandas-docs/stable/timeseries.html # - h...
python
def _get_generic_two_antidep_episodes_result( rowdata: Tuple[Any, ...] = None) -> DataFrame: """ Create a results row for this application. """ # Valid data types... see: # - pandas.core.dtypes.common.pandas_dtype # - https://pandas.pydata.org/pandas-docs/stable/timeseries.html # - h...
[ "def", "_get_generic_two_antidep_episodes_result", "(", "rowdata", ":", "Tuple", "[", "Any", ",", "...", "]", "=", "None", ")", "->", "DataFrame", ":", "# Valid data types... see:", "# - pandas.core.dtypes.common.pandas_dtype", "# - https://pandas.pydata.org/pandas-docs/stable/...
Create a results row for this application.
[ "Create", "a", "results", "row", "for", "this", "application", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/treatment_resistant_depression.py#L138-L161
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/treatment_resistant_depression.py
two_antidepressant_episodes_single_patient
def two_antidepressant_episodes_single_patient( patient_id: str, patient_drug_date_df: DataFrame, patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME, drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME, date_colname: str = DEFAULT_SOURCE_DATE_COLNAME, course_length_days: i...
python
def two_antidepressant_episodes_single_patient( patient_id: str, patient_drug_date_df: DataFrame, patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME, drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME, date_colname: str = DEFAULT_SOURCE_DATE_COLNAME, course_length_days: i...
[ "def", "two_antidepressant_episodes_single_patient", "(", "patient_id", ":", "str", ",", "patient_drug_date_df", ":", "DataFrame", ",", "patient_colname", ":", "str", "=", "DEFAULT_SOURCE_PATIENT_COLNAME", ",", "drug_colname", ":", "str", "=", "DEFAULT_SOURCE_DRUG_COLNAME",...
Processes a single patient for ``two_antidepressant_episodes()`` (q.v.). Implements the key algorithm.
[ "Processes", "a", "single", "patient", "for", "two_antidepressant_episodes", "()", "(", "q", ".", "v", ".", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/treatment_resistant_depression.py#L171-L364
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/treatment_resistant_depression.py
two_antidepressant_episodes
def two_antidepressant_episodes( patient_drug_date_df: DataFrame, patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME, drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME, date_colname: str = DEFAULT_SOURCE_DATE_COLNAME, course_length_days: int = DEFAULT_ANTIDEPRESSANT_COURSE_LENGT...
python
def two_antidepressant_episodes( patient_drug_date_df: DataFrame, patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME, drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME, date_colname: str = DEFAULT_SOURCE_DATE_COLNAME, course_length_days: int = DEFAULT_ANTIDEPRESSANT_COURSE_LENGT...
[ "def", "two_antidepressant_episodes", "(", "patient_drug_date_df", ":", "DataFrame", ",", "patient_colname", ":", "str", "=", "DEFAULT_SOURCE_PATIENT_COLNAME", ",", "drug_colname", ":", "str", "=", "DEFAULT_SOURCE_DRUG_COLNAME", ",", "date_colname", ":", "str", "=", "DE...
Takes a *pandas* ``DataFrame``, ``patient_drug_date_df`` (or, via ``reticulate``, an R ``data.frame`` or ``data.table``). This should contain dated present-tense references to antidepressant drugs (only). Returns a set of result rows as a ``DataFrame``.
[ "Takes", "a", "*", "pandas", "*", "DataFrame", "patient_drug_date_df", "(", "or", "via", "reticulate", "an", "R", "data", ".", "frame", "or", "data", ".", "table", ")", ".", "This", "should", "contain", "dated", "present", "-", "tense", "references", "to",...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/treatment_resistant_depression.py#L367-L441
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
does_unrtf_support_quiet
def does_unrtf_support_quiet() -> bool: """ The unrtf tool supports the '--quiet' argument from a version that I'm not quite sure of, where ``0.19.3 < version <= 0.21.9``. We check against 0.21.9 here. """ required_unrtf_version = Version("0.21.9") # ... probably: http://hg.savannah.gnu.org/...
python
def does_unrtf_support_quiet() -> bool: """ The unrtf tool supports the '--quiet' argument from a version that I'm not quite sure of, where ``0.19.3 < version <= 0.21.9``. We check against 0.21.9 here. """ required_unrtf_version = Version("0.21.9") # ... probably: http://hg.savannah.gnu.org/...
[ "def", "does_unrtf_support_quiet", "(", ")", "->", "bool", ":", "required_unrtf_version", "=", "Version", "(", "\"0.21.9\"", ")", "# ... probably: http://hg.savannah.gnu.org/hgweb/unrtf/", "# ... 0.21.9 definitely supports --quiet", "# ... 0.19.3 definitely doesn't support it", "unrt...
The unrtf tool supports the '--quiet' argument from a version that I'm not quite sure of, where ``0.19.3 < version <= 0.21.9``. We check against 0.21.9 here.
[ "The", "unrtf", "tool", "supports", "the", "--", "quiet", "argument", "from", "a", "version", "that", "I", "m", "not", "quite", "sure", "of", "where", "0", ".", "19", ".", "3", "<", "version", "<", "=", "0", ".", "21", ".", "9", ".", "We", "check...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L186-L209
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
get_filelikeobject
def get_filelikeobject(filename: str = None, blob: bytes = None) -> BinaryIO: """ Open a file-like object. Guard the use of this function with ``with``. Args: filename: for specifying via a filename blob: for specifying via an in-memory ``bytes`` object Retu...
python
def get_filelikeobject(filename: str = None, blob: bytes = None) -> BinaryIO: """ Open a file-like object. Guard the use of this function with ``with``. Args: filename: for specifying via a filename blob: for specifying via an in-memory ``bytes`` object Retu...
[ "def", "get_filelikeobject", "(", "filename", ":", "str", "=", "None", ",", "blob", ":", "bytes", "=", "None", ")", "->", "BinaryIO", ":", "if", "not", "filename", "and", "not", "blob", ":", "raise", "ValueError", "(", "\"no filename and no blob\"", ")", "...
Open a file-like object. Guard the use of this function with ``with``. Args: filename: for specifying via a filename blob: for specifying via an in-memory ``bytes`` object Returns: a :class:`BinaryIO` object
[ "Open", "a", "file", "-", "like", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L272-L293
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
get_file_contents
def get_file_contents(filename: str = None, blob: bytes = None) -> bytes: """ Returns the binary contents of a file, or of a BLOB. """ if not filename and not blob: raise ValueError("no filename and no blob") if filename and blob: raise ValueError("specify either filename or blob") ...
python
def get_file_contents(filename: str = None, blob: bytes = None) -> bytes: """ Returns the binary contents of a file, or of a BLOB. """ if not filename and not blob: raise ValueError("no filename and no blob") if filename and blob: raise ValueError("specify either filename or blob") ...
[ "def", "get_file_contents", "(", "filename", ":", "str", "=", "None", ",", "blob", ":", "bytes", "=", "None", ")", "->", "bytes", ":", "if", "not", "filename", "and", "not", "blob", ":", "raise", "ValueError", "(", "\"no filename and no blob\"", ")", "if",...
Returns the binary contents of a file, or of a BLOB.
[ "Returns", "the", "binary", "contents", "of", "a", "file", "or", "of", "a", "BLOB", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L297-L308
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
get_chardet_encoding
def get_chardet_encoding(binary_contents: bytes) -> Optional[str]: """ Guess the character set encoding of the specified ``binary_contents``. """ if not binary_contents: return None if chardet is None or UniversalDetector is None: log.warning("chardet not installed; limits detection ...
python
def get_chardet_encoding(binary_contents: bytes) -> Optional[str]: """ Guess the character set encoding of the specified ``binary_contents``. """ if not binary_contents: return None if chardet is None or UniversalDetector is None: log.warning("chardet not installed; limits detection ...
[ "def", "get_chardet_encoding", "(", "binary_contents", ":", "bytes", ")", "->", "Optional", "[", "str", "]", ":", "if", "not", "binary_contents", ":", "return", "None", "if", "chardet", "is", "None", "or", "UniversalDetector", "is", "None", ":", "log", ".", ...
Guess the character set encoding of the specified ``binary_contents``.
[ "Guess", "the", "character", "set", "encoding", "of", "the", "specified", "binary_contents", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L311-L340
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
get_file_contents_text
def get_file_contents_text( filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Returns the string contents of a file, or of a BLOB. """ binary_contents = get_file_contents(filename=filename, blob=blob) # 1. Try the encoding the user ...
python
def get_file_contents_text( filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Returns the string contents of a file, or of a BLOB. """ binary_contents = get_file_contents(filename=filename, blob=blob) # 1. Try the encoding the user ...
[ "def", "get_file_contents_text", "(", "filename", ":", "str", "=", "None", ",", "blob", ":", "bytes", "=", "None", ",", "config", ":", "TextProcessingConfig", "=", "_DEFAULT_CONFIG", ")", "->", "str", ":", "binary_contents", "=", "get_file_contents", "(", "fil...
Returns the string contents of a file, or of a BLOB.
[ "Returns", "the", "string", "contents", "of", "a", "file", "or", "of", "a", "BLOB", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L343-L371
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
get_cmd_output
def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str: """ Returns text output of a command. """ log.debug("get_cmd_output(): args = {!r}", args) p = subprocess.Popen(args, stdout=subprocess.PIPE) stdout, stderr = p.communicate() return stdout.decode(encoding, errors='ignore')
python
def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str: """ Returns text output of a command. """ log.debug("get_cmd_output(): args = {!r}", args) p = subprocess.Popen(args, stdout=subprocess.PIPE) stdout, stderr = p.communicate() return stdout.decode(encoding, errors='ignore')
[ "def", "get_cmd_output", "(", "*", "args", ",", "encoding", ":", "str", "=", "SYS_ENCODING", ")", "->", "str", ":", "log", ".", "debug", "(", "\"get_cmd_output(): args = {!r}\"", ",", "args", ")", "p", "=", "subprocess", ".", "Popen", "(", "args", ",", "...
Returns text output of a command.
[ "Returns", "text", "output", "of", "a", "command", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L374-L381
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
get_cmd_output_from_stdin
def get_cmd_output_from_stdin(stdint_content_binary: bytes, *args, encoding: str = SYS_ENCODING) -> str: """ Returns text output of a command, passing binary data in via stdin. """ p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr ...
python
def get_cmd_output_from_stdin(stdint_content_binary: bytes, *args, encoding: str = SYS_ENCODING) -> str: """ Returns text output of a command, passing binary data in via stdin. """ p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr ...
[ "def", "get_cmd_output_from_stdin", "(", "stdint_content_binary", ":", "bytes", ",", "*", "args", ",", "encoding", ":", "str", "=", "SYS_ENCODING", ")", "->", "str", ":", "p", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdin", "=", "subprocess", "...
Returns text output of a command, passing binary data in via stdin.
[ "Returns", "text", "output", "of", "a", "command", "passing", "binary", "data", "in", "via", "stdin", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L384-L391
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
convert_pdf_to_txt
def convert_pdf_to_txt(filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Converts a PDF file to text. Pass either a filename or a binary object. """ pdftotext = tools['pdftotext'] if pdftotext: # External command method ...
python
def convert_pdf_to_txt(filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Converts a PDF file to text. Pass either a filename or a binary object. """ pdftotext = tools['pdftotext'] if pdftotext: # External command method ...
[ "def", "convert_pdf_to_txt", "(", "filename", ":", "str", "=", "None", ",", "blob", ":", "bytes", "=", "None", ",", "config", ":", "TextProcessingConfig", "=", "_DEFAULT_CONFIG", ")", "->", "str", ":", "pdftotext", "=", "tools", "[", "'pdftotext'", "]", "i...
Converts a PDF file to text. Pass either a filename or a binary object.
[ "Converts", "a", "PDF", "file", "to", "text", ".", "Pass", "either", "a", "filename", "or", "a", "binary", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L399-L432
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
availability_pdf
def availability_pdf() -> bool: """ Is a PDF-to-text tool available? """ pdftotext = tools['pdftotext'] if pdftotext: return True elif pdfminer: log.warning("PDF conversion: pdftotext missing; " "using pdfminer (less efficient)") return True else: ...
python
def availability_pdf() -> bool: """ Is a PDF-to-text tool available? """ pdftotext = tools['pdftotext'] if pdftotext: return True elif pdfminer: log.warning("PDF conversion: pdftotext missing; " "using pdfminer (less efficient)") return True else: ...
[ "def", "availability_pdf", "(", ")", "->", "bool", ":", "pdftotext", "=", "tools", "[", "'pdftotext'", "]", "if", "pdftotext", ":", "return", "True", "elif", "pdfminer", ":", "log", ".", "warning", "(", "\"PDF conversion: pdftotext missing; \"", "\"using pdfminer ...
Is a PDF-to-text tool available?
[ "Is", "a", "PDF", "-", "to", "-", "text", "tool", "available?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L435-L447
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
gen_xml_files_from_docx
def gen_xml_files_from_docx(fp: BinaryIO) -> Iterator[str]: """ Generate XML files (as strings) from a DOCX file. Args: fp: :class:`BinaryIO` object for reading the ``.DOCX`` file Yields: the string contents of each individual XML file within the ``.DOCX`` file Raises: ...
python
def gen_xml_files_from_docx(fp: BinaryIO) -> Iterator[str]: """ Generate XML files (as strings) from a DOCX file. Args: fp: :class:`BinaryIO` object for reading the ``.DOCX`` file Yields: the string contents of each individual XML file within the ``.DOCX`` file Raises: ...
[ "def", "gen_xml_files_from_docx", "(", "fp", ":", "BinaryIO", ")", "->", "Iterator", "[", "str", "]", ":", "try", ":", "z", "=", "zipfile", ".", "ZipFile", "(", "fp", ")", "filelist", "=", "z", ".", "namelist", "(", ")", "for", "filename", "in", "fil...
Generate XML files (as strings) from a DOCX file. Args: fp: :class:`BinaryIO` object for reading the ``.DOCX`` file Yields: the string contents of each individual XML file within the ``.DOCX`` file Raises: zipfile.BadZipFile: if the zip is unreadable (encrypted?)
[ "Generate", "XML", "files", "(", "as", "strings", ")", "from", "a", "DOCX", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L478-L505
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
docx_text_from_xml
def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str: """ Converts an XML tree of a DOCX file to string contents. Args: xml: raw XML text config: :class:`TextProcessingConfig` control object Returns: contents as a string """ root = ElementTree.fromstrin...
python
def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str: """ Converts an XML tree of a DOCX file to string contents. Args: xml: raw XML text config: :class:`TextProcessingConfig` control object Returns: contents as a string """ root = ElementTree.fromstrin...
[ "def", "docx_text_from_xml", "(", "xml", ":", "str", ",", "config", ":", "TextProcessingConfig", ")", "->", "str", ":", "root", "=", "ElementTree", ".", "fromstring", "(", "xml", ")", "return", "docx_text_from_xml_node", "(", "root", ",", "0", ",", "config",...
Converts an XML tree of a DOCX file to string contents. Args: xml: raw XML text config: :class:`TextProcessingConfig` control object Returns: contents as a string
[ "Converts", "an", "XML", "tree", "of", "a", "DOCX", "file", "to", "string", "contents", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L508-L520
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
docx_text_from_xml_node
def docx_text_from_xml_node(node: ElementTree.Element, level: int, config: TextProcessingConfig) -> str: """ Returns text from an XML node within a DOCX file. Args: node: an XML node level: current level in XML hierarchy (used for recu...
python
def docx_text_from_xml_node(node: ElementTree.Element, level: int, config: TextProcessingConfig) -> str: """ Returns text from an XML node within a DOCX file. Args: node: an XML node level: current level in XML hierarchy (used for recu...
[ "def", "docx_text_from_xml_node", "(", "node", ":", "ElementTree", ".", "Element", ",", "level", ":", "int", ",", "config", ":", "TextProcessingConfig", ")", "->", "str", ":", "text", "=", "''", "# log.debug(\"Level {}, tag {}\", level, node.tag)", "if", "node", "...
Returns text from an XML node within a DOCX file. Args: node: an XML node level: current level in XML hierarchy (used for recursion; start level is 0) config: :class:`TextProcessingConfig` control object Returns: contents as a string
[ "Returns", "text", "from", "an", "XML", "node", "within", "a", "DOCX", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L523-L555
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
docx_table_from_xml_node
def docx_table_from_xml_node(table_node: ElementTree.Element, level: int, config: TextProcessingConfig) -> str: """ Converts an XML node representing a DOCX table into a textual representation. Args: table_node: XML node level: c...
python
def docx_table_from_xml_node(table_node: ElementTree.Element, level: int, config: TextProcessingConfig) -> str: """ Converts an XML node representing a DOCX table into a textual representation. Args: table_node: XML node level: c...
[ "def", "docx_table_from_xml_node", "(", "table_node", ":", "ElementTree", ".", "Element", ",", "level", ":", "int", ",", "config", ":", "TextProcessingConfig", ")", "->", "str", ":", "table", "=", "CustomDocxTable", "(", ")", "for", "row_node", "in", "table_no...
Converts an XML node representing a DOCX table into a textual representation. Args: table_node: XML node level: current level in XML hierarchy (used for recursion; start level is 0) config: :class:`TextProcessingConfig` control object Returns: string representat...
[ "Converts", "an", "XML", "node", "representing", "a", "DOCX", "table", "into", "a", "textual", "representation", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L630-L660
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
docx_process_simple_text
def docx_process_simple_text(text: str, width: int) -> str: """ Word-wraps text. Args: text: text to process width: width to word-wrap to (or 0 to skip word wrapping) Returns: wrapped text """ if width: return '\n'.join(textwrap.wrap(text, width=width)) else...
python
def docx_process_simple_text(text: str, width: int) -> str: """ Word-wraps text. Args: text: text to process width: width to word-wrap to (or 0 to skip word wrapping) Returns: wrapped text """ if width: return '\n'.join(textwrap.wrap(text, width=width)) else...
[ "def", "docx_process_simple_text", "(", "text", ":", "str", ",", "width", ":", "int", ")", "->", "str", ":", "if", "width", ":", "return", "'\\n'", ".", "join", "(", "textwrap", ".", "wrap", "(", "text", ",", "width", "=", "width", ")", ")", "else", ...
Word-wraps text. Args: text: text to process width: width to word-wrap to (or 0 to skip word wrapping) Returns: wrapped text
[ "Word", "-", "wraps", "text", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L667-L681
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
docx_process_table
def docx_process_table(table: DOCX_TABLE_TYPE, config: TextProcessingConfig) -> str: """ Converts a DOCX table to text. Structure representing a DOCX table: .. code-block:: none table .rows[] .cells[] .paragraphs[] ...
python
def docx_process_table(table: DOCX_TABLE_TYPE, config: TextProcessingConfig) -> str: """ Converts a DOCX table to text. Structure representing a DOCX table: .. code-block:: none table .rows[] .cells[] .paragraphs[] ...
[ "def", "docx_process_table", "(", "table", ":", "DOCX_TABLE_TYPE", ",", "config", ":", "TextProcessingConfig", ")", "->", "str", ":", "def", "get_cell_text", "(", "cell_", ")", "->", "str", ":", "cellparagraphs", "=", "[", "paragraph", ".", "text", ".", "str...
Converts a DOCX table to text. Structure representing a DOCX table: .. code-block:: none table .rows[] .cells[] .paragraphs[] .text That's the structure of a :class:`docx.table.Table` object, but also of our homebrew cre...
[ "Converts", "a", "DOCX", "table", "to", "text", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L684-L800
RudolfCardinal/pythonlib
cardinal_pythonlib/extract_text.py
docx_docx_iter_block_items
def docx_docx_iter_block_items(parent: DOCX_CONTAINER_TYPE) \ -> Iterator[DOCX_BLOCK_ITEM_TYPE]: # only called if docx loaded """ Iterate through items of a DOCX file. See https://github.com/python-openxml/python-docx/issues/40. Yield each paragraph and table child within ``parent``, in do...
python
def docx_docx_iter_block_items(parent: DOCX_CONTAINER_TYPE) \ -> Iterator[DOCX_BLOCK_ITEM_TYPE]: # only called if docx loaded """ Iterate through items of a DOCX file. See https://github.com/python-openxml/python-docx/issues/40. Yield each paragraph and table child within ``parent``, in do...
[ "def", "docx_docx_iter_block_items", "(", "parent", ":", "DOCX_CONTAINER_TYPE", ")", "->", "Iterator", "[", "DOCX_BLOCK_ITEM_TYPE", "]", ":", "# only called if docx loaded", "if", "isinstance", "(", "parent", ",", "docx", ".", "document", ".", "Document", ")", ":", ...
Iterate through items of a DOCX file. See https://github.com/python-openxml/python-docx/issues/40. Yield each paragraph and table child within ``parent``, in document order. Each returned value is an instance of either :class:`Table` or :class:`Paragraph`. ``parent`` would most commonly be a reference...
[ "Iterate", "through", "items", "of", "a", "DOCX", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L808-L836