signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def _sufficient_gaps(self,<EOL>startdate: datetime.date,<EOL>enddate: datetime.date,<EOL>requiredgaps: List[datetime.timedelta],<EOL>flexibility: int) -> Tuple[bool, Optional[Interval]]:
requiredgaps = list(requiredgaps) <EOL>interval = Interval.dayspan(startdate, enddate, include_end=True)<EOL>gaps = self.gap_subset(interval, flexibility)<EOL>gapdurations = gaps.durations()<EOL>gaplist = gaps.list()<EOL>gapdurations.sort(reverse=True) <EOL>requiredgaps.sort(reverse=True) <EOL>while requiredgaps:<EO...
Are there sufficient gaps (specified by ``requiredgaps``) in the date range specified? This is a worker function for :meth:`sufficient_gaps`.
f14675:c1:m35
def sufficient_gaps(self,<EOL>every_n_days: int,<EOL>requiredgaps: List[datetime.timedelta],<EOL>flexibility: int = <NUM_LIT:2>)-> Tuple[bool, Optional[Interval]]:
if len(self.intervals) < <NUM_LIT:2>:<EOL><INDENT>return False, None<EOL><DEDENT>startdate = self.start_date()<EOL>enddate = self.end_date()<EOL>ndays = (enddate - startdate).days + <NUM_LIT:1><EOL>if ndays <= every_n_days:<EOL><INDENT>return self._sufficient_gaps(startdate, enddate, requiredgaps,<EOL>flexibility)<EOL>...
Are gaps present sufficiently often? For example: .. code-block:: python every_n_days=21 requiredgaps=[ datetime.timedelta(hours=62), datetime.timedelta(hours=48), ] ... means "is there at least one 62-hour gap and one (separate) 48-hour gap in every possible 21-day sequence within the In...
f14675:c1:m36
def cumulative_time_to(self,<EOL>when: datetime.datetime) -> datetime.timedelta:
assert self.no_overlap, self._ONLY_FOR_NO_INTERVAL<EOL>cumulative = datetime.timedelta()<EOL>for interval in self.intervals:<EOL><INDENT>if interval.start >= when:<EOL><INDENT>break<EOL><DEDENT>elif interval.end <= when:<EOL><INDENT>cumulative += interval.duration()<EOL><DEDENT>else: <EOL><INDENT>cumulative += when - ...
Returns the cumulative time contained in our intervals up to the specified time point.
f14675:c1:m37
def cumulative_gaps_to(self,<EOL>when: datetime.datetime) -> datetime.timedelta:
gaps = self.gaps()<EOL>return gaps.cumulative_time_to(when)<EOL>
Return the cumulative time within our gaps, up to ``when``.
f14675:c1:m38
def time_afterwards_preceding(<EOL>self, when: datetime.datetime) -> Optional[datetime.timedelta]:
if self.is_empty():<EOL><INDENT>return None<EOL><DEDENT>end_time = self.end_datetime()<EOL>if when <= end_time:<EOL><INDENT>return datetime.timedelta()<EOL><DEDENT>else:<EOL><INDENT>return when - end_time<EOL><DEDENT>
Returns the time after our last interval, but before ``when``. If ``self`` is an empty list, returns ``None``.
f14675:c1:m39
def cumulative_before_during_after(self,<EOL>start: datetime.datetime,<EOL>when: datetime.datetime) ->Tuple[datetime.timedelta,<EOL>datetime.timedelta,<EOL>datetime.timedelta]:
assert self.no_overlap, (<EOL>"<STR_LIT>"<EOL>)<EOL>no_time = datetime.timedelta()<EOL>earliest_interval_start = self.start_datetime()<EOL>if when <= start:<EOL><INDENT>return no_time, no_time, no_time<EOL><DEDENT>if self.is_empty() or when <= earliest_interval_start:<EOL><INDENT>return when - start, no_time, no_time<E...
For a given time, ``when``, returns the cumulative time - after ``start`` but before ``self`` begins, prior to ``when``; - after ``start`` and during intervals represented by ``self``, prior to ``when``; - after ``start`` and after at least one interval represented by ``self`` has finished, and not within any inte...
f14675:c1:m40
def reformat_python_docstrings(top_dirs: List[str],<EOL>correct_copyright_lines: List[str],<EOL>show_only: bool = True,<EOL>rewrite: bool = False,<EOL>process_only_filenum: int = None) -> None:
filenum = <NUM_LIT:0><EOL>for top_dir in top_dirs:<EOL><INDENT>for dirpath, dirnames, filenames in walk(top_dir):<EOL><INDENT>for filename in filenames:<EOL><INDENT>fullname = join(dirpath, filename)<EOL>extension = splitext(filename)[<NUM_LIT:1>]<EOL>if extension != PYTHON_EXTENSION:<EOL><INDENT>continue<EOL><DEDENT>f...
Walk a directory, finding Python files and rewriting them. Args: top_dirs: list of directories to descend into correct_copyright_lines: list of lines (without newlines) representing the copyright docstring block, including the transition lines of equals symbols show_only: show resul...
f14676:m0
def __init__(self, full_path: str, top_dir: str,<EOL>correct_copyright_lines: List[str]) -> None:
self.full_path = full_path<EOL>self.advertised_filename = relative_filename_within_dir(<EOL>full_path, top_dir)<EOL>self.correct_copyright_lines = correct_copyright_lines<EOL>self.needs_rewriting = False<EOL>self.source_lines = [] <EOL>self.dest_lines = [] <EOL>self._read_source()<EOL>self._create_dest()<EOL>
Args: full_path: full path to source file top_dir: directory from which we calculate a relative filename to be shown correct_copyright_lines: list of lines (without newlines) representing the copyright docstring block, including the transition lines of equals ...
f14676:c0:m0
def _read_source(self) -> None:
with open(self.full_path, "<STR_LIT>") as f:<EOL><INDENT>for linenum, line_with_nl in enumerate(f.readlines(), start=<NUM_LIT:1>):<EOL><INDENT>line_without_newline = (<EOL>line_with_nl[:-<NUM_LIT:1>] if line_with_nl.endswith(NL)<EOL>else line_with_nl<EOL>)<EOL>if TAB in line_without_newline:<EOL><INDENT>self._warn("<ST...
Reads the source file.
f14676:c0:m1
def _create_dest(self) -> None:
in_body = False<EOL>in_docstring = False<EOL>in_copyright = False<EOL>copyright_done = False<EOL>docstring_done = False<EOL>swallow_blanks_and_filename_in_docstring = False<EOL>for linenum, sl in enumerate(self.source_lines, start=<NUM_LIT:1>):<EOL><INDENT>dl = sl<EOL>if dl.endswith(SPACE):<EOL><INDENT>self._debug("<ST...
Creates an internal representation of the destination file. This is where the thinking happens
f14676:c0:m2
@staticmethod<EOL><INDENT>def _debug_line(linenum: int, line: str, extramsg: str = "<STR_LIT>") -> None:<DEDENT>
log.critical("<STR_LIT>", extramsg, linenum, line)<EOL>
Writes a debugging report on a line.
f14676:c0:m3
def _logmsg(self, msg: str) -> str:
return "<STR_LIT>".format(self.advertised_filename, msg)<EOL>
Formats a log message.
f14676:c0:m4
def _critical(self, msg: str) -> None:
log.critical(self._logmsg(msg))<EOL>
Shows a critical message.
f14676:c0:m5
def _warn(self, msg: str) -> None:
log.warning(self._logmsg(msg))<EOL>
Shows a warning.
f14676:c0:m6
def _info(self, msg: str) -> None:
log.info(self._logmsg(msg))<EOL>
Shows an info message.
f14676:c0:m7
def _debug(self, msg: str) -> None:
log.debug(self._logmsg(msg))<EOL>
Shows a debugging message.
f14676:c0:m8
def _too_risky(self) -> None:
self._warn("<STR_LIT>")<EOL>self.needs_rewriting = False<EOL>
Shows a warning and sets this file as not for processing
f14676:c0:m9
def show(self) -> None:
self._write(stdout)<EOL>
Writes the destination to stdout.
f14676:c0:m10
def rewrite_file(self) -> None:
if not self.needs_rewriting:<EOL><INDENT>return<EOL><DEDENT>self._info("<STR_LIT>")<EOL>with open(self.full_path, "<STR_LIT:w>") as outfile:<EOL><INDENT>self._write(outfile)<EOL><DEDENT>
Rewrites the source file.
f14676:c0:m11
def _write(self, destination: TextIO) -> None:
for line in self.dest_lines:<EOL><INDENT>destination.write(line + NL)<EOL><DEDENT>
Writes the converted output to a destination.
f14676:c0:m12
def to_bytes(data: Any) -> bytearray:
<EOL>instance(data, int):<EOL>eturn bytearray([data])<EOL>n bytearray(data, encoding='<STR_LIT>')<EOL>
Convert anything to a ``bytearray``. See - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1
f14677:m2
def to_str(data: Any) -> str:
return str(data)<EOL>
Convert anything to a ``str``.
f14677:m3
def twos_comp_to_signed(val: int, n_bits: int) -> int:
assert n_bits % <NUM_LIT:8> == <NUM_LIT:0>, "<STR_LIT>"<EOL>n_bytes = n_bits // <NUM_LIT:8><EOL>b = val.to_bytes(n_bytes, byteorder=sys.byteorder, signed=False)<EOL>return int.from_bytes(b, byteorder=sys.byteorder, signed=True)<EOL>
Convert a "two's complement" representation (as an integer) to its signed version. Args: val: positive integer representing a number in two's complement format n_bits: number of bits (which must reflect a whole number of bytes) Returns: signed integer See http://stackoverflow.com/questions/1604464/twos-c...
f14677:m4
def signed_to_twos_comp(val: int, n_bits: int) -> int:
assert n_bits % <NUM_LIT:8> == <NUM_LIT:0>, "<STR_LIT>"<EOL>n_bytes = n_bits // <NUM_LIT:8><EOL>b = val.to_bytes(n_bytes, byteorder=sys.byteorder, signed=True)<EOL>return int.from_bytes(b, byteorder=sys.byteorder, signed=False)<EOL>
Convert a signed integer to its "two's complement" representation. Args: val: signed integer n_bits: number of bits (which must reflect a whole number of bytes) Returns: unsigned integer: two's complement version
f14677:m5
def bytes_to_long(bytesdata: bytes) -> int:
assert len(bytesdata) == <NUM_LIT:8><EOL>return sum((b << (k * <NUM_LIT:8>) for k, b in enumerate(bytesdata)))<EOL>
Converts an 8-byte sequence to a long integer. Args: bytesdata: 8 consecutive bytes, as a ``bytes`` object, in little-endian format (least significant byte [LSB] first) Returns: integer
f14677:m6
def murmur3_x86_32(data: Union[bytes, bytearray], seed: int = <NUM_LIT:0>) -> int:
<EOL><NUM_LIT><EOL><NUM_LIT><EOL>h = len(data)<EOL>seed<EOL>ed_end = (length & <NUM_LIT>) <EOL><INDENT>in range(<NUM_LIT:0>, rounded_end, <NUM_LIT:4>):<EOL>little endian load order<EOL>RNC: removed ord() calls<EOL><DEDENT><NUM_LIT:1> = (data[i] & <NUM_LIT>) | ((data[i + <NUM_LIT:1>] & <NUM_LIT>) << <NUM_LIT:8>) |((dat...
Pure 32-bit Python implementation of MurmurHash3; see http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash. Args: data: data to hash seed: seed Returns: integer hash
f14677:m7
def murmur3_64(data: Union[bytes, bytearray], seed: int = <NUM_LIT>) -> int:
<EOL>xc6a4a7935bd1e995<EOL><NUM_LIT:7><EOL>= <NUM_LIT:2> ** <NUM_LIT:64> - <NUM_LIT:1><EOL>h = len(data)<EOL>eed ^ ((m * length) & mask)<EOL>t = (length // <NUM_LIT:8>) * <NUM_LIT:8><EOL>: was /, but for Python <NUM_LIT:3> that gives float; brackets added for clarity<EOL>l in range(<NUM_LIT:0>, offset, <NUM_LIT:8>):<EO...
Pure 64-bit Python implementation of MurmurHash3; see http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash (plus RNC bugfixes). Args: data: data to hash seed: seed Returns: integer hash
f14677:m8
def pymmh3_hash128_x64(key: Union[bytes, bytearray], seed: int) -> int:
def fmix(k):<EOL><INDENT>k ^= k >> <NUM_LIT><EOL>k = (k * <NUM_LIT>) & <NUM_LIT><EOL>k ^= k >> <NUM_LIT><EOL>k = (k * <NUM_LIT>) & <NUM_LIT><EOL>k ^= k >> <NUM_LIT><EOL>return k<EOL><DEDENT>length = len(key)<EOL>nblocks = int(length / <NUM_LIT:16>)<EOL>h1 = seed<EOL>h2 = seed<EOL>c1 = <NUM_LIT><EOL>c2 = <NUM_LIT><EOL>f...
Implements 128-bit murmur3 hash for x64, as per ``pymmh3``, with some bugfixes. Args: key: data to hash seed: seed Returns: integer hash
f14677:m9
def pymmh3_hash128_x86(key: Union[bytes, bytearray], seed: int) -> int:
def fmix(h):<EOL><INDENT>h ^= h >> <NUM_LIT:16><EOL>h = (h * <NUM_LIT>) & <NUM_LIT><EOL>h ^= h >> <NUM_LIT><EOL>h = (h * <NUM_LIT>) & <NUM_LIT><EOL>h ^= h >> <NUM_LIT:16><EOL>return h<EOL><DEDENT>length = len(key)<EOL>nblocks = int(length / <NUM_LIT:16>)<EOL>h1 = seed<EOL>h2 = seed<EOL>h3 = seed<EOL>h4 = seed<EOL>c1 = ...
Implements 128-bit murmur3 hash for x86, as per ``pymmh3``, with some bugfixes. Args: key: data to hash seed: seed Returns: integer hash
f14677:m10
def pymmh3_hash128(key: Union[bytes, bytearray],<EOL>seed: int = <NUM_LIT:0>,<EOL>x64arch: bool = True) -> int:
if x64arch:<EOL><INDENT>return pymmh3_hash128_x64(key, seed)<EOL><DEDENT>else:<EOL><INDENT>return pymmh3_hash128_x86(key, seed)<EOL><DEDENT>
Implements 128bit murmur3 hash, as per ``pymmh3``. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: integer hash
f14677:m11
def pymmh3_hash64(key: Union[bytes, bytearray],<EOL>seed: int = <NUM_LIT:0>,<EOL>x64arch: bool = True) -> Tuple[int, int]:
hash_128 = pymmh3_hash128(key, seed, x64arch)<EOL>unsigned_val1 = hash_128 & <NUM_LIT> <EOL>if unsigned_val1 & <NUM_LIT> == <NUM_LIT:0>:<EOL><INDENT>signed_val1 = unsigned_val1<EOL><DEDENT>else:<EOL><INDENT>signed_val1 = -((unsigned_val1 ^ <NUM_LIT>) + <NUM_LIT:1>)<EOL><DEDENT>unsigned_val2 = (hash_128 >> <NUM_LIT:64>...
Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: tuple: tuple of integers, ``(signed_val1, signed_val2)``
f14677:m12
def compare_python_to_reference_murmur3_32(data: Any, seed: int = <NUM_LIT:0>) -> None:
assert mmh3, "<STR_LIT>"<EOL>c_data = to_str(data)<EOL>c_signed = mmh3.hash(c_data, seed=seed) <EOL>py_data = to_bytes(c_data)<EOL>py_unsigned = murmur3_x86_32(py_data, seed=seed)<EOL>py_signed = twos_comp_to_signed(py_unsigned, n_bits=<NUM_LIT:32>)<EOL>preamble = "<STR_LIT>".format(<EOL>data=repr(data), seed=seed)<EO...
Checks the pure Python implementation of 32-bit murmur3 against the ``mmh3`` C-based module. Args: data: data to hash seed: seed Raises: AssertionError: if the two calculations don't match
f14677:m13
def compare_python_to_reference_murmur3_64(data: Any, seed: int = <NUM_LIT:0>) -> None:
assert mmh3, "<STR_LIT>"<EOL>c_data = to_str(data)<EOL>c_signed_low, c_signed_high = mmh3.hash64(c_data, seed=seed,<EOL>x64arch=IS_64_BIT)<EOL>py_data = to_bytes(c_data)<EOL>py_signed_low, py_signed_high = pymmh3_hash64(py_data, seed=seed)<EOL>preamble = "<STR_LIT>""<STR_LIT>".format(data=repr(data), seed=seed)<EOL>if ...
Checks the pure Python implementation of 64-bit murmur3 against the ``mmh3`` C-based module. Args: data: data to hash seed: seed Raises: AssertionError: if the two calculations don't match
f14677:m14
def hash32(data: Any, seed=<NUM_LIT:0>) -> int:
with MultiTimerContext(timer, TIMING_HASH):<EOL><INDENT>c_data = to_str(data)<EOL>if mmh3:<EOL><INDENT>return mmh3.hash(c_data, seed=seed)<EOL><DEDENT>py_data = to_bytes(c_data)<EOL>py_unsigned = murmur3_x86_32(py_data, seed=seed)<EOL>return twos_comp_to_signed(py_unsigned, n_bits=<NUM_LIT:32>)<EOL><DEDENT>
Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 32-bit integer
f14677:m15
def hash64(data: Any, seed: int = <NUM_LIT:0>) -> int:
<EOL>c_data = to_str(data)<EOL>if mmh3:<EOL><INDENT>c_signed_low, _ = mmh3.hash64(data, seed=seed, x64arch=IS_64_BIT)<EOL>return c_signed_low<EOL><DEDENT>py_data = to_bytes(c_data)<EOL>py_signed_low, _ = pymmh3_hash64(py_data, seed=seed)<EOL>return py_signed_low<EOL>
Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 64-bit integer
f14677:m16
def main() -> None:
_ = """<STR_LIT>""" <EOL>testdata = [<EOL>"<STR_LIT:hello>",<EOL><NUM_LIT:1>,<EOL>["<STR_LIT>", "<STR_LIT>"],<EOL>]<EOL>for data in testdata:<EOL><INDENT>compare_python_to_reference_murmur3_32(data, seed=<NUM_LIT:0>)<EOL>compare_python_to_reference_murmur3_64(data, seed=<NUM_LIT:0>)<EOL><DEDENT>print("<STR_LIT>")<EOL>
Command-line validation checks.
f14677:m17
def hash(self, raw: Any) -> str:
raise NotImplementedError()<EOL>
Returns a hash of its input.
f14677:c0:m0
def output_length(self) -> int:
return len(self.hash("<STR_LIT>"))<EOL>
Returns the length of the hashes produced by this hasher.
f14677:c0:m1
def sqla_column_type(self) -> TypeEngine:
return String(length=self.output_length())<EOL>
Returns a SQLAlchemy :class:`Column` type instance, specifically ``String(length=self.output_length())``.
f14677:c0:m2
def __init__(self, hashfunc: Callable[[bytes], Any], salt: str) -> None:
self.hashfunc = hashfunc<EOL>self.salt_bytes = salt.encode('<STR_LIT:utf-8>')<EOL>
Args: hashfunc: hash function to use salt: salt to use (following UTF-8 encoding)
f14677:c1:m0
def __init__(self, digestmod: Any, key: str) -> None:
self.key_bytes = str(key).encode('<STR_LIT:utf-8>')<EOL>self.digestmod = digestmod<EOL>
Args: digestmod: see :func:`hmac.HMAC.__init__` key: cryptographic key to use
f14677:c5:m0
def hash(self, raw: Any) -> str:
with MultiTimerContext(timer, TIMING_HASH):<EOL><INDENT>raw_bytes = str(raw).encode('<STR_LIT:utf-8>')<EOL>hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes,<EOL>digestmod=self.digestmod)<EOL>return hmac_obj.hexdigest()<EOL><DEDENT>
Returns the hex digest of a HMAC-encoded version of the input.
f14677:c5:m1
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:
for key in d.keys():<EOL><INDENT>if k.lower() == key.lower():<EOL><INDENT>return key<EOL><DEDENT><DEDENT>return None<EOL>
Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one).
f14678:m0
def merge_dicts(*dict_args: Dict) -> Dict:
result = {}<EOL>for dictionary in dict_args:<EOL><INDENT>result.update(dictionary)<EOL><DEDENT>return result<EOL>
Given any number of dicts, shallow-copy them and merge into a new dict. Precedence goes to key/value pairs in dicts that are later in the list. See http://stackoverflow.com/questions/38987.
f14678:m1
def merge_two_dicts(x: Dict, y: Dict) -> Dict:
z = x.copy()<EOL>z.update(y)<EOL>return z<EOL>
Given two dicts, merge them into a new dict as a shallow copy, e.g. .. code-block:: python z = merge_two_dicts(x, y) If you can guarantee Python 3.5, then a simpler syntax is: .. code-block:: python z = {**x, **y} See http://stackoverflow.com/questions/38987.
f14678:m2
def rename_key(d: Dict[str, Any], old: str, new: str) -> None:
d[new] = d.pop(old)<EOL>
Rename a key in dictionary ``d`` from ``old`` to ``new``, in place.
f14678:m3
def rename_keys(d: Dict[str, Any], mapping: Dict[str, str]) -> Dict[str, Any]:
result = {} <EOL>for k, v in d.items():<EOL><INDENT>if k in mapping:<EOL><INDENT>k = mapping[k]<EOL><DEDENT>result[k] = v<EOL><DEDENT>return result<EOL>
Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: a new dictionary Keys that are not in ``mapping`` are left unchanged. The input parameters are not modified...
f14678:m4
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None:
<EOL>ld_key, new_key in renames.items():<EOL>f new_key == old_key:<EOL><INDENT>continue<EOL><DEDENT>f old_key in d:<EOL><INDENT>if new_key in d:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(repr(old_key), repr(new_key)))<EOL><DEDENT>d[new_key] = d.pop(old_key)<EOL><DEDENT>
Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary.
f14678:m5
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]:
result = {} <EOL>for k, v in d.items():<EOL><INDENT>result[prefix + k] = v<EOL><DEDENT>return result<EOL>
Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys.
f14678:m6
def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]:
return {v: k for k, v in d.items()}<EOL>
Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping.
f14678:m7
def set_null_values_in_dict(d: Dict[str, Any],<EOL>null_literals: List[Any]) -> None:
if not null_literals:<EOL><INDENT>return<EOL><DEDENT>for k, v in d.items():<EOL><INDENT>if v in null_literals:<EOL><INDENT>d[k] = None<EOL><DEDENT><DEDENT>
Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``.
f14678:m8
def map_keys_to_values(l: List[Any], d: Dict[Any, Any], default: Any = None,<EOL>raise_if_missing: bool = False,<EOL>omit_if_missing: bool = False) -> List[Any]:
result = []<EOL>for k in l:<EOL><INDENT>if raise_if_missing and k not in d:<EOL><INDENT>raise ValueError("<STR_LIT>" + repr(k))<EOL><DEDENT>if omit_if_missing and k not in d:<EOL><INDENT>continue<EOL><DEDENT>result.append(d.get(k, default))<EOL><DEDENT>return result<EOL>
The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l``, and return a list of corresponding values -- substituting ``default`` if any are missing, or raising :exc:`KeyError` if ``raise_if_missing`` is true, or omitting the entry if ``omit_if_missing`` is true.
f14678:m9
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any],<EOL>deleted_value: Any = None) -> Dict[Any, Any]:
changes = {k: v for k, v in d2.items()<EOL>if k not in d1 or d2[k] != d1[k]}<EOL>for k in d1.keys():<EOL><INDENT>if k not in d2:<EOL><INDENT>changes[k] = deleted_value<EOL><DEDENT><DEDENT>return changes<EOL>
Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to use for deleted keys; see below Returns: dict: a dictionary of the format ``{k: v}`` where the ``k``/``v`` pairs are key/value pairs that a...
f14678:m10
def delete_keys(d: Dict[Any, Any],<EOL>keys_to_delete: List[Any],<EOL>keys_to_keep: List[Any]) -> None:
for k in keys_to_delete:<EOL><INDENT>if k in d and k not in keys_to_keep:<EOL><INDENT>del d[k]<EOL><DEDENT><DEDENT>
Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are deleted... keys_to_keep: ... unless they are present in this list.
f14678:m11
def tsv_escape(x: Any) -> str:
if x is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>x = str(x)<EOL>return x.replace("<STR_LIT:\t>", "<STR_LIT>").replace("<STR_LIT:\n>", "<STR_LIT>")<EOL>
Escape data for tab-separated value (TSV) format.
f14679:m0
def make_tsv_row(values: List[Any]) -> str:
return "<STR_LIT:\t>".join([tsv_escape(x) for x in values]) + "<STR_LIT:\n>"<EOL>
From a list of values, make a TSV line.
f14679:m1
def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str:
if not dictlist:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>fieldnames = dictlist[<NUM_LIT:0>].keys()<EOL>tsv = "<STR_LIT:\t>".join([tsv_escape(f) for f in fieldnames]) + "<STR_LIT:\n>"<EOL>for d in dictlist:<EOL><INDENT>tsv += "<STR_LIT:\t>".join([tsv_escape(v) for v in d.values()]) + "<STR_LIT:\n>"<EOL><DEDENT>return...
From a consistent list of dictionaries mapping fieldnames to values, make a TSV file.
f14679:m2
def tsv_pairs_to_dict(line: str, key_lower: bool = True) -> Dict[str, str]:
items = line.split("<STR_LIT:\t>")<EOL>d = {} <EOL>for chunk in chunks(items, <NUM_LIT:2>):<EOL><INDENT>if len(chunk) < <NUM_LIT:2>:<EOL><INDENT>log.warning("<STR_LIT>", chunk)<EOL>continue<EOL><DEDENT>key = chunk[<NUM_LIT:0>]<EOL>value = unescape_tabs_newlines(chunk[<NUM_LIT:1>])<EOL>if key_lower:<EOL><INDENT>key = k...
r""" Converts a TSV line into sequential key/value pairs as a dictionary. For example, .. code-block:: none field1\tvalue1\tfield2\tvalue2 becomes .. code-block:: none {"field1": "value1", "field2": "value2"} Args: line: the line key_lower: should the keys ...
f14679:m3
def assert_processor_available(processor: str) -> None:
if processor not in [Processors.XHTML2PDF,<EOL>Processors.WEASYPRINT,<EOL>Processors.PDFKIT]:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if processor == Processors.WEASYPRINT and not weasyprint:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if processor == Processors.XHTML2PDF a...
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
f14680:m0
def get_default_fix_pdfkit_encoding_bug() -> bool:
<EOL>if pdfkit is None:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return bool(Version(pdfkit.__version__) == Version("<STR_LIT>"))<EOL><DEDENT>
Should we be trying to fix a ``pdfkit`` encoding bug, by default? Returns: should we? Yes if we have the specific buggy version of ``pdfkit``.
f14680:m1
def make_pdf_from_html(<EOL>on_disk: bool,<EOL>html: str,<EOL>output_path: str = None,<EOL>header_html: str = None,<EOL>footer_html: str = None,<EOL>wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,<EOL>wkhtmltopdf_options: Dict[str, Any] = None,<EOL>file_encoding: str = "<STR_LIT:utf-8>",<EOL>debug_options: bool = Fa...
wkhtmltopdf_options = wkhtmltopdf_options or {} <EOL>assert_processor_available(processor)<EOL>if debug_content:<EOL><INDENT>log.debug("<STR_LIT>", html)<EOL>log.debug("<STR_LIT>", header_html)<EOL>log.debug("<STR_LIT>", footer_html)<EOL><DEDENT>if fix_pdfkit_encoding_bug is None:<EOL><INDENT>fix_pdfkit_encoding_bug =...
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 allow you to pass ...
f14680:m2
def get_pdf_from_html(html: str,<EOL>header_html: str = None,<EOL>footer_html: str = None,<EOL>wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,<EOL>wkhtmltopdf_options: Dict[str, Any] = None,<EOL>file_encoding: str = "<STR_LIT:utf-8>",<EOL>debug_options: bool = False,<EOL>debug_content: bool = False,<EOL>debug_wkhtml...
result = make_pdf_from_html(<EOL>on_disk=False,<EOL>html=html,<EOL>header_html=header_html,<EOL>footer_html=footer_html,<EOL>wkhtmltopdf_filename=wkhtmltopdf_filename,<EOL>wkhtmltopdf_options=wkhtmltopdf_options,<EOL>file_encoding=file_encoding,<EOL>debug_options=debug_options,<EOL>debug_content=debug_content,<EOL>debu...
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
f14680:m3
def pdf_from_html(html: str,<EOL>header_html: str = None,<EOL>footer_html: str = None,<EOL>wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,<EOL>wkhtmltopdf_options: Dict[str, Any] = None,<EOL>file_encoding: str = "<STR_LIT:utf-8>",<EOL>debug_options: bool = False,<EOL>debug_content: bool = False,<EOL>fix_pdfkit_encod...
return get_pdf_from_html(html=html,<EOL>header_html=header_html,<EOL>footer_html=footer_html,<EOL>wkhtmltopdf_filename=wkhtmltopdf_filename,<EOL>wkhtmltopdf_options=wkhtmltopdf_options,<EOL>file_encoding=file_encoding,<EOL>debug_options=debug_options,<EOL>debug_content=debug_content,<EOL>fix_pdfkit_encoding_bug=fix_pdf...
Older function name for :func:`get_pdf_from_html` (q.v.).
f14680:m4
def make_pdf_on_disk_from_html(<EOL>html: str,<EOL>output_path: str,<EOL>header_html: str = None,<EOL>footer_html: str = None,<EOL>wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,<EOL>wkhtmltopdf_options: Dict[str, Any] = None,<EOL>file_encoding: str = "<STR_LIT:utf-8>",<EOL>debug_options: bool = False,<EOL>debug_con...
result = make_pdf_from_html(<EOL>on_disk=True,<EOL>output_path=output_path,<EOL>html=html,<EOL>header_html=header_html,<EOL>footer_html=footer_html,<EOL>wkhtmltopdf_filename=wkhtmltopdf_filename,<EOL>wkhtmltopdf_options=wkhtmltopdf_options,<EOL>file_encoding=file_encoding,<EOL>debug_options=debug_options,<EOL>debug_con...
Takes HTML and writes a PDF to the file specified by ``output_path``. See the arguments to :func:`make_pdf_from_html` (except ``on_disk``). Returns: success?
f14680:m5
def pdf_from_writer(writer: Union[PdfFileWriter, PdfFileMerger]) -> bytes:
memfile = io.BytesIO()<EOL>writer.write(memfile)<EOL>memfile.seek(<NUM_LIT:0>)<EOL>return memfile.read()<EOL>
Extracts a PDF (as binary data) from a PyPDF2 writer or merger object.
f14680:m6
def serve_pdf_to_stdout(pdf: bytes) -> None:
<EOL>print("<STR_LIT>")<EOL>sys.stdout.write(pdf)<EOL>
Serves a PDF to ``stdout`` (for web servers). Writes a ``Content-Type: application/pdf`` header and then the PDF to ``stdout``. See: - http://stackoverflow.com/questions/312230/proper-mime-type-for-pdf-files - http://www.askapache.com/htaccess/pdf-cookies-headers-rewrites.html - http://stackoverflow.com/questions/23...
f14680:m7
def make_pdf_writer() -> PdfFileWriter:
return PdfFileWriter()<EOL>
Creates and returns a PyPDF2 writer.
f14680:m8
def append_memory_pdf_to_writer(input_pdf: bytes,<EOL>writer: PdfFileWriter,<EOL>start_recto: bool = True) -> None:
if not input_pdf:<EOL><INDENT>return<EOL><DEDENT>if start_recto and writer.getNumPages() % <NUM_LIT:2> != <NUM_LIT:0>:<EOL><INDENT>writer.addBlankPage()<EOL><DEDENT>infile = io.BytesIO(input_pdf)<EOL>reader = PdfFileReader(infile)<EOL>for page_num in range(reader.numPages):<EOL><INDENT>writer.addPage(reader.getPage(pag...
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?
f14680:m9
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):
append_memory_pdf_to_writer(input_pdf=input_pdf,<EOL>writer=output_writer)<EOL>
Appends a PDF to a pyPDF writer. Legacy interface.
f14680:m10
def get_concatenated_pdf_from_disk(filenames: Iterable[str],<EOL>start_recto: bool = True) -> bytes:
<EOL>if start_recto:<EOL><INDENT>writer = PdfFileWriter()<EOL>for filename in filenames:<EOL><INDENT>if filename:<EOL><INDENT>if writer.getNumPages() % <NUM_LIT:2> != <NUM_LIT:0>:<EOL><INDENT>writer.addBlankPage()<EOL><DEDENT>writer.appendPagesFromReader(<EOL>PdfFileReader(open(filename, '<STR_LIT:rb>')))<EOL><DEDENT><...
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``
f14680:m11
def get_concatenated_pdf_in_memory(<EOL>pdf_plans: Iterable[PdfPlan],<EOL>start_recto: bool = True) -> bytes:
writer = PdfFileWriter()<EOL>for pdfplan in pdf_plans:<EOL><INDENT>pdfplan.add_to_writer(writer, start_recto=start_recto)<EOL><DEDENT>return pdf_from_writer(writer)<EOL>
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``
f14680:m12
def __init__(self,<EOL>is_html: bool = False,<EOL>html: str = None,<EOL>header_html: str = None,<EOL>footer_html: str = None,<EOL>wkhtmltopdf_filename: str = None,<EOL>wkhtmltopdf_options: Dict[str, Any] = None,<EOL>is_filename: bool = False,<EOL>filename: str = None):
assert is_html != is_filename, "<STR_LIT>"<EOL>self.is_html = is_html<EOL>self.html = html<EOL>self.header_html = header_html<EOL>self.footer_html = footer_html<EOL>self.wkhtmltopdf_filename = wkhtmltopdf_filename<EOL>self.wkhtmltopdf_options = wkhtmltopdf_options<EOL>self.is_filename = is_filename<EOL>self.filename = ...
Args: is_html: use HTML mode? html: for HTML mode, the main HTML header_html: for HTML mode, an optional page header (in HTML) footer_html: for HTML mode, an optional page footer (in HTML) wkhtmltopdf_filename: filename of the ``wkhtmltopdf`` executable wkhtmltopdf_options: options for ``wkhtmlt...
f14680:c1:m0
def add_to_writer(self,<EOL>writer: PdfFileWriter,<EOL>start_recto: bool = True) -> None:
if self.is_html:<EOL><INDENT>pdf = get_pdf_from_html(<EOL>html=self.html,<EOL>header_html=self.header_html,<EOL>footer_html=self.footer_html,<EOL>wkhtmltopdf_filename=self.wkhtmltopdf_filename,<EOL>wkhtmltopdf_options=self.wkhtmltopdf_options)<EOL>append_memory_pdf_to_writer(pdf, writer, start_recto=start_recto)<EOL><D...
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?
f14680:c1:m1
def mean(values: Sequence[Union[int, float, None]]) -> Optional[float]:
total = <NUM_LIT:0.0> <EOL>n = <NUM_LIT:0><EOL>for x in values:<EOL><INDENT>if x is not None:<EOL><INDENT>total += x<EOL>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>return total / n if n > <NUM_LIT:0> else None<EOL>
Returns the mean of a list of numbers. Args: values: values to mean, ignoring any values that are ``None`` Returns: the mean, or ``None`` if :math:`n = 0`
f14681:m0
def safe_logit(p: Union[float, int]) -> Optional[float]:
if p > <NUM_LIT:1> or p < <NUM_LIT:0>:<EOL><INDENT>return None <EOL><DEDENT>if p == <NUM_LIT:1>:<EOL><INDENT>return float("<STR_LIT>")<EOL><DEDENT>if p == <NUM_LIT:0>:<EOL><INDENT>return float("<STR_LIT>")<EOL><DEDENT>return math.log(p / (<NUM_LIT:1> - p))<EOL>
r""" Returns the logit (log odds) of its input probability .. math:: \alpha = logit(p) = log(x / (1 - x)) Args: p: :math:`p` Returns: :math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1].
f14681:m1
def normal_round_float(x: float, dp: int = <NUM_LIT:0>) -> float:
if not math.isfinite(x):<EOL><INDENT>return x<EOL><DEDENT>factor = pow(<NUM_LIT:10>, dp)<EOL>x = x * factor<EOL>if x >= <NUM_LIT:0>:<EOL><INDENT>x = math.floor(x + <NUM_LIT:0.5>)<EOL><DEDENT>else:<EOL><INDENT>x = math.ceil(x - <NUM_LIT:0.5>)<EOL><DEDENT>x = x / factor<EOL>return x<EOL>
Hmpf. Shouldn't need to have to implement this, but... Conventional rounding to integer via the "round half away from zero" method, e.g. .. code-block:: none 1.1 -> 1 1.5 -> 2 1.6 -> 2 2.0 -> 2 -1.6 -> -2 etc. ... or the equivalent for a certain number of decimal places. Note that round() ...
f14681:m2
def normal_round_int(x: float) -> int:
if not math.isfinite(x):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x >= <NUM_LIT:0>:<EOL><INDENT>return math.floor(x + <NUM_LIT:0.5>)<EOL><DEDENT>else:<EOL><INDENT>return math.ceil(x - <NUM_LIT:0.5>)<EOL><DEDENT>
Version of :func:`normal_round_float` but guaranteed to return an `int`.
f14681:m3
def coerce_to_pendulum(x: PotentialDatetimeType,<EOL>assume_local: bool = False) -> Optional[DateTime]:
if not x: <EOL><INDENT>return None<EOL><DEDENT>if isinstance(x, DateTime):<EOL><INDENT>return x<EOL><DEDENT>tz = get_tz_local() if assume_local else get_tz_utc()<EOL>if isinstance(x, datetime.datetime):<EOL><INDENT>return pendulum.instance(x, tz=tz) <EOL><DEDENT>elif isinstance(x, datetime.date):<EOL><INDENT>midnight...
Converts something to a :class:`pendulum.DateTime`. Args: x: something that may be coercible to a datetime assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.DateTime`, or ``None``. Raises: pendulum.parsing.exceptions.ParserError: if a strin...
f14683:m0
def coerce_to_pendulum_date(x: PotentialDatetimeType,<EOL>assume_local: bool = False) -> Optional[Date]:
p = coerce_to_pendulum(x, assume_local=assume_local)<EOL>return None if p is None else p.date()<EOL>
Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.Date`, or ``None``. Raises: pendulum.parsing.exceptions.ParserError: if a string fails to p...
f14683:m1
def pendulum_to_datetime(x: DateTime) -> datetime.datetime:
return datetime.datetime(<EOL>x.year, x.month, x.day,<EOL>x.hour, x.minute, x.second, x.microsecond,<EOL>tzinfo=x.tzinfo<EOL>)<EOL>
Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`.
f14683:m2
def pendulum_to_datetime_stripping_tz(x: DateTime) -> datetime.datetime:
return datetime.datetime(<EOL>x.year, x.month, x.day,<EOL>x.hour, x.minute, x.second, x.microsecond,<EOL>tzinfo=None<EOL>)<EOL>
Converts a Pendulum ``DateTime`` to a ``datetime.datetime`` that has had timezone information stripped.
f14683:m3
def pendulum_to_utc_datetime_without_tz(x: DateTime) -> datetime.datetime:
<EOL>lum_in_utc = pendulum.UTC.convert(x)<EOL>n pendulum_to_datetime_stripping_tz(pendulum_in_utc)<EOL>
Converts a Pendulum ``DateTime`` (which will have timezone information) to a ``datetime.datetime`` that (a) has no timezone information, and (b) is in UTC. Example: .. code-block:: python import pendulum from cardinal_pythonlib.datetimefunc import * in_moscow = pendulum.parse("2018-01-01T09:00+0300") # ...
f14683:m4
def pendulum_date_to_datetime_date(x: Date) -> datetime.date:
return datetime.date(year=x.year, month=x.month, day=x.day)<EOL>
Takes a :class:`pendulum.Date` and returns a :class:`datetime.date`. Used, for example, where a database backend insists on :class:`datetime.date`.
f14683:m5
def pendulum_time_to_datetime_time(x: Time) -> datetime.time:
return datetime.time(<EOL>hour=x.hour, minute=x.minute, second=x.second,<EOL>microsecond=x.microsecond,<EOL>tzinfo=x.tzinfo<EOL>)<EOL>
Takes a :class:`pendulum.Time` and returns a :class:`datetime.time`. Used, for example, where a database backend insists on :class:`datetime.time`.
f14683:m6
def format_datetime(d: PotentialDatetimeType,<EOL>fmt: str,<EOL>default: str = None) -> Optional[str]:
d = coerce_to_pendulum(d)<EOL>if d is None:<EOL><INDENT>return default<EOL><DEDENT>return d.strftime(fmt)<EOL>
Format a datetime with a ``strftime`` format specification string, or return ``default`` if the input is ``None``.
f14683:m7
def strfdelta(tdelta: Union[datetime.timedelta, int, float, str],<EOL>fmt='<STR_LIT>',<EOL>inputtype='<STR_LIT>'):
<EOL>vert tdelta to integer seconds.<EOL>puttype == '<STR_LIT>':<EOL>emainder = int(tdelta.total_seconds())<EOL>inputtype in ['<STR_LIT:s>', '<STR_LIT>']:<EOL>emainder = int(tdelta)<EOL>inputtype in ['<STR_LIT:m>', '<STR_LIT>']:<EOL>emainder = int(tdelta) * <NUM_LIT><EOL>inputtype in ['<STR_LIT:h>', '<STR_LIT>']:<EOL>e...
Convert a ``datetime.timedelta`` object or a regular number to a custom- formatted string, just like the ``strftime()`` method does for ``datetime.datetime`` objects. The ``fmt`` argument allows custom formatting to be specified. Fields can include ``seconds``, ``minutes``, ``hours``, ``days``, and ``weeks``. Each fie...
f14683:m8
def get_tz_local() -> Timezone:
<EOL>return local_timezone()<EOL>
Returns the local timezone, in :class:`pendulum.Timezone`` format. (This is a subclass of :class:`datetime.tzinfo`.)
f14683:m9
def get_tz_utc() -> Timezone:
return pendulum.UTC<EOL>
Returns the UTC timezone.
f14683:m10
def get_now_localtz_pendulum() -> DateTime:
tz = get_tz_local()<EOL>return pendulum.now().in_tz(tz)<EOL>
Get the time now in the local timezone, as a :class:`pendulum.DateTime`.
f14683:m11
def get_now_utc_pendulum() -> DateTime:
tz = get_tz_utc()<EOL>return DateTime.utcnow().in_tz(tz)<EOL>
Get the time now in the UTC timezone, as a :class:`pendulum.DateTime`.
f14683:m12
def get_now_utc_datetime() -> datetime.datetime:
return datetime.datetime.now(pendulum.UTC)<EOL>
Get the time now in the UTC timezone, as a :class:`datetime.datetime`.
f14683:m13
def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime:
dt = coerce_to_pendulum(dt)<EOL>tz = get_tz_utc()<EOL>return dt.in_tz(tz)<EOL>
Convert date/time with timezone to UTC (with UTC timezone).
f14683:m14
def convert_datetime_to_local(dt: PotentialDatetimeType) -> DateTime:
dt = coerce_to_pendulum(dt)<EOL>tz = get_tz_local()<EOL>return dt.in_tz(tz)<EOL>
Convert date/time with timezone to local timezone.
f14683:m15
def get_duration_h_m(start: Union[str, DateTime],<EOL>end: Union[str, DateTime],<EOL>default: str = "<STR_LIT>") -> str:
start = coerce_to_pendulum(start)<EOL>end = coerce_to_pendulum(end)<EOL>if start is None or end is None:<EOL><INDENT>return default<EOL><DEDENT>duration = end - start<EOL>minutes = duration.in_minutes()<EOL>(hours, minutes) = divmod(minutes, <NUM_LIT>)<EOL>if hours < <NUM_LIT:0>:<EOL><INDENT>hours += <NUM_LIT:1><EOL>mi...
Calculate the time between two dates/times expressed as strings. Args: start: start date/time end: end date/time default: string value to return in case either of the inputs is ``None`` Returns: a string that is one of .. code-block: 'hh:mm' '-hh:mm' default
f14683:m16
def get_age(dob: PotentialDatetimeType,<EOL>when: PotentialDatetimeType,<EOL>default: str = "<STR_LIT>") -> Union[int, str]:
dob = coerce_to_pendulum_date(dob)<EOL>when = coerce_to_pendulum_date(when)<EOL>if dob is None or when is None:<EOL><INDENT>return default<EOL><DEDENT>return (when - dob).years<EOL>
Age (in whole years) at a particular date, or ``default``. Args: dob: date of birth when: date/time at which to calculate age default: value to return if either input is ``None`` Returns: age in whole years (rounded down), or ``default``
f14683:m17
def truncate_date_to_first_of_month(<EOL>dt: Optional[DateLikeType]) -> Optional[DateLikeType]:
if dt is None:<EOL><INDENT>return None<EOL><DEDENT>return dt.replace(day=<NUM_LIT:1>)<EOL>
Change the day to the first of the month.
f14683:m18
def get_now_utc_notz_datetime() -> datetime.datetime:
now = datetime.datetime.utcnow()<EOL>return now.replace(tzinfo=None)<EOL>
Get the UTC time now, but with no timezone information, in :class:`datetime.datetime` format.
f14683:m19
def coerce_to_datetime(x: Any) -> Optional[datetime.datetime]:
if x is None:<EOL><INDENT>return None<EOL><DEDENT>elif isinstance(x, DateTime):<EOL><INDENT>return pendulum_to_datetime(x)<EOL><DEDENT>elif isinstance(x, datetime.datetime):<EOL><INDENT>return x<EOL><DEDENT>elif isinstance(x, datetime.date):<EOL><INDENT>return datetime.datetime(x.year, x.month, x.day)<EOL><DEDENT>else:...
Ensure an object is a :class:`datetime.datetime`, or coerce to one, or raise :exc:`ValueError` or :exc:`OverflowError` (as per http://dateutil.readthedocs.org/en/latest/parser.html).
f14683:m20
def print_utf8(s: str) -> None:
sys.stdout.write(s.encode('<STR_LIT:utf-8>'))<EOL>
Writes a Unicode string to ``sys.stdout`` in UTF-8 encoding.
f14684:m0
def get_int_or_none(s: str) -> Optional[int]:
try:<EOL><INDENT>return int(s)<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>return None<EOL><DEDENT>
Returns the integer value of a string, or ``None`` if it's not convertible to an ``int``.
f14684:m1