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:<EOL><INDENT>if not gapdurations:<EOL><INDENT>return False, None<EOL><DEDENT>if gapdurations[<NUM_LIT:0>] < requiredgaps[<NUM_LIT:0>]:<EOL><INDENT>return False, self.first_interval_ending(gaplist[<NUM_LIT:0>].start)<EOL><DEDENT>gapdurations.pop(<NUM_LIT:0>)<EOL>requiredgaps.pop(<NUM_LIT:0>)<EOL>gaplist.pop(<NUM_LIT:0>)<EOL><DEDENT>return True, None<EOL> | 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><DEDENT>for i in range(ndays - every_n_days):<EOL><INDENT>j = i + every_n_days<EOL>a = startdate + datetime.timedelta(days=i)<EOL>b = startdate + datetime.timedelta(days=j)<EOL>sufficient, ffi = self._sufficient_gaps(a, b, requiredgaps,<EOL>flexibility)<EOL>if not sufficient:<EOL><INDENT>return False, ffi<EOL><DEDENT><DEDENT>return True, None<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 IntervalList?
- If ``flexibility == 0``: gaps must be WHOLLY WITHIN the interval.
- If ``flexibility == 1``: gaps may OVERLAP the edges of the interval.
- If ``flexibility == 2``: gaps may ABUT the edges of the interval.
Returns ``(True, None)`` or ``(False, first_failure_interval)``. | 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 - interval.start<EOL><DEDENT><DEDENT>return cumulative<EOL> | 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<EOL><DEDENT>if earliest_interval_start < start:<EOL><INDENT>before = no_time<EOL><DEDENT>else:<EOL><INDENT>before = earliest_interval_start - start<EOL><DEDENT>during = self.cumulative_time_to(when)<EOL>after = (<EOL>self.cumulative_gaps_to(when) +<EOL>self.time_afterwards_preceding(when)<EOL>)<EOL>return before, during, after<EOL> | 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 intervals represented by
``self``, and prior to ``when``.
Args:
start: the start time of interest (e.g. before ``self`` begins)
when: the time of interest
Returns:
tuple: ``before, during, after``
Illustration
.. code-block:: none
start: S
self: X---X X---X X---X X---X
when: W
before: ----
during: ----- ----- -----
after: ------- ------- ---- | 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>filenum += <NUM_LIT:1><EOL>if process_only_filenum and filenum != process_only_filenum:<EOL><INDENT>continue<EOL><DEDENT>log.info("<STR_LIT>", filenum, fullname)<EOL>proc = PythonProcessor(<EOL>full_path=fullname,<EOL>top_dir=top_dir,<EOL>correct_copyright_lines=correct_copyright_lines)<EOL>if show_only:<EOL><INDENT>proc.show()<EOL><DEDENT>elif rewrite:<EOL><INDENT>proc.rewrite_file()<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | 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 results (to stdout) only; don't rewrite
rewrite: write the changes
process_only_filenum: only process this file number (1-based index);
for debugging only | 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
symbols | 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("<STR_LIT>".format(linenum))<EOL><DEDENT>if CR in line_without_newline:<EOL><INDENT>self._warn("<STR_LIT>"<EOL>"<STR_LIT>".format(linenum))<EOL><DEDENT>self.source_lines.append(line_without_newline)<EOL><DEDENT><DEDENT> | 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("<STR_LIT>".format(linenum))<EOL>dl = dl.rstrip()<EOL><DEDENT>if not in_body:<EOL><INDENT>if linenum == <NUM_LIT:1>:<EOL><INDENT>if not dl.startswith(SHEBANG_START):<EOL><INDENT>self._warn("<STR_LIT>"<EOL>"<STR_LIT>".format(dl))<EOL>self._too_risky()<EOL>return<EOL><DEDENT>if dl != CORRECT_SHEBANG:<EOL><INDENT>self._debug("<STR_LIT>".format(dl))<EOL><DEDENT>dl = CORRECT_SHEBANG<EOL><DEDENT>if (linenum == <NUM_LIT:2> and dl.startswith(HASH_SPACE) and<EOL>dl.endswith(PYTHON_EXTENSION)):<EOL><INDENT>self._debug(<EOL>"<STR_LIT>".format(dl))<EOL>dl = None<EOL><DEDENT>elif TRIPLE_DOUBLEQUOTE in dl:<EOL><INDENT>if (not dl.startswith(TRIPLE_DOUBLEQUOTE) and<EOL>not dl.startswith(RAW_TRIPLE_DOUBLEQUOTE)):<EOL><INDENT>self._warn(<EOL>"<STR_LIT>")<EOL>self._debug_line(linenum, dl)<EOL>self._too_risky()<EOL>return<EOL><DEDENT>if in_docstring: <EOL><INDENT>in_docstring = False<EOL>docstring_done = True<EOL>in_body = True<EOL><DEDENT>elif not docstring_done: <EOL><INDENT>in_docstring = True<EOL>tdq = "<STR_LIT>" <EOL>if dl.startswith(TRIPLE_DOUBLEQUOTE):<EOL><INDENT>tdq = TRIPLE_DOUBLEQUOTE<EOL><DEDENT>elif dl.startswith(RAW_TRIPLE_DOUBLEQUOTE):<EOL><INDENT>tdq = RAW_TRIPLE_DOUBLEQUOTE<EOL><DEDENT>else:<EOL><INDENT>assert "<STR_LIT>"<EOL><DEDENT>self.dest_lines.append(tdq)<EOL>self.dest_lines.append(self.advertised_filename)<EOL>self.dest_lines.append(BLANK)<EOL>self.dest_lines.extend(self.correct_copyright_lines)<EOL>self.dest_lines.append(BLANK)<EOL>swallow_blanks_and_filename_in_docstring = True<EOL>if dl == tdq:<EOL><INDENT>dl = None <EOL><DEDENT>else:<EOL><INDENT>dl = dl[len(tdq):]<EOL><DEDENT><DEDENT><DEDENT>elif in_docstring:<EOL><INDENT>if dl == TRANSITION:<EOL><INDENT>if in_copyright: <EOL><INDENT>in_copyright = False<EOL>copyright_done = True<EOL>dl = None <EOL><DEDENT>elif not copyright_done:<EOL><INDENT>in_copyright = True<EOL>dl = None <EOL><DEDENT><DEDENT>elif in_copyright:<EOL><INDENT>dl = None <EOL><DEDENT>elif dl == RST_COMMENT_LINE:<EOL><INDENT>dl = None <EOL><DEDENT>elif swallow_blanks_and_filename_in_docstring:<EOL><INDENT>if dl == BLANK or dl == self.advertised_filename:<EOL><INDENT>dl = None<EOL><DEDENT>elif copyright_done:<EOL><INDENT>swallow_blanks_and_filename_in_docstring = False<EOL><DEDENT><DEDENT><DEDENT>elif not dl.startswith(HASH) and not dl == BLANK:<EOL><INDENT>in_body = True<EOL>if not docstring_done:<EOL><INDENT>new_docstring_lines = [<EOL>BLANK,<EOL>TRIPLE_DOUBLEQUOTE,<EOL>self.advertised_filename,<EOL>BLANK,<EOL>] + self.correct_copyright_lines + [<EOL>BLANK,<EOL>MISSING_RST_TITLE,<EOL>BLANK,<EOL>TRIPLE_DOUBLEQUOTE<EOL>]<EOL>self._warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(MISSING_RST_TITLE))<EOL>self.dest_lines[<NUM_LIT:1>:<NUM_LIT:1>] = new_docstring_lines<EOL><DEDENT><DEDENT><DEDENT>if dl is not None:<EOL><INDENT>self.dest_lines.append(dl)<EOL><DEDENT><DEDENT>self.needs_rewriting = self.dest_lines != self.source_lines<EOL> | 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-complement-in-python | 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>) |((data[i + <NUM_LIT:2>] & <NUM_LIT>) << <NUM_LIT:16>) | (data[i + <NUM_LIT:3>] << <NUM_LIT>)<EOL><NUM_LIT:1> *= c1<EOL><NUM_LIT:1> = (k1 << <NUM_LIT:15>) | ((k1 & <NUM_LIT>) >> <NUM_LIT>) <EOL><NUM_LIT:1> *= c2<EOL><NUM_LIT:1> ^= k1<EOL><NUM_LIT:1> = (h1 << <NUM_LIT>) | ((h1 & <NUM_LIT>) >> <NUM_LIT>) <EOL><NUM_LIT:1> = h1 * <NUM_LIT:5> + <NUM_LIT><EOL>l<EOL><NUM_LIT:0><EOL><INDENT>length & <NUM_LIT><EOL><DEDENT>l == <NUM_LIT:3>:<EOL><NUM_LIT:1> = (data[rounded_end + <NUM_LIT:2>] & <NUM_LIT>) << <NUM_LIT:16><EOL>lthrough<EOL>l in (<NUM_LIT:2>, <NUM_LIT:3>):<EOL><NUM_LIT:1> |= (data[rounded_end + <NUM_LIT:1>] & <NUM_LIT>) << <NUM_LIT:8><EOL>lthrough<EOL>l in (<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>):<EOL><NUM_LIT:1> |= data[rounded_end] & <NUM_LIT><EOL><NUM_LIT:1> *= c1<EOL><NUM_LIT:1> = (k1 << <NUM_LIT:15>) | ((k1 & <NUM_LIT>) >> <NUM_LIT>) <EOL><NUM_LIT:1> *= c2<EOL><NUM_LIT:1> ^= k1<EOL>alization<EOL><INDENT>length<EOL><DEDENT>x(h1)<EOL><INDENT>((h1 & <NUM_LIT>) >> <NUM_LIT:16>)<EOL><NUM_LIT><EOL>((h1 & <NUM_LIT>) >> <NUM_LIT>)<EOL><NUM_LIT><EOL>((h1 & <NUM_LIT>) >> <NUM_LIT:16>)<EOL><DEDENT>n h1 & <NUM_LIT><EOL> | 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>):<EOL><INDENT>= bytes_to_long(data[ll:ll + <NUM_LIT:8>])<EOL>= (k * m) & mask<EOL>^= (k >> r) & mask<EOL>= (k * m) & mask<EOL>= (h ^ k)<EOL>= (h * m) & mask<EOL><DEDENT>ength & <NUM_LIT:7><EOL>>= <NUM_LIT:7>:<EOL><INDENT>= (h ^ (data[offset + <NUM_LIT:6>] << <NUM_LIT>))<EOL><DEDENT>>= <NUM_LIT:6>:<EOL><INDENT>= (h ^ (data[offset + <NUM_LIT:5>] << <NUM_LIT>))<EOL><DEDENT>>= <NUM_LIT:5>:<EOL><INDENT>= (h ^ (data[offset + <NUM_LIT:4>] << <NUM_LIT:32>))<EOL><DEDENT>>= <NUM_LIT:4>:<EOL><INDENT>= (h ^ (data[offset + <NUM_LIT:3>] << <NUM_LIT>))<EOL><DEDENT>>= <NUM_LIT:3>:<EOL><INDENT>= (h ^ (data[offset + <NUM_LIT:2>] << <NUM_LIT:16>))<EOL><DEDENT>>= <NUM_LIT:2>:<EOL><INDENT>= (h ^ (data[offset + <NUM_LIT:1>] << <NUM_LIT:8>))<EOL><DEDENT>>= <NUM_LIT:1>:<EOL><INDENT>= (h ^ data[offset])<EOL>= (h * m) & mask<EOL><DEDENT>(h >> r) & mask<EOL>h * m) & mask<EOL>(h >> r) & mask<EOL>n h<EOL> | 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>for block_start in range(<NUM_LIT:0>, nblocks * <NUM_LIT:8>, <NUM_LIT:8>):<EOL><INDENT>k1 = (<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:7>] << <NUM_LIT> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:6>] << <NUM_LIT> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:5>] << <NUM_LIT> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:4>] << <NUM_LIT:32> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:3>] << <NUM_LIT> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:2>] << <NUM_LIT:16> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:1>] << <NUM_LIT:8> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:0>]<EOL>)<EOL>k2 = (<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:15>] << <NUM_LIT> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT>] << <NUM_LIT> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT>] << <NUM_LIT> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:12>] << <NUM_LIT:32> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:11>] << <NUM_LIT> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:10>] << <NUM_LIT:16> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:9>] << <NUM_LIT:8> |<EOL>key[<NUM_LIT:2> * block_start + <NUM_LIT:8>]<EOL>)<EOL>k1 = (c1 * k1) & <NUM_LIT><EOL>k1 = (k1 << <NUM_LIT> | k1 >> <NUM_LIT>) & <NUM_LIT> <EOL>k1 = (c2 * k1) & <NUM_LIT><EOL>h1 ^= k1<EOL>h1 = (h1 << <NUM_LIT> | h1 >> <NUM_LIT>) & <NUM_LIT> <EOL>h1 = (h1 + h2) & <NUM_LIT><EOL>h1 = (h1 * <NUM_LIT:5> + <NUM_LIT>) & <NUM_LIT><EOL>k2 = (c2 * k2) & <NUM_LIT><EOL>k2 = (k2 << <NUM_LIT> | k2 >> <NUM_LIT>) & <NUM_LIT> <EOL>k2 = (c1 * k2) & <NUM_LIT><EOL>h2 ^= k2<EOL>h2 = (h2 << <NUM_LIT> | h2 >> <NUM_LIT>) & <NUM_LIT> <EOL>h2 = (h1 + h2) & <NUM_LIT><EOL>h2 = (h2 * <NUM_LIT:5> + <NUM_LIT>) & <NUM_LIT><EOL><DEDENT>tail_index = nblocks * <NUM_LIT:16><EOL>k1 = <NUM_LIT:0><EOL>k2 = <NUM_LIT:0><EOL>tail_size = length & <NUM_LIT:15><EOL>if tail_size >= <NUM_LIT:15>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:12>] << <NUM_LIT:32><EOL><DEDENT>if tail_size >= <NUM_LIT:12>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:11>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT:11>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:10>] << <NUM_LIT:16><EOL><DEDENT>if tail_size >= <NUM_LIT:10>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:9>] << <NUM_LIT:8><EOL><DEDENT>if tail_size >= <NUM_LIT:9>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:8>]<EOL><DEDENT>if tail_size > <NUM_LIT:8>:<EOL><INDENT>k2 = (k2 * c2) & <NUM_LIT><EOL>k2 = (k2 << <NUM_LIT> | k2 >> <NUM_LIT>) & <NUM_LIT> <EOL>k2 = (k2 * c1) & <NUM_LIT><EOL>h2 ^= k2<EOL><DEDENT>if tail_size >= <NUM_LIT:8>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:7>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT:7>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:6>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT:6>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:5>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT:5>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:4>] << <NUM_LIT:32><EOL><DEDENT>if tail_size >= <NUM_LIT:4>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:3>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT:3>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:2>] << <NUM_LIT:16><EOL><DEDENT>if tail_size >= <NUM_LIT:2>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:1>] << <NUM_LIT:8><EOL><DEDENT>if tail_size >= <NUM_LIT:1>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:0>]<EOL><DEDENT>if tail_size > <NUM_LIT:0>:<EOL><INDENT>k1 = (k1 * c1) & <NUM_LIT><EOL>k1 = (k1 << <NUM_LIT> | k1 >> <NUM_LIT>) & <NUM_LIT> <EOL>k1 = (k1 * c2) & <NUM_LIT><EOL>h1 ^= k1<EOL><DEDENT>h1 ^= length<EOL>h2 ^= length<EOL>h1 = (h1 + h2) & <NUM_LIT><EOL>h2 = (h1 + h2) & <NUM_LIT><EOL>h1 = fmix(h1)<EOL>h2 = fmix(h2)<EOL>h1 = (h1 + h2) & <NUM_LIT><EOL>h2 = (h1 + h2) & <NUM_LIT><EOL>return h2 << <NUM_LIT:64> | h1<EOL> | 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 = <NUM_LIT><EOL>c2 = <NUM_LIT><EOL>c3 = <NUM_LIT><EOL>c4 = <NUM_LIT><EOL>for block_start in range(<NUM_LIT:0>, nblocks * <NUM_LIT:16>, <NUM_LIT:16>):<EOL><INDENT>k1 = (<EOL>key[block_start + <NUM_LIT:3>] << <NUM_LIT> |<EOL>key[block_start + <NUM_LIT:2>] << <NUM_LIT:16> |<EOL>key[block_start + <NUM_LIT:1>] << <NUM_LIT:8> |<EOL>key[block_start + <NUM_LIT:0>]<EOL>)<EOL>k2 = (<EOL>key[block_start + <NUM_LIT:7>] << <NUM_LIT> |<EOL>key[block_start + <NUM_LIT:6>] << <NUM_LIT:16> |<EOL>key[block_start + <NUM_LIT:5>] << <NUM_LIT:8> |<EOL>key[block_start + <NUM_LIT:4>]<EOL>)<EOL>k3 = (<EOL>key[block_start + <NUM_LIT:11>] << <NUM_LIT> |<EOL>key[block_start + <NUM_LIT:10>] << <NUM_LIT:16> |<EOL>key[block_start + <NUM_LIT:9>] << <NUM_LIT:8> |<EOL>key[block_start + <NUM_LIT:8>]<EOL>)<EOL>k4 = (<EOL>key[block_start + <NUM_LIT:15>] << <NUM_LIT> |<EOL>key[block_start + <NUM_LIT>] << <NUM_LIT:16> |<EOL>key[block_start + <NUM_LIT>] << <NUM_LIT:8> |<EOL>key[block_start + <NUM_LIT:12>]<EOL>)<EOL>k1 = (c1 * k1) & <NUM_LIT><EOL>k1 = (k1 << <NUM_LIT:15> | k1 >> <NUM_LIT>) & <NUM_LIT> <EOL>k1 = (c2 * k1) & <NUM_LIT><EOL>h1 ^= k1<EOL>h1 = (h1 << <NUM_LIT> | h1 >> <NUM_LIT>) & <NUM_LIT> <EOL>h1 = (h1 + h2) & <NUM_LIT><EOL>h1 = (h1 * <NUM_LIT:5> + <NUM_LIT>) & <NUM_LIT><EOL>k2 = (c2 * k2) & <NUM_LIT><EOL>k2 = (k2 << <NUM_LIT:16> | k2 >> <NUM_LIT:16>) & <NUM_LIT> <EOL>k2 = (c3 * k2) & <NUM_LIT><EOL>h2 ^= k2<EOL>h2 = (h2 << <NUM_LIT> | h2 >> <NUM_LIT:15>) & <NUM_LIT> <EOL>h2 = (h2 + h3) & <NUM_LIT><EOL>h2 = (h2 * <NUM_LIT:5> + <NUM_LIT>) & <NUM_LIT><EOL>k3 = (c3 * k3) & <NUM_LIT><EOL>k3 = (k3 << <NUM_LIT> | k3 >> <NUM_LIT:15>) & <NUM_LIT> <EOL>k3 = (c4 * k3) & <NUM_LIT><EOL>h3 ^= k3<EOL>h3 = (h3 << <NUM_LIT:15> | h3 >> <NUM_LIT>) & <NUM_LIT> <EOL>h3 = (h3 + h4) & <NUM_LIT><EOL>h3 = (h3 * <NUM_LIT:5> + <NUM_LIT>) & <NUM_LIT><EOL>k4 = (c4 * k4) & <NUM_LIT><EOL>k4 = (k4 << <NUM_LIT> | k4 >> <NUM_LIT>) & <NUM_LIT> <EOL>k4 = (c1 * k4) & <NUM_LIT><EOL>h4 ^= k4<EOL>h4 = (h4 << <NUM_LIT> | h4 >> <NUM_LIT>) & <NUM_LIT> <EOL>h4 = (h1 + h4) & <NUM_LIT><EOL>h4 = (h4 * <NUM_LIT:5> + <NUM_LIT>) & <NUM_LIT><EOL><DEDENT>tail_index = nblocks * <NUM_LIT:16><EOL>k1 = <NUM_LIT:0><EOL>k2 = <NUM_LIT:0><EOL>k3 = <NUM_LIT:0><EOL>k4 = <NUM_LIT:0><EOL>tail_size = length & <NUM_LIT:15><EOL>if tail_size >= <NUM_LIT:15>:<EOL><INDENT>k4 ^= key[tail_index + <NUM_LIT>] << <NUM_LIT:16><EOL><DEDENT>if tail_size >= <NUM_LIT>:<EOL><INDENT>k4 ^= key[tail_index + <NUM_LIT>] << <NUM_LIT:8><EOL><DEDENT>if tail_size >= <NUM_LIT>:<EOL><INDENT>k4 ^= key[tail_index + <NUM_LIT:12>]<EOL><DEDENT>if tail_size > <NUM_LIT:12>:<EOL><INDENT>k4 = (k4 * c4) & <NUM_LIT><EOL>k4 = (k4 << <NUM_LIT> | k4 >> <NUM_LIT>) & <NUM_LIT> <EOL>k4 = (k4 * c1) & <NUM_LIT><EOL>h4 ^= k4<EOL><DEDENT>if tail_size >= <NUM_LIT:12>:<EOL><INDENT>k3 ^= key[tail_index + <NUM_LIT:11>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT:11>:<EOL><INDENT>k3 ^= key[tail_index + <NUM_LIT:10>] << <NUM_LIT:16><EOL><DEDENT>if tail_size >= <NUM_LIT:10>:<EOL><INDENT>k3 ^= key[tail_index + <NUM_LIT:9>] << <NUM_LIT:8><EOL><DEDENT>if tail_size >= <NUM_LIT:9>:<EOL><INDENT>k3 ^= key[tail_index + <NUM_LIT:8>]<EOL><DEDENT>if tail_size > <NUM_LIT:8>:<EOL><INDENT>k3 = (k3 * c3) & <NUM_LIT><EOL>k3 = (k3 << <NUM_LIT> | k3 >> <NUM_LIT:15>) & <NUM_LIT> <EOL>k3 = (k3 * c4) & <NUM_LIT><EOL>h3 ^= k3<EOL><DEDENT>if tail_size >= <NUM_LIT:8>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:7>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT:7>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:6>] << <NUM_LIT:16><EOL><DEDENT>if tail_size >= <NUM_LIT:6>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:5>] << <NUM_LIT:8><EOL><DEDENT>if tail_size >= <NUM_LIT:5>:<EOL><INDENT>k2 ^= key[tail_index + <NUM_LIT:4>]<EOL><DEDENT>if tail_size > <NUM_LIT:4>:<EOL><INDENT>k2 = (k2 * c2) & <NUM_LIT><EOL>k2 = (k2 << <NUM_LIT:16> | k2 >> <NUM_LIT:16>) & <NUM_LIT> <EOL>k2 = (k2 * c3) & <NUM_LIT><EOL>h2 ^= k2<EOL><DEDENT>if tail_size >= <NUM_LIT:4>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:3>] << <NUM_LIT><EOL><DEDENT>if tail_size >= <NUM_LIT:3>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:2>] << <NUM_LIT:16><EOL><DEDENT>if tail_size >= <NUM_LIT:2>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:1>] << <NUM_LIT:8><EOL><DEDENT>if tail_size >= <NUM_LIT:1>:<EOL><INDENT>k1 ^= key[tail_index + <NUM_LIT:0>]<EOL><DEDENT>if tail_size > <NUM_LIT:0>:<EOL><INDENT>k1 = (k1 * c1) & <NUM_LIT><EOL>k1 = (k1 << <NUM_LIT:15> | k1 >> <NUM_LIT>) & <NUM_LIT> <EOL>k1 = (k1 * c2) & <NUM_LIT><EOL>h1 ^= k1<EOL><DEDENT>h1 ^= length<EOL>h2 ^= length<EOL>h3 ^= length<EOL>h4 ^= length<EOL>h1 = (h1 + h2) & <NUM_LIT><EOL>h1 = (h1 + h3) & <NUM_LIT><EOL>h1 = (h1 + h4) & <NUM_LIT><EOL>h2 = (h1 + h2) & <NUM_LIT><EOL>h3 = (h1 + h3) & <NUM_LIT><EOL>h4 = (h1 + h4) & <NUM_LIT><EOL>h1 = fmix(h1)<EOL>h2 = fmix(h2)<EOL>h3 = fmix(h3)<EOL>h4 = fmix(h4)<EOL>h1 = (h1 + h2) & <NUM_LIT><EOL>h1 = (h1 + h3) & <NUM_LIT><EOL>h1 = (h1 + h4) & <NUM_LIT><EOL>h2 = (h1 + h2) & <NUM_LIT><EOL>h3 = (h1 + h3) & <NUM_LIT><EOL>h4 = (h1 + h4) & <NUM_LIT><EOL>return h4 << <NUM_LIT> | h3 << <NUM_LIT:64> | h2 << <NUM_LIT:32> | h1<EOL> | 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>) & <NUM_LIT> <EOL>if unsigned_val2 & <NUM_LIT> == <NUM_LIT:0>:<EOL><INDENT>signed_val2 = unsigned_val2<EOL><DEDENT>else:<EOL><INDENT>signed_val2 = -((unsigned_val2 ^ <NUM_LIT>) + <NUM_LIT:1>)<EOL><DEDENT>return signed_val1, signed_val2<EOL> | 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)<EOL>if c_signed == py_signed:<EOL><INDENT>print(preamble + "<STR_LIT>".format(result=c_signed))<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(<EOL>preamble + "<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>c_data=repr(c_data),<EOL>c_signed=c_signed,<EOL>py_data=repr(py_data),<EOL>py_unsigned=py_unsigned,<EOL>py_signed=py_signed))<EOL><DEDENT> | 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 c_signed_low == py_signed_low and c_signed_high == py_signed_high:<EOL><INDENT>print(preamble + "<STR_LIT>".format(<EOL>low=c_signed_low, high=c_signed_high))<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(<EOL>preamble +<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>c_data=repr(c_data),<EOL>c_low=c_signed_low,<EOL>c_high=c_signed_high,<EOL>py_data=repr(py_data),<EOL>py_low=py_signed_low,<EOL>py_high=py_signed_high))<EOL><DEDENT> | 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 are absent from ``d1`` and present in ``d2``,
or present in both but with different values (in which case the ``d2``
value is shown). If a key ``k`` is present in ``d1`` but absent in
``d2``, the result dictionary has the entry ``{k: deleted_value}``. | 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 tsv<EOL> | 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 = key.lower()<EOL><DEDENT>d[key] = value<EOL><DEDENT>return d<EOL> | 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 be forced to lower case? | 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 and not xhtml2pdf:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if processor == Processors.PDFKIT and not pdfkit:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT> | 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 = False,<EOL>debug_content: bool = False,<EOL>debug_wkhtmltopdf_args: bool = True,<EOL>fix_pdfkit_encoding_bug: bool = None,<EOL>processor: str = _DEFAULT_PROCESSOR) -> Union[bytes, bool]: | 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 = get_default_fix_pdfkit_encoding_bug()<EOL><DEDENT>if processor == Processors.XHTML2PDF:<EOL><INDENT>if on_disk:<EOL><INDENT>with open(output_path, mode='<STR_LIT:wb>') as outfile:<EOL><INDENT>xhtml2pdf.document.pisaDocument(html, outfile)<EOL><DEDENT>return True<EOL><DEDENT>else:<EOL><INDENT>memfile = io.BytesIO()<EOL>xhtml2pdf.document.pisaDocument(html, memfile)<EOL>memfile.seek(<NUM_LIT:0>)<EOL>return memfile.read()<EOL><DEDENT><DEDENT>elif processor == Processors.WEASYPRINT:<EOL><INDENT>if on_disk:<EOL><INDENT>return weasyprint.HTML(string=html).write_pdf(output_path)<EOL><DEDENT>else:<EOL><INDENT>return weasyprint.HTML(string=html).write_pdf()<EOL><DEDENT><DEDENT>elif processor == Processors.PDFKIT:<EOL><INDENT>if not wkhtmltopdf_filename:<EOL><INDENT>config = None<EOL><DEDENT>else:<EOL><INDENT>if fix_pdfkit_encoding_bug: <EOL><INDENT>log.debug("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>config = pdfkit.configuration(<EOL>wkhtmltopdf=wkhtmltopdf_filename.encode('<STR_LIT:utf-8>'))<EOL><DEDENT>else:<EOL><INDENT>config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_filename)<EOL><DEDENT><DEDENT>h_filename = None<EOL>f_filename = None<EOL>try:<EOL><INDENT>if header_html:<EOL><INDENT>h_fd, h_filename = tempfile.mkstemp(suffix='<STR_LIT>')<EOL>os.write(h_fd, header_html.encode(file_encoding))<EOL>os.close(h_fd)<EOL>wkhtmltopdf_options["<STR_LIT>"] = h_filename<EOL><DEDENT>if footer_html:<EOL><INDENT>f_fd, f_filename = tempfile.mkstemp(suffix='<STR_LIT>')<EOL>os.write(f_fd, footer_html.encode(file_encoding))<EOL>os.close(f_fd)<EOL>wkhtmltopdf_options["<STR_LIT>"] = f_filename<EOL><DEDENT>if debug_options:<EOL><INDENT>log.debug("<STR_LIT>", config)<EOL>log.debug("<STR_LIT>",<EOL>pformat(wkhtmltopdf_options))<EOL><DEDENT>kit = pdfkit.pdfkit.PDFKit(html, '<STR_LIT:string>', configuration=config,<EOL>options=wkhtmltopdf_options)<EOL>if on_disk:<EOL><INDENT>path = output_path<EOL><DEDENT>else:<EOL><INDENT>path = None<EOL><DEDENT>if debug_wkhtmltopdf_args:<EOL><INDENT>log.debug("<STR_LIT>", getpass.getuser())<EOL>log.debug("<STR_LIT>",<EOL>kit.command(path=path))<EOL><DEDENT>return kit.to_pdf(path=path)<EOL><DEDENT>finally:<EOL><INDENT>if h_filename:<EOL><INDENT>os.remove(h_filename)<EOL><DEDENT>if f_filename:<EOL><INDENT>os.remove(f_filename)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | 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
appropriate HTML content to serve as the header/footer (rather than
passing it within the main HTML).
Args:
on_disk: make file on disk (rather than returning it in memory)?
html: main HTML
output_path: if ``on_disk``, the output filename
header_html: optional page header, as HTML
footer_html: optional page footer, as HTML
wkhtmltopdf_filename: filename of the ``wkhtmltopdf`` executable
wkhtmltopdf_options: options for ``wkhtmltopdf``
file_encoding: encoding to use when writing the header/footer to disk
debug_options: log ``wkhtmltopdf`` config/options passed to ``pdfkit``?
debug_content: log the main/header/footer HTML?
debug_wkhtmltopdf_args: log the final command-line arguments to
that will be used by ``pdfkit`` when it calls ``wkhtmltopdf``?
fix_pdfkit_encoding_bug: attempt to work around bug in e.g.
``pdfkit==0.5.0`` by encoding ``wkhtmltopdf_filename`` to UTF-8
before passing it to ``pdfkit``? If you pass ``None`` here, then
a default value is used, from
:func:`get_default_fix_pdfkit_encoding_bug`.
processor: a PDF processor type from :class:`Processors`
Returns:
the PDF binary as a ``bytes`` object
Raises:
AssertionError: if bad ``processor``
RuntimeError: if requested processor is unavailable | 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_wkhtmltopdf_args: bool = True,<EOL>fix_pdfkit_encoding_bug: bool = None,<EOL>processor: str = _DEFAULT_PROCESSOR) -> bytes: | 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>debug_wkhtmltopdf_args=debug_wkhtmltopdf_args,<EOL>fix_pdfkit_encoding_bug=fix_pdfkit_encoding_bug,<EOL>processor=processor,<EOL>) <EOL>return result<EOL> | 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_encoding_bug: bool = True,<EOL>processor: str = _DEFAULT_PROCESSOR) -> bytes: | 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_pdfkit_encoding_bug,<EOL>processor=processor)<EOL> | 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_content: bool = False,<EOL>debug_wkhtmltopdf_args: bool = True,<EOL>fix_pdfkit_encoding_bug: bool = None,<EOL>processor: str = _DEFAULT_PROCESSOR) -> bool: | 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_content=debug_content,<EOL>debug_wkhtmltopdf_args=debug_wkhtmltopdf_args,<EOL>fix_pdfkit_encoding_bug=fix_pdfkit_encoding_bug,<EOL>processor=processor,<EOL>) <EOL>return result<EOL> | 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/2374427 | 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(page_num))<EOL><DEDENT> | 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><DEDENT>return pdf_from_writer(writer)<EOL><DEDENT>else:<EOL><INDENT>merger = PdfFileMerger()<EOL>for filename in filenames:<EOL><INDENT>if filename:<EOL><INDENT>merger.append(open(filename, '<STR_LIT:rb>'))<EOL><DEDENT><DEDENT>return pdf_from_writer(merger)<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 = filename<EOL> | 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 ``wkhtmltopdf``
is_filename: use file mode?
filename: for file mode, the filename of the existing PDF on disk
Use either ``is_html`` or ``is_filename``, not both. | 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><DEDENT>elif self.is_filename:<EOL><INDENT>if start_recto and writer.getNumPages() % <NUM_LIT:2> != <NUM_LIT:0>:<EOL><INDENT>writer.addBlankPage()<EOL><DEDENT>writer.appendPagesFromReader(PdfFileReader(<EOL>open(self.filename, '<STR_LIT:rb>')))<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | 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() implements "banker's rounding", which is never what
we want:
- https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python # noqa | 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 = DateTime.min.time()<EOL>dt = DateTime.combine(x, midnight)<EOL>return pendulum.instance(dt, tz=tz) <EOL><DEDENT>elif isinstance(x, str):<EOL><INDENT>return pendulum.parse(x, tz=tz) <EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(x))<EOL><DEDENT> | 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 string fails to parse
ValueError: if no conversion possible | 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 parse
ValueError: if no conversion possible | 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") # 9am in Moscow
in_london = pendulum.UTC.convert(in_moscow) # 6am in UTC
dt_utc_from_moscow = pendulum_to_utc_datetime_without_tz(in_moscow) # 6am, no timezone info
dt_utc_from_london = pendulum_to_utc_datetime_without_tz(in_london) # 6am, no timezone info | 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>emainder = int(tdelta) * <NUM_LIT><EOL>inputtype in ['<STR_LIT:d>', '<STR_LIT>']:<EOL>emainder = int(tdelta) * <NUM_LIT><EOL>inputtype in ['<STR_LIT:w>', '<STR_LIT>']:<EOL>emainder = int(tdelta) * <NUM_LIT><EOL>aise ValueError("<STR_LIT>".format(inputtype))<EOL>ormatter()<EOL>ed_fields = [field_tuple[<NUM_LIT:1>] for field_tuple in f.parse(fmt)]<EOL>ble_fields = ('<STR_LIT>', '<STR_LIT:D>', '<STR_LIT:H>', '<STR_LIT:M>', '<STR_LIT:S>')<EOL>ants = {'<STR_LIT>': <NUM_LIT>, '<STR_LIT:D>': <NUM_LIT>, '<STR_LIT:H>': <NUM_LIT>, '<STR_LIT:M>': <NUM_LIT>, '<STR_LIT:S>': <NUM_LIT:1>}<EOL>s = {}<EOL>ield in possible_fields:<EOL>f field in desired_fields and field in constants:<EOL><INDENT>values[field], remainder = divmod(remainder, constants[field])<EOL><DEDENT>n f.format(fmt, **values)<EOL> | 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
field is optional.
Some examples:
.. code-block:: none
'{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02}' --> ' 5d 8:04:02'
'{H}h {S}s' --> '72h 800s'
The ``inputtype`` argument allows ``tdelta`` to be a regular number,
instead of the default behaviour of treating it as a ``datetime.timedelta``
object. Valid ``inputtype`` strings:
.. code-block:: none
'timedelta', # treats input as a datetime.timedelta
's', 'seconds',
'm', 'minutes',
'h', 'hours',
'd', 'days',
'w', 'weeks'
Modified from
https://stackoverflow.com/questions/538666/python-format-timedelta-to-string | 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>minutes = <NUM_LIT> - minutes<EOL>return "<STR_LIT>".format(hours, "<STR_LIT>" if minutes == <NUM_LIT:0> else minutes)<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>".format(hours, "<STR_LIT>" if minutes == <NUM_LIT:0> else minutes)<EOL><DEDENT> | 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:<EOL><INDENT>return dateutil.parser.parse(x)<EOL><DEDENT> | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.