def create_pax_header(self, info, encoding):

info["<STR_LIT>"] = POSIX_MAGIC<EOL>pax_headers = self.pax_headers.copy()<EOL>for name, hname, length in (<EOL>("<STR_LIT:name>", "<STR_LIT:path>", LENGTH_NAME), ("<STR_LIT>", "<STR_LIT>", LENGTH_LINK),<EOL>("<STR_LIT>", "<STR_LIT>", <NUM_LIT:32>), ("<STR_LIT>", "<STR_LIT>", <NUM_LIT:32>)):<EOL><INDENT>if hname in pax_headers:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>info[name].encode("<STR_LIT:ascii>", "<STR_LIT:strict>")<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>pax_headers[hname] = info[name]<EOL>continue<EOL><DEDENT>if len(info[name]) > length:<EOL><INDENT>pax_headers[hname] = info[name]<EOL><DEDENT><DEDENT>for name, digits in (("<STR_LIT>", <NUM_LIT:8>), ("<STR_LIT>", <NUM_LIT:8>), ("<STR_LIT:size>", <NUM_LIT:12>), ("<STR_LIT>", <NUM_LIT:12>)):<EOL><INDENT>if name in pax_headers:<EOL><INDENT>info[name] = <NUM_LIT:0><EOL>continue<EOL><DEDENT>val = info[name]<EOL>if not <NUM_LIT:0> <= val < <NUM_LIT:8> ** (digits - <NUM_LIT:1>) or isinstance(val, float):<EOL><INDENT>pax_headers[name] = str(val)<EOL>info[name] = <NUM_LIT:0><EOL><DEDENT><DEDENT>if pax_headers:<EOL><INDENT>buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding)<EOL><DEDENT>else:<EOL><INDENT>buf = b"<STR_LIT>"<EOL><DEDENT>return buf + self._create_header(info, USTAR_FORMAT, "<STR_LIT:ascii>", "<STR_LIT:replace>")<EOL>

Return the object as a ustar header block. If it cannot be
           represented this way, prepend a pax extended header sequence
           with supplement information.


return cls._create_pax_generic_header(pax_headers, XGLTYPE, "<STR_LIT:utf8>")<EOL>

Return the object as a pax global header block sequence.


prefix = name[:LENGTH_PREFIX + <NUM_LIT:1>]<EOL>while prefix and prefix[-<NUM_LIT:1>] != "<STR_LIT:/>":<EOL><INDENT>prefix = prefix[:-<NUM_LIT:1>]<EOL><DEDENT>name = name[len(prefix):]<EOL>prefix = prefix[:-<NUM_LIT:1>]<EOL>if not prefix or len(name) > LENGTH_NAME:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return prefix, name<EOL>

Split a name longer than 100 chars into a prefix
           and a name part.


@staticmethod<EOL><INDENT>def _create_header(info, format, encoding, errors):<DEDENT>

parts = [<EOL>stn(info.get("<STR_LIT:name>", "<STR_LIT>"), <NUM_LIT:100>, encoding, errors),<EOL>itn(info.get("<STR_LIT>", <NUM_LIT:0>) & <NUM_LIT>, <NUM_LIT:8>, format),<EOL>itn(info.get("<STR_LIT>", <NUM_LIT:0>), <NUM_LIT:8>, format),<EOL>itn(info.get("<STR_LIT>", <NUM_LIT:0>), <NUM_LIT:8>, format),<EOL>itn(info.get("<STR_LIT:size>", <NUM_LIT:0>), <NUM_LIT:12>, format),<EOL>itn(info.get("<STR_LIT>", <NUM_LIT:0>), <NUM_LIT:12>, format),<EOL>b"<STR_LIT:U+0020>", <EOL>info.get("<STR_LIT:type>", REGTYPE),<EOL>stn(info.get("<STR_LIT>", "<STR_LIT>"), <NUM_LIT:100>, encoding, errors),<EOL>info.get("<STR_LIT>", POSIX_MAGIC),<EOL>stn(info.get("<STR_LIT>", "<STR_LIT>"), <NUM_LIT:32>, encoding, errors),<EOL>stn(info.get("<STR_LIT>", "<STR_LIT>"), <NUM_LIT:32>, encoding, errors),<EOL>itn(info.get("<STR_LIT>", <NUM_LIT:0>), <NUM_LIT:8>, format),<EOL>itn(info.get("<STR_LIT>", <NUM_LIT:0>), <NUM_LIT:8>, format),<EOL>stn(info.get("<STR_LIT>", "<STR_LIT>"), <NUM_LIT>, encoding, errors)<EOL>]<EOL>buf = struct.pack("<STR_LIT>" % BLOCKSIZE, b"<STR_LIT>".join(parts))<EOL>chksum = calc_chksums(buf[-BLOCKSIZE:])[<NUM_LIT:0>]<EOL>buf = buf[:-<NUM_LIT>] + ("<STR_LIT>" % chksum).encode("<STR_LIT:ascii>") + buf[-<NUM_LIT>:]<EOL>return buf<EOL>

Return a header block. info is a dictionary with file
           information, format must be one of the *_FORMAT constants.


blocks, remainder = divmod(len(payload), BLOCKSIZE)<EOL>if remainder > <NUM_LIT:0>:<EOL><INDENT>payload += (BLOCKSIZE - remainder) * NUL<EOL><DEDENT>return payload<EOL>

Return the string payload filled with zero bytes
           up to the next 512 byte border.


@classmethod<EOL><INDENT>def _create_gnu_long_header(cls, name, type, encoding, errors):<DEDENT>

name = name.encode(encoding, errors) + NUL<EOL>info = {}<EOL>info["<STR_LIT:name>"] = "<STR_LIT>"<EOL>info["<STR_LIT:type>"] = type<EOL>info["<STR_LIT:size>"] = len(name)<EOL>info["<STR_LIT>"] = GNU_MAGIC<EOL>return cls._create_header(info, USTAR_FORMAT, encoding, errors) +cls._create_payload(name)<EOL>

Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
           for name.


@classmethod<EOL><INDENT>def _create_pax_generic_header(cls, pax_headers, type, encoding):<DEDENT>

<EOL>binary = False<EOL>for keyword, value in pax_headers.items():<EOL><INDENT>try:<EOL><INDENT>value.encode("<STR_LIT:utf8>", "<STR_LIT:strict>")<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>binary = True<EOL>break<EOL><DEDENT><DEDENT>records = b"<STR_LIT>"<EOL>if binary:<EOL><INDENT>records += b"<STR_LIT>"<EOL><DEDENT>for keyword, value in pax_headers.items():<EOL><INDENT>keyword = keyword.encode("<STR_LIT:utf8>")<EOL>if binary:<EOL><INDENT>value = value.encode(encoding, "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>value = value.encode("<STR_LIT:utf8>")<EOL><DEDENT>l = len(keyword) + len(value) + <NUM_LIT:3>   <EOL>n = p = <NUM_LIT:0><EOL>while True:<EOL><INDENT>n = l + len(str(p))<EOL>if n == p:<EOL><INDENT>break<EOL><DEDENT>p = n<EOL><DEDENT>records += bytes(str(p), "<STR_LIT:ascii>") + b"<STR_LIT:U+0020>" + keyword + b"<STR_LIT:=>" + value + b"<STR_LIT:\n>"<EOL><DEDENT>info = {}<EOL>info["<STR_LIT:name>"] = "<STR_LIT>"<EOL>info["<STR_LIT:type>"] = type<EOL>info["<STR_LIT:size>"] = len(records)<EOL>info["<STR_LIT>"] = POSIX_MAGIC<EOL>return cls._create_header(info, USTAR_FORMAT, "<STR_LIT:ascii>", "<STR_LIT:replace>") +cls._create_payload(records)<EOL>

Return a POSIX.1-2008 extended or global header sequence
           that contains a list of keyword, value pairs. The values
           must be strings.


@classmethod<EOL><INDENT>def frombuf(cls, buf, encoding, errors):<DEDENT>

if len(buf) == <NUM_LIT:0>:<EOL><INDENT>raise EmptyHeaderError("<STR_LIT>")<EOL><DEDENT>if len(buf) != BLOCKSIZE:<EOL><INDENT>raise TruncatedHeaderError("<STR_LIT>")<EOL><DEDENT>if buf.count(NUL) == BLOCKSIZE:<EOL><INDENT>raise EOFHeaderError("<STR_LIT>")<EOL><DEDENT>chksum = nti(buf[<NUM_LIT>:<NUM_LIT>])<EOL>if chksum not in calc_chksums(buf):<EOL><INDENT>raise InvalidHeaderError("<STR_LIT>")<EOL><DEDENT>obj = cls()<EOL>obj.name = nts(buf[<NUM_LIT:0>:<NUM_LIT:100>], encoding, errors)<EOL>obj.mode = nti(buf[<NUM_LIT:100>:<NUM_LIT>])<EOL>obj.uid = nti(buf[<NUM_LIT>:<NUM_LIT>])<EOL>obj.gid = nti(buf[<NUM_LIT>:<NUM_LIT>])<EOL>obj.size = nti(buf[<NUM_LIT>:<NUM_LIT>])<EOL>obj.mtime = nti(buf[<NUM_LIT>:<NUM_LIT>])<EOL>obj.chksum = chksum<EOL>obj.type = buf[<NUM_LIT>:<NUM_LIT>]<EOL>obj.linkname = nts(buf[<NUM_LIT>:<NUM_LIT>], encoding, errors)<EOL>obj.uname = nts(buf[<NUM_LIT>:<NUM_LIT>], encoding, errors)<EOL>obj.gname = nts(buf[<NUM_LIT>:<NUM_LIT>], encoding, errors)<EOL>obj.devmajor = nti(buf[<NUM_LIT>:<NUM_LIT>])<EOL>obj.devminor = nti(buf[<NUM_LIT>:<NUM_LIT>])<EOL>prefix = nts(buf[<NUM_LIT>:<NUM_LIT>], encoding, errors)<EOL>if obj.type == AREGTYPE and obj.name.endswith("<STR_LIT:/>"):<EOL><INDENT>obj.type = DIRTYPE<EOL><DEDENT>if obj.type == GNUTYPE_SPARSE:<EOL><INDENT>pos = <NUM_LIT><EOL>structs = []<EOL>for i in range(<NUM_LIT:4>):<EOL><INDENT>try:<EOL><INDENT>offset = nti(buf[pos:pos + <NUM_LIT:12>])<EOL>numbytes = nti(buf[pos + <NUM_LIT:12>:pos + <NUM_LIT>])<EOL><DEDENT>except ValueError:<EOL><INDENT>break<EOL><DEDENT>structs.append((offset, numbytes))<EOL>pos += <NUM_LIT><EOL><DEDENT>isextended = bool(buf[<NUM_LIT>])<EOL>origsize = nti(buf[<NUM_LIT>:<NUM_LIT>])<EOL>obj._sparse_structs = (structs, isextended, origsize)<EOL><DEDENT>if obj.isdir():<EOL><INDENT>obj.name = obj.name.rstrip("<STR_LIT:/>")<EOL><DEDENT>if prefix and obj.type not in GNU_TYPES:<EOL><INDENT>obj.name = prefix + "<STR_LIT:/>" + obj.name<EOL><DEDENT>return obj<EOL>

Construct a TarInfo object from a 512 byte bytes object.


buf = tarfile.fileobj.read(BLOCKSIZE)<EOL>obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)<EOL>obj.offset = tarfile.fileobj.tell() - BLOCKSIZE<EOL>return obj._proc_member(tarfile)<EOL>

Return the next TarInfo object from TarFile object
           tarfile.


if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):<EOL><INDENT>return self._proc_gnulong(tarfile)<EOL><DEDENT>elif self.type == GNUTYPE_SPARSE:<EOL><INDENT>return self._proc_sparse(tarfile)<EOL><DEDENT>elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):<EOL><INDENT>return self._proc_pax(tarfile)<EOL><DEDENT>else:<EOL><INDENT>return self._proc_builtin(tarfile)<EOL><DEDENT>

Choose the right processing method depending on
           the type and call it.


self.offset_data = tarfile.fileobj.tell()<EOL>offset = self.offset_data<EOL>if self.isreg() or self.type not in SUPPORTED_TYPES:<EOL><INDENT>offset += self._block(self.size)<EOL><DEDENT>tarfile.offset = offset<EOL>self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)<EOL>return self<EOL>

Process a builtin type or an unknown type which
           will be treated as a regular file.


buf = tarfile.fileobj.read(self._block(self.size))<EOL>try:<EOL><INDENT>next = self.fromtarfile(tarfile)<EOL><DEDENT>except HeaderError:<EOL><INDENT>raise SubsequentHeaderError("<STR_LIT>")<EOL><DEDENT>next.offset = self.offset<EOL>if self.type == GNUTYPE_LONGNAME:<EOL><INDENT>next.name = nts(buf, tarfile.encoding, tarfile.errors)<EOL><DEDENT>elif self.type == GNUTYPE_LONGLINK:<EOL><INDENT>next.linkname = nts(buf, tarfile.encoding, tarfile.errors)<EOL><DEDENT>return next<EOL>

Process the blocks that hold a GNU longname
           or longlink member.


<EOL>structs, isextended, origsize = self._sparse_structs<EOL>del self._sparse_structs<EOL>while isextended:<EOL><INDENT>buf = tarfile.fileobj.read(BLOCKSIZE)<EOL>pos = <NUM_LIT:0><EOL>for i in range(<NUM_LIT>):<EOL><INDENT>try:<EOL><INDENT>offset = nti(buf[pos:pos + <NUM_LIT:12>])<EOL>numbytes = nti(buf[pos + <NUM_LIT:12>:pos + <NUM_LIT>])<EOL><DEDENT>except ValueError:<EOL><INDENT>break<EOL><DEDENT>if offset and numbytes:<EOL><INDENT>structs.append((offset, numbytes))<EOL><DEDENT>pos += <NUM_LIT><EOL><DEDENT>isextended = bool(buf[<NUM_LIT>])<EOL><DEDENT>self.sparse = structs<EOL>self.offset_data = tarfile.fileobj.tell()<EOL>tarfile.offset = self.offset_data + self._block(self.size)<EOL>self.size = origsize<EOL>return self<EOL>

Process a GNU sparse header plus extra headers.


<EOL>buf = tarfile.fileobj.read(self._block(self.size))<EOL>if self.type == XGLTYPE:<EOL><INDENT>pax_headers = tarfile.pax_headers<EOL><DEDENT>else:<EOL><INDENT>pax_headers = tarfile.pax_headers.copy()<EOL><DEDENT>match = re.search(br"<STR_LIT>", buf)<EOL>if match is not None:<EOL><INDENT>pax_headers["<STR_LIT>"] = match.group(<NUM_LIT:1>).decode("<STR_LIT:utf8>")<EOL><DEDENT>hdrcharset = pax_headers.get("<STR_LIT>")<EOL>if hdrcharset == "<STR_LIT>":<EOL><INDENT>encoding = tarfile.encoding<EOL><DEDENT>else:<EOL><INDENT>encoding = "<STR_LIT:utf8>"<EOL><DEDENT>regex = re.compile(br"<STR_LIT>")<EOL>pos = <NUM_LIT:0><EOL>while True:<EOL><INDENT>match = regex.match(buf, pos)<EOL>if not match:<EOL><INDENT>break<EOL><DEDENT>length, keyword = match.groups()<EOL>length = int(length)<EOL>value = buf[match.end(<NUM_LIT:2>) + <NUM_LIT:1>:match.start(<NUM_LIT:1>) + length - <NUM_LIT:1>]<EOL>keyword = self._decode_pax_field(keyword, "<STR_LIT:utf8>", "<STR_LIT:utf8>",<EOL>tarfile.errors)<EOL>if keyword in PAX_NAME_FIELDS:<EOL><INDENT>value = self._decode_pax_field(value, encoding, tarfile.encoding,<EOL>tarfile.errors)<EOL><DEDENT>else:<EOL><INDENT>value = self._decode_pax_field(value, "<STR_LIT:utf8>", "<STR_LIT:utf8>",<EOL>tarfile.errors)<EOL><DEDENT>pax_headers[keyword] = value<EOL>pos += length<EOL><DEDENT>try:<EOL><INDENT>next = self.fromtarfile(tarfile)<EOL><DEDENT>except HeaderError:<EOL><INDENT>raise SubsequentHeaderError("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in pax_headers:<EOL><INDENT>self._proc_gnusparse_01(next, pax_headers)<EOL><DEDENT>elif "<STR_LIT>" in pax_headers:<EOL><INDENT>self._proc_gnusparse_00(next, pax_headers, buf)<EOL><DEDENT>elif pax_headers.get("<STR_LIT>") == "<STR_LIT:1>" and pax_headers.get("<STR_LIT>") == "<STR_LIT:0>":<EOL><INDENT>self._proc_gnusparse_10(next, pax_headers, tarfile)<EOL><DEDENT>if self.type in (XHDTYPE, SOLARIS_XHDTYPE):<EOL><INDENT>next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)<EOL>next.offset = self.offset<EOL>if "<STR_LIT:size>" in pax_headers:<EOL><INDENT>offset = next.offset_data<EOL>if next.isreg() or next.type not in SUPPORTED_TYPES:<EOL><INDENT>offset += next._block(next.size)<EOL><DEDENT>tarfile.offset = offset<EOL><DEDENT><DEDENT>return next<EOL>

Process an extended or global header as described in
           POSIX.1-2008.


def _proc_gnusparse_00(self, next, pax_headers, buf):

offsets = []<EOL>for match in re.finditer(br"<STR_LIT>", buf):<EOL><INDENT>offsets.append(int(match.group(<NUM_LIT:1>)))<EOL><DEDENT>numbytes = []<EOL>for match in re.finditer(br"<STR_LIT>", buf):<EOL><INDENT>numbytes.append(int(match.group(<NUM_LIT:1>)))<EOL><DEDENT>next.sparse = list(zip(offsets, numbytes))<EOL>

Process a GNU tar extended sparse header, version 0.0.


def _proc_gnusparse_01(self, next, pax_headers):

sparse = [int(x) for x in pax_headers["<STR_LIT>"].split("<STR_LIT:U+002C>")]<EOL>next.sparse = list(zip(sparse[::<NUM_LIT:2>], sparse[<NUM_LIT:1>::<NUM_LIT:2>]))<EOL>

Process a GNU tar extended sparse header, version 0.1.


def _proc_gnusparse_10(self, next, pax_headers, tarfile):

fields = None<EOL>sparse = []<EOL>buf = tarfile.fileobj.read(BLOCKSIZE)<EOL>fields, buf = buf.split(b"<STR_LIT:\n>", <NUM_LIT:1>)<EOL>fields = int(fields)<EOL>while len(sparse) < fields * <NUM_LIT:2>:<EOL><INDENT>if b"<STR_LIT:\n>" not in buf:<EOL><INDENT>buf += tarfile.fileobj.read(BLOCKSIZE)<EOL><DEDENT>number, buf = buf.split(b"<STR_LIT:\n>", <NUM_LIT:1>)<EOL>sparse.append(int(number))<EOL><DEDENT>next.offset_data = tarfile.fileobj.tell()<EOL>next.sparse = list(zip(sparse[::<NUM_LIT:2>], sparse[<NUM_LIT:1>::<NUM_LIT:2>]))<EOL>

Process a GNU tar extended sparse header, version 1.0.


def _apply_pax_info(self, pax_headers, encoding, errors):

for keyword, value in pax_headers.items():<EOL><INDENT>if keyword == "<STR_LIT>":<EOL><INDENT>setattr(self, "<STR_LIT:path>", value)<EOL><DEDENT>elif keyword == "<STR_LIT>":<EOL><INDENT>setattr(self, "<STR_LIT:size>", int(value))<EOL><DEDENT>elif keyword == "<STR_LIT>":<EOL><INDENT>setattr(self, "<STR_LIT:size>", int(value))<EOL><DEDENT>elif keyword in PAX_FIELDS:<EOL><INDENT>if keyword in PAX_NUMBER_FIELDS:<EOL><INDENT>try:<EOL><INDENT>value = PAX_NUMBER_FIELDS[keyword](value)<EOL><DEDENT>except ValueError:<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT><DEDENT>if keyword == "<STR_LIT:path>":<EOL><INDENT>value = value.rstrip("<STR_LIT:/>")<EOL><DEDENT>setattr(self, keyword, value)<EOL><DEDENT><DEDENT>self.pax_headers = pax_headers.copy()<EOL>

Replace fields with supplemental information from a previous
           pax extended or global header.


def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):

try:<EOL><INDENT>return value.decode(encoding, "<STR_LIT:strict>")<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>return value.decode(fallback_encoding, fallback_errors)<EOL><DEDENT>

Decode a single field from a pax record.


blocks, remainder = divmod(count, BLOCKSIZE)<EOL>if remainder:<EOL><INDENT>blocks += <NUM_LIT:1><EOL><DEDENT>return blocks * BLOCKSIZE<EOL>

Round up a byte count by BLOCKSIZE and return it,
           e.g. _block(834) => 1024.


def __init__(self, name=None, mode="<STR_LIT:r>", fileobj=None, format=None,<EOL>tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,<EOL>errors="<STR_LIT>", pax_headers=None, debug=None, errorlevel=None):

if len(mode) > <NUM_LIT:1> or mode not in "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.mode = mode<EOL>self._mode = {"<STR_LIT:r>": "<STR_LIT:rb>", "<STR_LIT:a>": "<STR_LIT>", "<STR_LIT:w>": "<STR_LIT:wb>"}[mode]<EOL>if not fileobj:<EOL><INDENT>if self.mode == "<STR_LIT:a>" and not os.path.exists(name):<EOL><INDENT>self.mode = "<STR_LIT:w>"<EOL>self._mode = "<STR_LIT:wb>"<EOL><DEDENT>fileobj = bltn_open(name, self._mode)<EOL>self._extfileobj = False<EOL><DEDENT>else:<EOL><INDENT>if name is None and hasattr(fileobj, "<STR_LIT:name>"):<EOL><INDENT>name = fileobj.name<EOL><DEDENT>if hasattr(fileobj, "<STR_LIT>"):<EOL><INDENT>self._mode = fileobj.mode<EOL><DEDENT>self._extfileobj = True<EOL><DEDENT>self.name = os.path.abspath(name) if name else None<EOL>self.fileobj = fileobj<EOL>if format is not None:<EOL><INDENT>self.format = format<EOL><DEDENT>if tarinfo is not None:<EOL><INDENT>self.tarinfo = tarinfo<EOL><DEDENT>if dereference is not None:<EOL><INDENT>self.dereference = dereference<EOL><DEDENT>if ignore_zeros is not None:<EOL><INDENT>self.ignore_zeros = ignore_zeros<EOL><DEDENT>if encoding is not None:<EOL><INDENT>self.encoding = encoding<EOL><DEDENT>self.errors = errors<EOL>if pax_headers is not None and self.format == PAX_FORMAT:<EOL><INDENT>self.pax_headers = pax_headers<EOL><DEDENT>else:<EOL><INDENT>self.pax_headers = {}<EOL><DEDENT>if debug is not None:<EOL><INDENT>self.debug = debug<EOL><DEDENT>if errorlevel is not None:<EOL><INDENT>self.errorlevel = errorlevel<EOL><DEDENT>self.closed = False<EOL>self.members = []       <EOL>self._loaded = False    <EOL>self.offset = self.fileobj.tell()<EOL>self.inodes = {}        <EOL>try:<EOL><INDENT>if self.mode == "<STR_LIT:r>":<EOL><INDENT>self.firstmember = None<EOL>self.firstmember = self.next()<EOL><DEDENT>if self.mode == "<STR_LIT:a>":<EOL><INDENT>while True:<EOL><INDENT>self.fileobj.seek(self.offset)<EOL>try:<EOL><INDENT>tarinfo = self.tarinfo.fromtarfile(self)<EOL>self.members.append(tarinfo)<EOL><DEDENT>except EOFHeaderError:<EOL><INDENT>self.fileobj.seek(self.offset)<EOL>break<EOL><DEDENT>except HeaderError as e:<EOL><INDENT>raise ReadError(str(e))<EOL><DEDENT><DEDENT><DEDENT>if self.mode in "<STR_LIT>":<EOL><INDENT>self._loaded = True<EOL>if self.pax_headers:<EOL><INDENT>buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())<EOL>self.fileobj.write(buf)<EOL>self.offset += len(buf)<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>if not self._extfileobj:<EOL><INDENT>self.fileobj.close()<EOL><DEDENT>self.closed = True<EOL>raise<EOL><DEDENT>

Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
           read from an existing archive, 'a' to append data to an existing
           file or 'w' to create a new file overwriting an existing one. `mode'
           defaults to 'r'.
           If `fileobj' is given, it is used for reading or writing data. If it
           can be determined, `mode' is overridden by `fileobj's mode.
           `fileobj' is not closed, when TarFile is closed.


@classmethod<EOL><INDENT>def open(cls, name=None, mode="<STR_LIT:r>", fileobj=None, bufsize=RECORDSIZE, **kwargs):<DEDENT>

if not name and not fileobj:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if mode in ("<STR_LIT:r>", "<STR_LIT>"):<EOL><INDENT>for comptype in cls.OPEN_METH:<EOL><INDENT>func = getattr(cls, cls.OPEN_METH[comptype])<EOL>if fileobj is not None:<EOL><INDENT>saved_pos = fileobj.tell()<EOL><DEDENT>try:<EOL><INDENT>return func(name, "<STR_LIT:r>", fileobj, **kwargs)<EOL><DEDENT>except (ReadError, CompressionError) as e:<EOL><INDENT>if fileobj is not None:<EOL><INDENT>fileobj.seek(saved_pos)<EOL><DEDENT>continue<EOL><DEDENT><DEDENT>raise ReadError("<STR_LIT>")<EOL><DEDENT>elif "<STR_LIT::>" in mode:<EOL><INDENT>filemode, comptype = mode.split("<STR_LIT::>", <NUM_LIT:1>)<EOL>filemode = filemode or "<STR_LIT:r>"<EOL>comptype = comptype or "<STR_LIT>"<EOL>if comptype in cls.OPEN_METH:<EOL><INDENT>func = getattr(cls, cls.OPEN_METH[comptype])<EOL><DEDENT>else:<EOL><INDENT>raise CompressionError("<STR_LIT>" % comptype)<EOL><DEDENT>return func(name, filemode, fileobj, **kwargs)<EOL><DEDENT>elif "<STR_LIT:|>" in mode:<EOL><INDENT>filemode, comptype = mode.split("<STR_LIT:|>", <NUM_LIT:1>)<EOL>filemode = filemode or "<STR_LIT:r>"<EOL>comptype = comptype or "<STR_LIT>"<EOL>if filemode not in "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>stream = _Stream(name, filemode, comptype, fileobj, bufsize)<EOL>try:<EOL><INDENT>t = cls(name, filemode, stream, **kwargs)<EOL><DEDENT>except:<EOL><INDENT>stream.close()<EOL>raise<EOL><DEDENT>t._extfileobj = False<EOL>return t<EOL><DEDENT>elif mode in "<STR_LIT>":<EOL><INDENT>return cls.taropen(name, mode, fileobj, **kwargs)<EOL><DEDENT>raise ValueError("<STR_LIT>")<EOL>

Open a tar archive for reading, writing or appending. Return
           an appropriate TarFile class.

           mode:
           'r' or 'r:*' open for reading with transparent compression
           'r:'         open for reading exclusively uncompressed
           'r:gz'       open for reading with gzip compression
           'r:bz2'      open for reading with bzip2 compression
           'a' or 'a:'  open for appending, creating the file if necessary
           'w' or 'w:'  open for writing without compression
           'w:gz'       open for writing with gzip compression
           'w:bz2'      open for writing with bzip2 compression

           'r|*'        open a stream of tar blocks with transparent compression
           'r|'         open an uncompressed stream of tar blocks for reading
           'r|gz'       open a gzip compressed stream of tar blocks
           'r|bz2'      open a bzip2 compressed stream of tar blocks
           'w|'         open an uncompressed stream for writing
           'w|gz'       open a gzip compressed stream for writing
           'w|bz2'      open a bzip2 compressed stream for writing


@classmethod<EOL><INDENT>def taropen(cls, name, mode="<STR_LIT:r>", fileobj=None, **kwargs):<DEDENT>

if len(mode) > <NUM_LIT:1> or mode not in "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return cls(name, mode, fileobj, **kwargs)<EOL>

Open uncompressed tar archive name for reading or writing.


@classmethod<EOL><INDENT>def gzopen(cls, name, mode="<STR_LIT:r>", fileobj=None, compresslevel=<NUM_LIT:9>, **kwargs):<DEDENT>

if len(mode) > <NUM_LIT:1> or mode not in "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>import gzip<EOL>gzip.GzipFile<EOL><DEDENT>except (ImportError, AttributeError):<EOL><INDENT>raise CompressionError("<STR_LIT>")<EOL><DEDENT>extfileobj = fileobj is not None<EOL>try:<EOL><INDENT>fileobj = gzip.GzipFile(name, mode + "<STR_LIT:b>", compresslevel, fileobj)<EOL>t = cls.taropen(name, mode, fileobj, **kwargs)<EOL><DEDENT>except IOError:<EOL><INDENT>if not extfileobj and fileobj is not None:<EOL><INDENT>fileobj.close()<EOL><DEDENT>if fileobj is None:<EOL><INDENT>raise<EOL><DEDENT>raise ReadError("<STR_LIT>")<EOL><DEDENT>except:<EOL><INDENT>if not extfileobj and fileobj is not None:<EOL><INDENT>fileobj.close()<EOL><DEDENT>raise<EOL><DEDENT>t._extfileobj = extfileobj<EOL>return t<EOL>

Open gzip compressed tar archive name for reading or writing.
           Appending is not allowed.


@classmethod<EOL><INDENT>def bz2open(cls, name, mode="<STR_LIT:r>", fileobj=None, compresslevel=<NUM_LIT:9>, **kwargs):<DEDENT>

if len(mode) > <NUM_LIT:1> or mode not in "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>import bz2<EOL><DEDENT>except ImportError:<EOL><INDENT>raise CompressionError("<STR_LIT>")<EOL><DEDENT>if fileobj is not None:<EOL><INDENT>fileobj = _BZ2Proxy(fileobj, mode)<EOL><DEDENT>else:<EOL><INDENT>fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)<EOL><DEDENT>try:<EOL><INDENT>t = cls.taropen(name, mode, fileobj, **kwargs)<EOL><DEDENT>except (IOError, EOFError):<EOL><INDENT>fileobj.close()<EOL>raise ReadError("<STR_LIT>")<EOL><DEDENT>t._extfileobj = False<EOL>return t<EOL>

Open bzip2 compressed tar archive name for reading or writing.
           Appending is not allowed.


if self.closed:<EOL><INDENT>return<EOL><DEDENT>if self.mode in "<STR_LIT>":<EOL><INDENT>self.fileobj.write(NUL * (BLOCKSIZE * <NUM_LIT:2>))<EOL>self.offset += (BLOCKSIZE * <NUM_LIT:2>)<EOL>blocks, remainder = divmod(self.offset, RECORDSIZE)<EOL>if remainder > <NUM_LIT:0>:<EOL><INDENT>self.fileobj.write(NUL * (RECORDSIZE - remainder))<EOL><DEDENT><DEDENT>if not self._extfileobj:<EOL><INDENT>self.fileobj.close()<EOL><DEDENT>self.closed = True<EOL>

Close the TarFile. In write-mode, two finishing zero blocks are
           appended to the archive.


tarinfo = self._getmember(name)<EOL>if tarinfo is None:<EOL><INDENT>raise KeyError("<STR_LIT>" % name)<EOL><DEDENT>return tarinfo<EOL>

Return a TarInfo object for member `name'. If `name' can not be
           found in the archive, KeyError is raised. If a member occurs more
           than once in the archive, its last occurrence is assumed to be the
           most up-to-date version.


self._check()<EOL>if not self._loaded:    <EOL><INDENT>self._load()        <EOL><DEDENT>return self.members<EOL>

Return the members of the archive as a list of TarInfo objects. The
           list has the same order as the members in the archive.


return [tarinfo.name for tarinfo in self.getmembers()]<EOL>

Return the members of the archive as a list of their names. It has
           the same order as the list returned by getmembers().


def gettarinfo(self, name=None, arcname=None, fileobj=None):

self._check("<STR_LIT>")<EOL>if fileobj is not None:<EOL><INDENT>name = fileobj.name<EOL><DEDENT>if arcname is None:<EOL><INDENT>arcname = name<EOL><DEDENT>drv, arcname = os.path.splitdrive(arcname)<EOL>arcname = arcname.replace(os.sep, "<STR_LIT:/>")<EOL>arcname = arcname.lstrip("<STR_LIT:/>")<EOL>tarinfo = self.tarinfo()<EOL>tarinfo.tarfile = self<EOL>if fileobj is None:<EOL><INDENT>if hasattr(os, "<STR_LIT>") and not self.dereference:<EOL><INDENT>statres = os.lstat(name)<EOL><DEDENT>else:<EOL><INDENT>statres = os.stat(name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>statres = os.fstat(fileobj.fileno())<EOL><DEDENT>linkname = "<STR_LIT>"<EOL>stmd = statres.st_mode<EOL>if stat.S_ISREG(stmd):<EOL><INDENT>inode = (statres.st_ino, statres.st_dev)<EOL>if not self.dereference and statres.st_nlink > <NUM_LIT:1> andinode in self.inodes and arcname != self.inodes[inode]:<EOL><INDENT>type = LNKTYPE<EOL>linkname = self.inodes[inode]<EOL><DEDENT>else:<EOL><INDENT>type = REGTYPE<EOL>if inode[<NUM_LIT:0>]:<EOL><INDENT>self.inodes[inode] = arcname<EOL><DEDENT><DEDENT><DEDENT>elif stat.S_ISDIR(stmd):<EOL><INDENT>type = DIRTYPE<EOL><DEDENT>elif stat.S_ISFIFO(stmd):<EOL><INDENT>type = FIFOTYPE<EOL><DEDENT>elif stat.S_ISLNK(stmd):<EOL><INDENT>type = SYMTYPE<EOL>linkname = os.readlink(name)<EOL><DEDENT>elif stat.S_ISCHR(stmd):<EOL><INDENT>type = CHRTYPE<EOL><DEDENT>elif stat.S_ISBLK(stmd):<EOL><INDENT>type = BLKTYPE<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>tarinfo.name = arcname<EOL>tarinfo.mode = stmd<EOL>tarinfo.uid = statres.st_uid<EOL>tarinfo.gid = statres.st_gid<EOL>if type == REGTYPE:<EOL><INDENT>tarinfo.size = statres.st_size<EOL><DEDENT>else:<EOL><INDENT>tarinfo.size = <NUM_LIT:0><EOL><DEDENT>tarinfo.mtime = statres.st_mtime<EOL>tarinfo.type = type<EOL>tarinfo.linkname = linkname<EOL>if pwd:<EOL><INDENT>try:<EOL><INDENT>tarinfo.uname = pwd.getpwuid(tarinfo.uid)[<NUM_LIT:0>]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if grp:<EOL><INDENT>try:<EOL><INDENT>tarinfo.gname = grp.getgrgid(tarinfo.gid)[<NUM_LIT:0>]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if type in (CHRTYPE, BLKTYPE):<EOL><INDENT>if hasattr(os, "<STR_LIT>") and hasattr(os, "<STR_LIT>"):<EOL><INDENT>tarinfo.devmajor = os.major(statres.st_rdev)<EOL>tarinfo.devminor = os.minor(statres.st_rdev)<EOL><DEDENT><DEDENT>return tarinfo<EOL>

Create a TarInfo object for either the file `name' or the file
           object `fileobj' (using os.fstat on its file descriptor). You can
           modify some of the TarInfo's attributes before you add it using
           addfile(). If given, `arcname' specifies an alternative name for the
           file in the archive.


self._check()<EOL>for tarinfo in self:<EOL><INDENT>if verbose:<EOL><INDENT>print(filemode(tarinfo.mode), end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % (tarinfo.uname or tarinfo.uid,<EOL>tarinfo.gname or tarinfo.gid), end='<STR_LIT:U+0020>')<EOL>if tarinfo.ischr() or tarinfo.isblk():<EOL><INDENT>print("<STR_LIT>" % ("<STR_LIT>"% (tarinfo.devmajor, tarinfo.devminor)), end='<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % tarinfo.size, end='<STR_LIT:U+0020>')<EOL><DEDENT>print("<STR_LIT>"% time.localtime(tarinfo.mtime)[:<NUM_LIT:6>], end='<STR_LIT:U+0020>')<EOL><DEDENT>print(tarinfo.name + ("<STR_LIT:/>" if tarinfo.isdir() else "<STR_LIT>"), end='<STR_LIT:U+0020>')<EOL>if verbose:<EOL><INDENT>if tarinfo.issym():<EOL><INDENT>print("<STR_LIT>", tarinfo.linkname, end='<STR_LIT:U+0020>')<EOL><DEDENT>if tarinfo.islnk():<EOL><INDENT>print("<STR_LIT>", tarinfo.linkname, end='<STR_LIT:U+0020>')<EOL><DEDENT><DEDENT>print()<EOL><DEDENT>

Print a table of contents to sys.stdout. If `verbose' is False, only
           the names of the members are printed. If it is True, an `ls -l'-like
           output is produced.


def add(self, name, arcname=None, recursive=True, exclude=None, filter=None):

self._check("<STR_LIT>")<EOL>if arcname is None:<EOL><INDENT>arcname = name<EOL><DEDENT>if exclude is not None:<EOL><INDENT>import warnings<EOL>warnings.warn("<STR_LIT>",<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>if exclude(name):<EOL><INDENT>self._dbg(<NUM_LIT:2>, "<STR_LIT>" % name)<EOL>return<EOL><DEDENT><DEDENT>if self.name is not None and os.path.abspath(name) == self.name:<EOL><INDENT>self._dbg(<NUM_LIT:2>, "<STR_LIT>" % name)<EOL>return<EOL><DEDENT>self._dbg(<NUM_LIT:1>, name)<EOL>tarinfo = self.gettarinfo(name, arcname)<EOL>if tarinfo is None:<EOL><INDENT>self._dbg(<NUM_LIT:1>, "<STR_LIT>" % name)<EOL>return<EOL><DEDENT>if filter is not None:<EOL><INDENT>tarinfo = filter(tarinfo)<EOL>if tarinfo is None:<EOL><INDENT>self._dbg(<NUM_LIT:2>, "<STR_LIT>" % name)<EOL>return<EOL><DEDENT><DEDENT>if tarinfo.isreg():<EOL><INDENT>f = bltn_open(name, "<STR_LIT:rb>")<EOL>self.addfile(tarinfo, f)<EOL>f.close()<EOL><DEDENT>elif tarinfo.isdir():<EOL><INDENT>self.addfile(tarinfo)<EOL>if recursive:<EOL><INDENT>for f in os.listdir(name):<EOL><INDENT>self.add(os.path.join(name, f), os.path.join(arcname, f),<EOL>recursive, exclude, filter=filter)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.addfile(tarinfo)<EOL><DEDENT>

Add the file `name' to the archive. `name' may be any type of file
           (directory, fifo, symbolic link, etc.). If given, `arcname'
           specifies an alternative name for the file in the archive.
           Directories are added recursively by default. This can be avoided by
           setting `recursive' to False. `exclude' is a function that should
           return True for each filename to be excluded. `filter' is a function
           that expects a TarInfo object argument and returns the changed
           TarInfo object, if it returns None the TarInfo object will be
           excluded from the archive.


def addfile(self, tarinfo, fileobj=None):

self._check("<STR_LIT>")<EOL>tarinfo = copy.copy(tarinfo)<EOL>buf = tarinfo.tobuf(self.format, self.encoding, self.errors)<EOL>self.fileobj.write(buf)<EOL>self.offset += len(buf)<EOL>if fileobj is not None:<EOL><INDENT>copyfileobj(fileobj, self.fileobj, tarinfo.size)<EOL>blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)<EOL>if remainder > <NUM_LIT:0>:<EOL><INDENT>self.fileobj.write(NUL * (BLOCKSIZE - remainder))<EOL>blocks += <NUM_LIT:1><EOL><DEDENT>self.offset += blocks * BLOCKSIZE<EOL><DEDENT>self.members.append(tarinfo)<EOL>

Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
           given, tarinfo.size bytes are read from it and added to the archive.
           You can create TarInfo objects using gettarinfo().
           On Windows platforms, `fileobj' should always be opened with mode
           'rb' to avoid irritation about the file size.


def extractall(self, path="<STR_LIT:.>", members=None):

directories = []<EOL>if members is None:<EOL><INDENT>members = self<EOL><DEDENT>for tarinfo in members:<EOL><INDENT>if tarinfo.isdir():<EOL><INDENT>directories.append(tarinfo)<EOL>tarinfo = copy.copy(tarinfo)<EOL>tarinfo.mode = <NUM_LIT><EOL><DEDENT>self.extract(tarinfo, path, set_attrs=not tarinfo.isdir())<EOL><DEDENT>directories.sort(key=lambda a: a.name)<EOL>directories.reverse()<EOL>for tarinfo in directories:<EOL><INDENT>dirpath = os.path.join(path, tarinfo.name)<EOL>try:<EOL><INDENT>self.chown(tarinfo, dirpath)<EOL>self.utime(tarinfo, dirpath)<EOL>self.chmod(tarinfo, dirpath)<EOL><DEDENT>except ExtractError as e:<EOL><INDENT>if self.errorlevel > <NUM_LIT:1>:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>self._dbg(<NUM_LIT:1>, "<STR_LIT>" % e)<EOL><DEDENT><DEDENT><DEDENT>

Extract all members from the archive to the current working
           directory and set owner, modification time and permissions on
           directories afterwards. `path' specifies a different directory
           to extract to. `members' is optional and must be a subset of the
           list returned by getmembers().


def extract(self, member, path="<STR_LIT>", set_attrs=True):

self._check("<STR_LIT:r>")<EOL>if isinstance(member, str):<EOL><INDENT>tarinfo = self.getmember(member)<EOL><DEDENT>else:<EOL><INDENT>tarinfo = member<EOL><DEDENT>if tarinfo.islnk():<EOL><INDENT>tarinfo._link_target = os.path.join(path, tarinfo.linkname)<EOL><DEDENT>try:<EOL><INDENT>self._extract_member(tarinfo, os.path.join(path, tarinfo.name),<EOL>set_attrs=set_attrs)<EOL><DEDENT>except EnvironmentError as e:<EOL><INDENT>if self.errorlevel > <NUM_LIT:0>:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>if e.filename is None:<EOL><INDENT>self._dbg(<NUM_LIT:1>, "<STR_LIT>" % e.strerror)<EOL><DEDENT>else:<EOL><INDENT>self._dbg(<NUM_LIT:1>, "<STR_LIT>" % (e.strerror, e.filename))<EOL><DEDENT><DEDENT><DEDENT>except ExtractError as e:<EOL><INDENT>if self.errorlevel > <NUM_LIT:1>:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>self._dbg(<NUM_LIT:1>, "<STR_LIT>" % e)<EOL><DEDENT><DEDENT>

Extract a member from the archive to the current working directory,
           using its full name. Its file information is extracted as accurately
           as possible. `member' may be a filename or a TarInfo object. You can
           specify a different directory using `path'. File attributes (owner,
           mtime, mode) are set unless `set_attrs' is False.


self._check("<STR_LIT:r>")<EOL>if isinstance(member, str):<EOL><INDENT>tarinfo = self.getmember(member)<EOL><DEDENT>else:<EOL><INDENT>tarinfo = member<EOL><DEDENT>if tarinfo.isreg():<EOL><INDENT>return self.fileobject(self, tarinfo)<EOL><DEDENT>elif tarinfo.type not in SUPPORTED_TYPES:<EOL><INDENT>return self.fileobject(self, tarinfo)<EOL><DEDENT>elif tarinfo.islnk() or tarinfo.issym():<EOL><INDENT>if isinstance(self.fileobj, _Stream):<EOL><INDENT>raise StreamError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>return self.extractfile(self._find_link_target(tarinfo))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Extract a member from the archive as a file object. `member' may be
           a filename or a TarInfo object. If `member' is a regular file, a
           file-like object is returned. If `member' is a link, a file-like
           object is constructed from the link's target. If `member' is none of
           the above, None is returned.
           The file-like object is read-only and provides the following
           methods: read(), readline(), readlines(), seek() and tell()


def _extract_member(self, tarinfo, targetpath, set_attrs=True):

<EOL>targetpath = targetpath.rstrip("<STR_LIT:/>")<EOL>targetpath = targetpath.replace("<STR_LIT:/>", os.sep)<EOL>upperdirs = os.path.dirname(targetpath)<EOL>if upperdirs and not os.path.exists(upperdirs):<EOL><INDENT>os.makedirs(upperdirs)<EOL><DEDENT>if tarinfo.islnk() or tarinfo.issym():<EOL><INDENT>self._dbg(<NUM_LIT:1>, "<STR_LIT>" % (tarinfo.name, tarinfo.linkname))<EOL><DEDENT>else:<EOL><INDENT>self._dbg(<NUM_LIT:1>, tarinfo.name)<EOL><DEDENT>if tarinfo.isreg():<EOL><INDENT>self.makefile(tarinfo, targetpath)<EOL><DEDENT>elif tarinfo.isdir():<EOL><INDENT>self.makedir(tarinfo, targetpath)<EOL><DEDENT>elif tarinfo.isfifo():<EOL><INDENT>self.makefifo(tarinfo, targetpath)<EOL><DEDENT>elif tarinfo.ischr() or tarinfo.isblk():<EOL><INDENT>self.makedev(tarinfo, targetpath)<EOL><DEDENT>elif tarinfo.islnk() or tarinfo.issym():<EOL><INDENT>self.makelink(tarinfo, targetpath)<EOL><DEDENT>elif tarinfo.type not in SUPPORTED_TYPES:<EOL><INDENT>self.makeunknown(tarinfo, targetpath)<EOL><DEDENT>else:<EOL><INDENT>self.makefile(tarinfo, targetpath)<EOL><DEDENT>if set_attrs:<EOL><INDENT>self.chown(tarinfo, targetpath)<EOL>if not tarinfo.issym():<EOL><INDENT>self.chmod(tarinfo, targetpath)<EOL>self.utime(tarinfo, targetpath)<EOL><DEDENT><DEDENT>

Extract the TarInfo object tarinfo to a physical
           file called targetpath.


try:<EOL><INDENT>os.mkdir(targetpath, <NUM_LIT>)<EOL><DEDENT>except EnvironmentError as e:<EOL><INDENT>if e.errno != errno.EEXIST:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>


def makefile(self, tarinfo, targetpath):

source = self.fileobj<EOL>source.seek(tarinfo.offset_data)<EOL>target = bltn_open(targetpath, "<STR_LIT:wb>")<EOL>if tarinfo.sparse is not None:<EOL><INDENT>for offset, size in tarinfo.sparse:<EOL><INDENT>target.seek(offset)<EOL>copyfileobj(source, target, size)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>copyfileobj(source, target, tarinfo.size)<EOL><DEDENT>target.seek(tarinfo.size)<EOL>target.truncate()<EOL>target.close()<EOL>


def makeunknown(self, tarinfo, targetpath):

self.makefile(tarinfo, targetpath)<EOL>self._dbg(<NUM_LIT:1>, "<STR_LIT>""<STR_LIT>" % tarinfo.type)<EOL>

Make a file from a TarInfo object with an unknown type
           at targetpath.


def makefifo(self, tarinfo, targetpath):

if hasattr(os, "<STR_LIT>"):<EOL><INDENT>os.mkfifo(targetpath)<EOL><DEDENT>else:<EOL><INDENT>raise ExtractError("<STR_LIT>")<EOL><DEDENT>


if not hasattr(os, "<STR_LIT>") or not hasattr(os, "<STR_LIT>"):<EOL><INDENT>raise ExtractError("<STR_LIT>")<EOL><DEDENT>mode = tarinfo.mode<EOL>if tarinfo.isblk():<EOL><INDENT>mode |= stat.S_IFBLK<EOL><DEDENT>else:<EOL><INDENT>mode |= stat.S_IFCHR<EOL><DEDENT>os.mknod(targetpath, mode,<EOL>os.makedev(tarinfo.devmajor, tarinfo.devminor))<EOL>

Make a character or block device called targetpath.


def makelink(self, tarinfo, targetpath):

Make a (symbolic) link called targetpath. If it cannot be created
          (platform limitation), we try to make a copy of the referenced file
          instead of a link.


if pwd and hasattr(os, "<STR_LIT>") and os.geteuid() == <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>g = grp.getgrnam(tarinfo.gname)[<NUM_LIT:2>]<EOL><DEDENT>except KeyError:<EOL><INDENT>g = tarinfo.gid<EOL><DEDENT>try:<EOL><INDENT>u = pwd.getpwnam(tarinfo.uname)[<NUM_LIT:2>]<EOL><DEDENT>except KeyError:<EOL><INDENT>u = tarinfo.uid<EOL><DEDENT>try:<EOL><INDENT>if tarinfo.issym() and hasattr(os, "<STR_LIT>"):<EOL><INDENT>os.lchown(targetpath, u, g)<EOL><DEDENT>else:<EOL><INDENT>if sys.platform != "<STR_LIT>":<EOL><INDENT>os.chown(targetpath, u, g)<EOL><DEDENT><DEDENT><DEDENT>except EnvironmentError as e:<EOL><INDENT>raise ExtractError("<STR_LIT>")<EOL><DEDENT><DEDENT>

Set owner of targetpath according to tarinfo.


if hasattr(os, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>os.chmod(targetpath, tarinfo.mode)<EOL><DEDENT>except EnvironmentError as e:<EOL><INDENT>raise ExtractError("<STR_LIT>")<EOL><DEDENT><DEDENT>

Set file permissions of targetpath according to tarinfo.


if not hasattr(os, '<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))<EOL><DEDENT>except EnvironmentError as e:<EOL><INDENT>raise ExtractError("<STR_LIT>")<EOL><DEDENT>

Set modification time of targetpath according to tarinfo.


self._check("<STR_LIT>")<EOL>if self.firstmember is not None:<EOL><INDENT>m = self.firstmember<EOL>self.firstmember = None<EOL>return m<EOL><DEDENT>self.fileobj.seek(self.offset)<EOL>tarinfo = None<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>tarinfo = self.tarinfo.fromtarfile(self)<EOL><DEDENT>except EOFHeaderError as e:<EOL><INDENT>if self.ignore_zeros:<EOL><INDENT>self._dbg(<NUM_LIT:2>, "<STR_LIT>" % (self.offset, e))<EOL>self.offset += BLOCKSIZE<EOL>continue<EOL><DEDENT><DEDENT>except InvalidHeaderError as e:<EOL><INDENT>if self.ignore_zeros:<EOL><INDENT>self._dbg(<NUM_LIT:2>, "<STR_LIT>" % (self.offset, e))<EOL>self.offset += BLOCKSIZE<EOL>continue<EOL><DEDENT>elif self.offset == <NUM_LIT:0>:<EOL><INDENT>raise ReadError(str(e))<EOL><DEDENT><DEDENT>except EmptyHeaderError:<EOL><INDENT>if self.offset == <NUM_LIT:0>:<EOL><INDENT>raise ReadError("<STR_LIT>")<EOL><DEDENT><DEDENT>except TruncatedHeaderError as e:<EOL><INDENT>if self.offset == <NUM_LIT:0>:<EOL><INDENT>raise ReadError(str(e))<EOL><DEDENT><DEDENT>except SubsequentHeaderError as e:<EOL><INDENT>raise ReadError(str(e))<EOL><DEDENT>break<EOL><DEDENT>if tarinfo is not None:<EOL><INDENT>self.members.append(tarinfo)<EOL><DEDENT>else:<EOL><INDENT>self._loaded = True<EOL><DEDENT>return tarinfo<EOL>

Return the next member of the archive as a TarInfo object, when
           TarFile is opened for reading. Return None if there is no more
           available.


def _getmember(self, name, tarinfo=None, normalize=False):

<EOL>members = self.getmembers()<EOL>if tarinfo is not None:<EOL><INDENT>members = members[:members.index(tarinfo)]<EOL><DEDENT>if normalize:<EOL><INDENT>name = os.path.normpath(name)<EOL><DEDENT>for member in reversed(members):<EOL><INDENT>if normalize:<EOL><INDENT>member_name = os.path.normpath(member.name)<EOL><DEDENT>else:<EOL><INDENT>member_name = member.name<EOL><DEDENT>if name == member_name:<EOL><INDENT>return member<EOL><DEDENT><DEDENT>

Find an archive member by name from bottom to top.
           If tarinfo is given, it is used as the starting point.


while True:<EOL><INDENT>tarinfo = self.next()<EOL>if tarinfo is None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>self._loaded = True<EOL>

Read through the entire archive file and look for readable
           members.


if self.closed:<EOL><INDENT>raise IOError("<STR_LIT>" % self.__class__.__name__)<EOL><DEDENT>if mode is not None and self.mode not in mode:<EOL><INDENT>raise IOError("<STR_LIT>" % self.mode)<EOL><DEDENT>

Check if TarFile is still open, and if the operation's mode
           corresponds to TarFile's mode.


if tarinfo.issym():<EOL><INDENT>linkname = os.path.dirname(tarinfo.name) + "<STR_LIT:/>" + tarinfo.linkname<EOL>limit = None<EOL><DEDENT>else:<EOL><INDENT>linkname = tarinfo.linkname<EOL>limit = tarinfo<EOL><DEDENT>member = self._getmember(linkname, tarinfo=limit, normalize=True)<EOL>if member is None:<EOL><INDENT>raise KeyError("<STR_LIT>" % linkname)<EOL><DEDENT>return member<EOL>

Find the target member of a symlink or hardlink member in the
           archive.


if self._loaded:<EOL><INDENT>return iter(self.members)<EOL><DEDENT>else:<EOL><INDENT>return TarIter(self)<EOL><DEDENT>


if level <= self.debug:<EOL><INDENT>print(msg, file=sys.stderr)<EOL><DEDENT>


self.tarfile = tarfile<EOL>self.index = <NUM_LIT:0><EOL>


return self<EOL>


<EOL>if not self.tarfile._loaded:<EOL><INDENT>tarinfo = self.tarfile.next()<EOL>if not tarinfo:<EOL><INDENT>self.tarfile._loaded = True<EOL>raise StopIteration<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>tarinfo = self.tarfile.members[self.index]<EOL><DEDENT>except IndexError:<EOL><INDENT>raise StopIteration<EOL><DEDENT><DEDENT>self.index += <NUM_LIT:1><EOL>return tarinfo<EOL>

Return the next item using TarFile's next() method.
           When all members have been read, set TarFile as _loaded.


def __init__(self, path, threaded=True, timeout=None):

LockBase.__init__(self, path, threaded, timeout)<EOL>self.unique_name  = os.path.join(self.lock_file,<EOL>"<STR_LIT>" % (self.hostname,<EOL>self.tname,<EOL>self.pid))<EOL>

>>> lock = MkdirLockFile('somefile')
>>> lock = MkdirLockFile('somefile', threaded=False)


LockBase.__init__(self, path, threaded, timeout)<EOL>self.lock_file = unicode(self.lock_file)<EOL>self.unique_name = unicode(self.unique_name)<EOL>if SQLiteLockFile.testdb is None:<EOL><INDENT>import tempfile<EOL>_fd, testdb = tempfile.mkstemp()<EOL>os.close(_fd)<EOL>os.unlink(testdb)<EOL>del _fd, tempfile<EOL>SQLiteLockFile.testdb = testdb<EOL><DEDENT>import sqlite3<EOL>self.connection = sqlite3.connect(SQLiteLockFile.testdb)<EOL>c = self.connection.cursor()<EOL>try:<EOL><INDENT>c.execute("<STR_LIT>"<EOL>"<STR_LIT:(>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT:)>")<EOL><DEDENT>except sqlite3.OperationalError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.connection.commit()<EOL>import atexit<EOL>atexit.register(os.unlink, SQLiteLockFile.testdb)<EOL><DEDENT>

>>> lock = SQLiteLockFile('somefile')
>>> lock = SQLiteLockFile('somefile', threaded=False)


from . import linklockfile<EOL>return _fl_helper(linklockfile.LinkLockFile, "<STR_LIT>",<EOL>*args, **kwds)<EOL>

Factory function provided for backwards compatibility.

    Do not use in new code.  Instead, import LinkLockFile from the
    lockfile.linklockfile module.


from . import mkdirlockfile<EOL>return _fl_helper(mkdirlockfile.MkdirLockFile, "<STR_LIT>",<EOL>*args, **kwds)<EOL>

Factory function provided for backwards compatibility.

    Do not use in new code.  Instead, import MkdirLockFile from the
    lockfile.mkdirlockfile module.


from . import sqlitelockfile<EOL>return _fl_helper(sqlitelockfile.SQLiteLockFile, "<STR_LIT>",<EOL>*args, **kwds)<EOL>

Factory function provided for backwards compatibility.

    Do not use in new code.  Instead, import SQLiteLockFile from the
    lockfile.mkdirlockfile module.


def decor(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>lock = FileLock(path, timeout=timeout)<EOL>lock.acquire()<EOL>try:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>lock.release()<EOL><DEDENT><DEDENT>return wrapper<EOL><DEDENT>return decor<EOL>

Decorator which enables locks for decorated function.

    Arguments:
     - path: path for lockfile.
     - timeout (optional): Timeout for acquiring lock.

     Usage:
         @locked('/var/run/myname', timeout=0)
         def myname(...):
             ...


self.path = path<EOL>self.lock_file = os.path.abspath(path) + "<STR_LIT>"<EOL>self.hostname = socket.gethostname()<EOL>self.pid = os.getpid()<EOL>if threaded:<EOL><INDENT>t = threading.current_thread()<EOL>ident = getattr(t, "<STR_LIT>", hash(t))<EOL>self.tname = "<STR_LIT>" % (ident & <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>self.tname = "<STR_LIT>"<EOL><DEDENT>dirname = os.path.dirname(self.lock_file)<EOL>self.unique_name = os.path.join(dirname,<EOL>"<STR_LIT>" % (self.hostname,<EOL>self.tname,<EOL>self.pid,<EOL>hash(self.path)))<EOL>self.timeout = timeout<EOL>

>>> lock = LockBase('somefile')
>>> lock = LockBase('somefile', threaded=False)


raise NotImplemented("<STR_LIT>")<EOL>

Acquire the lock.

* If timeout is omitted (or None), wait forever trying to lock the
  file.

* If timeout > 0, try to acquire the lock for that many seconds.  If
  the lock period expires and the file is still locked, raise
  LockTimeout.

* If timeout <= 0, raise AlreadyLocked immediately if the file is
  already locked.


raise NotImplemented("<STR_LIT>")<EOL>

Release the lock.

If the file is not locked, raise NotLocked.


raise NotImplemented("<STR_LIT>")<EOL>


raise NotImplemented("<STR_LIT>")<EOL>

Return True if this object is locking the file.


raise NotImplemented("<STR_LIT>")<EOL>

Remove a lock.  Useful if a locking thread failed to unlock.


self.acquire()<EOL>return self<EOL>


self.release()<EOL>


pid = None<EOL>try:<EOL><INDENT>pidfile = open(pidfile_path, '<STR_LIT:r>')<EOL><DEDENT>except IOError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>line = pidfile.readline().strip()<EOL>try:<EOL><INDENT>pid = int(line)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>pidfile.close()<EOL><DEDENT>return pid<EOL>

Read the PID recorded in the named PID file.

        Read and return the numeric PID recorded as text in the named
        PID file. If the PID file cannot be read, or if the content is
        not a valid PID, return ``None``.


open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)<EOL>open_mode = <NUM_LIT><EOL>pidfile_fd = os.open(pidfile_path, open_flags, open_mode)<EOL>pidfile = os.fdopen(pidfile_fd, '<STR_LIT:w>')<EOL>pid = os.getpid()<EOL>line = "<STR_LIT>" % vars()<EOL>pidfile.write(line)<EOL>pidfile.close()<EOL>

Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.


try:<EOL><INDENT>os.remove(pidfile_path)<EOL><DEDENT>except OSError as exc:<EOL><INDENT>if exc.errno == errno.ENOENT:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>

Remove the named PID file if it exists.

        Removing a PID file that doesn't already exist puts us in the
        desired state, so we ignore the condition if the file does not
        exist.


return read_pid_from_pidfile(self.path)<EOL>


return os.path.exists(self.path)<EOL>

Test if the lock is currently held.

            The lock is held if the PID file for this lock exists.


return self.is_locked() and os.getpid() == self.read_pid()<EOL>

Test if the lock is held by the current process.

        Returns ``True`` if the current process ID matches the
        number stored in the PID file.


timeout = timeout is not None and timeout or self.timeout<EOL>end_time = time.time()<EOL>if timeout is not None and timeout > <NUM_LIT:0>:<EOL><INDENT>end_time += timeout<EOL><DEDENT>while True:<EOL><INDENT>try:<EOL><INDENT>write_pid_to_pidfile(self.path)<EOL><DEDENT>except OSError as exc:<EOL><INDENT>if exc.errno == errno.EEXIST:<EOL><INDENT>if timeout is not None and time.time() > end_time:<EOL><INDENT>if timeout > <NUM_LIT:0>:<EOL><INDENT>raise LockTimeout("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>self.path)<EOL><DEDENT>else:<EOL><INDENT>raise AlreadyLocked("<STR_LIT>" %<EOL>self.path)<EOL><DEDENT><DEDENT>time.sleep(timeout is not None and timeout/<NUM_LIT:10> or <NUM_LIT:0.1>)<EOL><DEDENT>else:<EOL><INDENT>raise LockFailed("<STR_LIT>" % self.path)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>

Acquire the lock.

        Creates the PID file for this lock, or raises an error if
        the lock could not be acquired.


if not self.is_locked():<EOL><INDENT>raise NotLocked("<STR_LIT>" % self.path)<EOL><DEDENT>if not self.i_am_locking():<EOL><INDENT>raise NotMyLock("<STR_LIT>" % self.path)<EOL><DEDENT>remove_existing_pidfile(self.path)<EOL>

Release the lock.

            Removes the PID file to release the lock, or raises an
            error if the current process does not hold the lock.


Break an existing lock.

            Removes the PID file if it already exists, otherwise does
            nothing.


def prepare_response(self, request, cached):

<EOL>if "<STR_LIT:*>" in cached.get("<STR_LIT>", {}):<EOL><INDENT>return<EOL><DEDENT>for header, value in cached.get("<STR_LIT>", {}).items():<EOL><INDENT>if request.headers.get(header, None) != value:<EOL><INDENT>return<EOL><DEDENT><DEDENT>body = io.BytesIO(cached["<STR_LIT>"].pop("<STR_LIT:body>"))<EOL>return HTTPResponse(<EOL>body=body,<EOL>preload_content=False,<EOL>**cached["<STR_LIT>"]<EOL>)<EOL>

Verify our vary headers match and construct a real urllib3
        HTTPResponse object.


groups = URI.match(uri).groups()<EOL>return (groups[<NUM_LIT:1>], groups[<NUM_LIT:3>], groups[<NUM_LIT:4>], groups[<NUM_LIT:6>], groups[<NUM_LIT:8>])<EOL>

Parses a URI using the regex given in Appendix B of RFC 3986.

        (scheme, authority, path, query, fragment) = parse_uri(uri)


(scheme, authority, path, query, fragment) = parse_uri(uri)<EOL>if not scheme or not authority:<EOL><INDENT>raise Exception("<STR_LIT>" % uri)<EOL><DEDENT>scheme = scheme.lower()<EOL>authority = authority.lower()<EOL>if not path:<EOL><INDENT>path = "<STR_LIT:/>"<EOL><DEDENT>request_uri = query and "<STR_LIT:?>".join([path, query]) or path<EOL>defrag_uri = scheme + "<STR_LIT>" + authority + request_uri<EOL>return defrag_uri<EOL>

Normalize the URL to create a safe key for the cache


retval = {}<EOL>cc_header = '<STR_LIT>'<EOL>if '<STR_LIT>' in headers:<EOL><INDENT>cc_header = '<STR_LIT>'<EOL><DEDENT>if cc_header in headers:<EOL><INDENT>parts = headers[cc_header].split('<STR_LIT:U+002C>')<EOL>parts_with_args = [<EOL>tuple([x.strip().lower() for x in part.split("<STR_LIT:=>", <NUM_LIT:1>)])<EOL>for part in parts if -<NUM_LIT:1> != part.find("<STR_LIT:=>")<EOL>]<EOL>parts_wo_args = [<EOL>(name.strip().lower(), <NUM_LIT:1>)<EOL>for name in parts if -<NUM_LIT:1> == name.find("<STR_LIT:=>")<EOL>]<EOL>retval = dict(parts_with_args + parts_wo_args)<EOL><DEDENT>return retval<EOL>

Parse the cache control headers returning a dictionary with values
for the different directives.


cache_url = self.cache_url(request.url)<EOL>cc = self.parse_cache_control(request.headers)<EOL>no_cache = True if '<STR_LIT>' in cc else False<EOL>if '<STR_LIT>' in cc and cc['<STR_LIT>'] == <NUM_LIT:0>:<EOL><INDENT>no_cache = True<EOL><DEDENT>if no_cache:<EOL><INDENT>return False<EOL><DEDENT>resp = self.serializer.loads(request, self.cache.get(cache_url))<EOL>if not resp:<EOL><INDENT>return False<EOL><DEDENT>headers = CaseInsensitiveDict(resp.headers)<EOL>now = time.time()<EOL>date = calendar.timegm(<EOL>parsedate_tz(headers['<STR_LIT:date>'])<EOL>)<EOL>current_age = max(<NUM_LIT:0>, now - date)<EOL>resp_cc = self.parse_cache_control(headers)<EOL>freshness_lifetime = <NUM_LIT:0><EOL>if '<STR_LIT>' in resp_cc and resp_cc['<STR_LIT>'].isdigit():<EOL><INDENT>freshness_lifetime = int(resp_cc['<STR_LIT>'])<EOL><DEDENT>elif '<STR_LIT>' in headers:<EOL><INDENT>expires = parsedate_tz(headers['<STR_LIT>'])<EOL>if expires is not None:<EOL><INDENT>expire_time = calendar.timegm(expires) - date<EOL>freshness_lifetime = max(<NUM_LIT:0>, expire_time)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in cc:<EOL><INDENT>try:<EOL><INDENT>freshness_lifetime = int(cc['<STR_LIT>'])<EOL><DEDENT>except ValueError:<EOL><INDENT>freshness_lifetime = <NUM_LIT:0><EOL><DEDENT><DEDENT>if '<STR_LIT>' in cc:<EOL><INDENT>try:<EOL><INDENT>min_fresh = int(cc['<STR_LIT>'])<EOL><DEDENT>except ValueError:<EOL><INDENT>min_fresh = <NUM_LIT:0><EOL><DEDENT>current_age += min_fresh<EOL><DEDENT>fresh = (freshness_lifetime > current_age)<EOL>if fresh:<EOL><INDENT>return resp<EOL><DEDENT>if '<STR_LIT>' not in headers:<EOL><INDENT>self.cache.delete(cache_url)<EOL><DEDENT>return False<EOL>

Return a cached response if it exists in the cache, otherwise
return False.


def cache_response(self, request, response, body=None):

<EOL>if response.status not in [<NUM_LIT:200>, <NUM_LIT>]:<EOL><INDENT>return<EOL><DEDENT>response_headers = CaseInsensitiveDict(response.headers)<EOL>cc_req = self.parse_cache_control(request.headers)<EOL>cc = self.parse_cache_control(response_headers)<EOL>cache_url = self.cache_url(request.url)<EOL>no_store = cc.get('<STR_LIT>') or cc_req.get('<STR_LIT>')<EOL>if no_store and self.cache.get(cache_url):<EOL><INDENT>self.cache.delete(cache_url)<EOL><DEDENT>if self.cache_etags and '<STR_LIT>' in response_headers:<EOL><INDENT>self.cache.set(<EOL>cache_url,<EOL>self.serializer.dumps(request, response, body=body),<EOL>)<EOL><DEDENT>elif '<STR_LIT:date>' in response_headers:<EOL><INDENT>if cc and cc.get('<STR_LIT>'):<EOL><INDENT>if int(cc['<STR_LIT>']) > <NUM_LIT:0>:<EOL><INDENT>self.cache.set(<EOL>cache_url,<EOL>self.serializer.dumps(request, response, body=body),<EOL>)<EOL><DEDENT><DEDENT>elif '<STR_LIT>' in response_headers:<EOL><INDENT>if response_headers['<STR_LIT>']:<EOL><INDENT>self.cache.set(<EOL>cache_url,<EOL>self.serializer.dumps(request, response, body=body),<EOL>)<EOL><DEDENT><DEDENT><DEDENT>

Algorithm for caching requests.

This assumes a requests Response object.


def update_cached_response(self, request, response):

cache_url = self.cache_url(request.url)<EOL>cached_response = self.serializer.loads(request, self.cache.get(cache_url))<EOL>if not cached_response:<EOL><INDENT>return response<EOL><DEDENT>excluded_headers = [<EOL>"<STR_LIT>",<EOL>]<EOL>cached_response.headers.update(<EOL>dict((k, v) for k, v in response.headers.items()<EOL>if k.lower() not in excluded_headers)<EOL>)<EOL>cached_response.status = <NUM_LIT:200><EOL>self.cache.set(<EOL>cache_url,<EOL>self.serializer.dumps(request, cached_response),<EOL>)<EOL>return cached_response<EOL>

On a 304 we will get a new set of headers that we want to
        update our cached value with, assuming we have one.

        This should only ever be called when we've sent an ETag and
        gotten a 304 as the response.


if request.method == '<STR_LIT:GET>':<EOL><INDENT>cached_response = self.controller.cached_request(request)<EOL>if cached_response:<EOL><INDENT>return self.build_response(request, cached_response, from_cache=True)<EOL><DEDENT>request.headers.update(self.controller.conditional_headers(request))<EOL><DEDENT>resp = super(CacheControlAdapter, self).send(request, **kw)<EOL>return resp<EOL>

Send a request. Use the request information to see if it
exists in the cache and cache the response if we need to and can.


def build_response(self, request, response, from_cache=False):

if not from_cache and request.method == '<STR_LIT:GET>':<EOL><INDENT>if response.status == <NUM_LIT>:<EOL><INDENT>cached_response = self.controller.update_cached_response(<EOL>request, response<EOL>)<EOL>if cached_response is not response:<EOL><INDENT>from_cache = True<EOL><DEDENT>response.read(decode_content=False)<EOL>response.release_conn()<EOL>response = cached_response<EOL><DEDENT>else:<EOL><INDENT>if self.heuristic:<EOL><INDENT>response = self.heuristic.apply(response)<EOL><DEDENT>response._fp = CallbackFileWrapper(<EOL>response._fp,<EOL>functools.partial(<EOL>self.controller.cache_response,<EOL>request,<EOL>response,<EOL>)<EOL>)<EOL><DEDENT><DEDENT>resp = super(CacheControlAdapter, self).build_response(<EOL>request, response<EOL>)<EOL>if request.method in self.invalidating_methods and resp.ok:<EOL><INDENT>cache_url = self.controller.cache_url(request.url)<EOL>self.cache.delete(cache_url)<EOL><DEDENT>resp.from_cache = from_cache<EOL>return resp<EOL>

Build a response by making a request or using the cache.

This will end up calling send and returning a potentially
cached response


if hasattr(td, '<STR_LIT>'):<EOL><INDENT>return td.total_seconds()<EOL><DEDENT>ms = td.microseconds<EOL>secs = (td.seconds + td.days * <NUM_LIT> * <NUM_LIT>)<EOL>return (ms + secs * <NUM_LIT:10>**<NUM_LIT:6>) / <NUM_LIT:10>**<NUM_LIT:6><EOL>


for key in self.conn.keys():<EOL><INDENT>self.conn.delete(key)<EOL><DEDENT>

Helper for clearing all the keys in a database. Use with
        caution!


return '<STR_LIT>'<EOL>

Return a valid 1xx warning header value describing the cache adjustments.

The response is provided too allow warnings like 113
http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need
to explicitly say response is over 24 hours old.


return {}<EOL>

Update the response headers with any new headers.

        NOTE: This SHOULD always include some Warning header to
              signify that the response was cached by the client, not
              by way of the provided headers.


try:<EOL><INDENT>return IPv4Address(address)<EOL><DEDENT>except (AddressValueError, NetmaskValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return IPv6Address(address)<EOL><DEDENT>except (AddressValueError, NetmaskValueError):<EOL><INDENT>pass<EOL><DEDENT>if isinstance(address, bytes):<EOL><INDENT>raise AddressValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % address)<EOL><DEDENT>raise ValueError('<STR_LIT>' %<EOL>address)<EOL>

Take an IP string/int and return an object of the correct type.

    Args:
        address: A string or integer, the IP address.  Either IPv4 or
          IPv6 addresses may be supplied; integers less than 2**32 will
          be considered to be IPv4 by default.

    Returns:
        An IPv4Address or IPv6Address object.

    Raises:
        ValueError: if the *address* passed isn't either a v4 or a v6
          address


try:<EOL><INDENT>return IPv4Network(address, strict)<EOL><DEDENT>except (AddressValueError, NetmaskValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return IPv6Network(address, strict)<EOL><DEDENT>except (AddressValueError, NetmaskValueError):<EOL><INDENT>pass<EOL><DEDENT>raise ValueError('<STR_LIT>' %<EOL>address)<EOL>

Take an IP string/int and return an object of the correct type.

    Args:
        address: A string or integer, the IP network.  Either IPv4 or
          IPv6 networks may be supplied; integers less than 2**32 will
          be considered to be IPv4 by default.

    Returns:
        An IPv4Network or IPv6Network object.

    Raises:
        ValueError: if the string passed isn't either a v4 or a v6
          address. Or if the network has host bits set.


try:<EOL><INDENT>return IPv4Interface(address)<EOL><DEDENT>except (AddressValueError, NetmaskValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return IPv6Interface(address)<EOL><DEDENT>except (AddressValueError, NetmaskValueError):<EOL><INDENT>pass<EOL><DEDENT>raise ValueError('<STR_LIT>' %<EOL>address)<EOL>

Take an IP string/int and return an object of the correct type.

    Args:
        address: A string or integer, the IP address.  Either IPv4 or
          IPv6 addresses may be supplied; integers less than 2**32 will
          be considered to be IPv4 by default.

    Returns:
        An IPv4Interface or IPv6Interface object.

    Raises:
        ValueError: if the string passed isn't either a v4 or a v6
          address.

    Notes:
        The IPv?Interface classes describe an Address on a particular
        Network, so they're basically a combination of both the Address
        and Network classes.


try:<EOL><INDENT>return _compat_to_bytes(address, <NUM_LIT:4>, '<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Represent an address as 4 packed bytes in network (big-endian) order.

    Args:
        address: An integer representation of an IPv4 IP address.

    Returns:
        The integer address packed as 4 bytes in network (big-endian) order.

    Raises:
        ValueError: If the integer is negative or too large to be an
          IPv4 IP address.


try:<EOL><INDENT>return _compat_to_bytes(address, <NUM_LIT:16>, '<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Represent an address as 16 packed bytes in network (big-endian) order.

    Args:
        address: An integer representation of an IPv6 IP address.

    Returns:
        The integer address packed as 16 bytes in network (big-endian) order.


addr = _compat_str(address).split('<STR_LIT:/>')<EOL>if len(addr) > <NUM_LIT:2>:<EOL><INDENT>raise AddressValueError("<STR_LIT>" % address)<EOL><DEDENT>return addr<EOL>

Helper to split the netmask and raise AddressValueError if needed


first = last = addresses[<NUM_LIT:0>]<EOL>for ip in addresses[<NUM_LIT:1>:]:<EOL><INDENT>if ip._ip == last._ip + <NUM_LIT:1>:<EOL><INDENT>last = ip<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return (first, last)<EOL>

Find a sequence of IPv#Address.

    Args:
        addresses: a list of IPv#Address objects.

    Returns:
        A tuple containing the first and last IP addresses in the sequence.


if number == <NUM_LIT:0>:<EOL><INDENT>return bits<EOL><DEDENT>for i in range(bits):<EOL><INDENT>if (number >> i) & <NUM_LIT:1>:<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return bits<EOL>

Count the number of zero bits on the right hand side.

    Args:
        number: an integer.
        bits: maximum number of bits to count.

    Returns:
        The number of zero bits on the right hand side of the number.


if (not (isinstance(first, _BaseAddress) and<EOL>isinstance(last, _BaseAddress))):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if first.version != last.version:<EOL><INDENT>raise TypeError("<STR_LIT>" %<EOL>(first, last))<EOL><DEDENT>if first > last:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if first.version == <NUM_LIT:4>:<EOL><INDENT>ip = IPv4Network<EOL><DEDENT>elif first.version == <NUM_LIT:6>:<EOL><INDENT>ip = IPv6Network<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>ip_bits = first._max_prefixlen<EOL>first_int = first._ip<EOL>last_int = last._ip<EOL>while first_int <= last_int:<EOL><INDENT>nbits = min(_count_righthand_zero_bits(first_int, ip_bits),<EOL>_compat_bit_length(last_int - first_int + <NUM_LIT:1>) - <NUM_LIT:1>)<EOL>net = ip('<STR_LIT>' % (first, ip_bits - nbits))<EOL>yield net<EOL>first_int += <NUM_LIT:1> << nbits<EOL>if first_int - <NUM_LIT:1> == ip._ALL_ONES:<EOL><INDENT>break<EOL><DEDENT>first = first.__class__(first_int)<EOL><DEDENT>

Summarize a network range given the first and last IP addresses.

    Example:
        >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
        ...                              IPv4Address('192.0.2.130')))
        ...                                #doctest: +NORMALIZE_WHITESPACE
        [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
         IPv4Network('192.0.2.130/32')]

    Args:
        first: the first IPv4Address or IPv6Address in the range.
        last: the last IPv4Address or IPv6Address in the range.

    Returns:
        An iterator of the summarized IPv(4|6) network objects.

    Raise:
        TypeError:
            If the first and last objects are not IP addresses.
            If the first and last objects are not the same version.
        ValueError:
            If the last object is not greater than the first.
            If the version of the first address is not 4 or 6.


while True:<EOL><INDENT>last_addr = None<EOL>ret_array = []<EOL>optimized = False<EOL>for cur_addr in addresses:<EOL><INDENT>if not ret_array:<EOL><INDENT>last_addr = cur_addr<EOL>ret_array.append(cur_addr)<EOL><DEDENT>elif (cur_addr.network_address >= last_addr.network_address and<EOL>cur_addr.broadcast_address <= last_addr.broadcast_address):<EOL><INDENT>optimized = True<EOL><DEDENT>elif cur_addr == list(last_addr.supernet().subnets())[<NUM_LIT:1>]:<EOL><INDENT>ret_array[-<NUM_LIT:1>] = last_addr = last_addr.supernet()<EOL>optimized = True<EOL><DEDENT>else:<EOL><INDENT>last_addr = cur_addr<EOL>ret_array.append(cur_addr)<EOL><DEDENT><DEDENT>addresses = ret_array<EOL>if not optimized:<EOL><INDENT>return addresses<EOL><DEDENT><DEDENT>

Loops through the addresses, collapsing concurrent netblocks.

    Example:

        ip1 = IPv4Network('192.0.2.0/26')
        ip2 = IPv4Network('192.0.2.64/26')
        ip3 = IPv4Network('192.0.2.128/26')
        ip4 = IPv4Network('192.0.2.192/26')

        _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
          [IPv4Network('192.0.2.0/24')]

        This shouldn't be called directly; it is called via
          collapse_addresses([]).

    Args:
        addresses: A list of IPv4Network's or IPv6Network's

    Returns:
        A list of IPv4Network's or IPv6Network's depending on what we were
        passed.


i = <NUM_LIT:0><EOL>addrs = []<EOL>ips = []<EOL>nets = []<EOL>for ip in addresses:<EOL><INDENT>if isinstance(ip, _BaseAddress):<EOL><INDENT>if ips and ips[-<NUM_LIT:1>]._version != ip._version:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>ip, ips[-<NUM_LIT:1>]))<EOL><DEDENT>ips.append(ip)<EOL><DEDENT>elif ip._prefixlen == ip._max_prefixlen:<EOL><INDENT>if ips and ips[-<NUM_LIT:1>]._version != ip._version:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>ip, ips[-<NUM_LIT:1>]))<EOL><DEDENT>try:<EOL><INDENT>ips.append(ip.ip)<EOL><DEDENT>except AttributeError:<EOL><INDENT>ips.append(ip.network_address)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if nets and nets[-<NUM_LIT:1>]._version != ip._version:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>ip, nets[-<NUM_LIT:1>]))<EOL><DEDENT>nets.append(ip)<EOL><DEDENT><DEDENT>ips = sorted(set(ips))<EOL>nets = sorted(set(nets))<EOL>while i < len(ips):<EOL><INDENT>(first, last) = _find_address_range(ips[i:])<EOL>i = ips.index(last) + <NUM_LIT:1><EOL>addrs.extend(summarize_address_range(first, last))<EOL><DEDENT>return iter(_collapse_addresses_recursive(sorted(<EOL>addrs + nets, key=_BaseNetwork._get_networks_key)))<EOL>

Collapse a list of IP objects.

    Example:
        collapse_addresses([IPv4Network('192.0.2.0/25'),
                            IPv4Network('192.0.2.128/25')]) ->
                           [IPv4Network('192.0.2.0/24')]

    Args:
        addresses: An iterator of IPv4Network or IPv6Network objects.

    Returns:
        An iterator of the collapsed IPv(4|6)Network objects.

    Raises:
        TypeError: If passed a list of mixed version objects.


if isinstance(obj, _BaseNetwork):<EOL><INDENT>return obj._get_networks_key()<EOL><DEDENT>elif isinstance(obj, _BaseAddress):<EOL><INDENT>return obj._get_address_key()<EOL><DEDENT>return NotImplemented<EOL>

Return a key suitable for sorting between networks and addresses.

    Address and Network objects are not sortable by default; they're
    fundamentally different so the expression

        IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')

    doesn't make any sense.  There are some times however, where you may wish
    to have ipaddress sort these for you anyway. If you need to do this, you
    can use this function as the key= argument to sorted().

    Args:
      obj: either a Network or Address object.
    Returns:
      appropriate key.


return self._explode_shorthand_ip_string()<EOL>

Return the longhand version of the IP address as a string.


return _compat_str(self)<EOL>

Return the shorthand version of the IP address as a string.


if prefixlen is None:<EOL><INDENT>prefixlen = self._prefixlen<EOL><DEDENT>return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)<EOL>

Turn the prefix length netmask into a int for comparison.

        Args:
            prefixlen: An integer, the prefix length.

        Returns:
            An integer.


def _prefix_from_ip_int(self, ip_int, mask=<NUM_LIT:32>):

return mask - _count_righthand_zero_bits(ip_int, mask)<EOL>

Return prefix length from the decimal netmask.

        Args:
            ip_int: An integer, the IP address.
            mask: The netmask.  Defaults to 32.

        Returns:
            An integer, the prefix length.


if not prefixlen:<EOL><INDENT>prefixlen = self._prefixlen<EOL><DEDENT>return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))<EOL>

Turn a prefix length into a dotted decimal string.

        Args:
            prefixlen: An integer, the netmask prefix length.

        Returns:
            A string, the dotted decimal netmask string.


network = int(self.network_address)<EOL>broadcast = int(self.broadcast_address)<EOL>for x in _compat_range(network + <NUM_LIT:1>, broadcast):<EOL><INDENT>yield self._address_class(x)<EOL><DEDENT>

Generate Iterator over usable hosts in a network.

        This is like __iter__ except it doesn't return the network
        or broadcast addresses.


return self.network_address in other or (<EOL>self.broadcast_address in other or (<EOL>other.network_address in self or (<EOL>other.broadcast_address in self)))<EOL>

Tell if self is partly contained in other.


return int(self.broadcast_address) - int(self.network_address) + <NUM_LIT:1><EOL>


if not self._version == other._version:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>self, other))<EOL><DEDENT>if not isinstance(other, _BaseNetwork):<EOL><INDENT>raise TypeError("<STR_LIT>" % other)<EOL><DEDENT>if not (other.network_address >= self.network_address and<EOL>other.broadcast_address <= self.broadcast_address):<EOL><INDENT>raise ValueError('<STR_LIT>' % (other, self))<EOL><DEDENT>if other == self:<EOL><INDENT>raise StopIteration<EOL><DEDENT>other = other.__class__('<STR_LIT>' % (other.network_address,<EOL>other.prefixlen))<EOL>s1, s2 = self.subnets()<EOL>while s1 != other and s2 != other:<EOL><INDENT>if (other.network_address >= s1.network_address and<EOL>other.broadcast_address <= s1.broadcast_address):<EOL><INDENT>yield s2<EOL>s1, s2 = s1.subnets()<EOL><DEDENT>elif (other.network_address >= s2.network_address and<EOL>other.broadcast_address <= s2.broadcast_address):<EOL><INDENT>yield s1<EOL>s1, s2 = s2.subnets()<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError('<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(s1, s2, other))<EOL><DEDENT><DEDENT>if s1 == other:<EOL><INDENT>yield s2<EOL><DEDENT>elif s2 == other:<EOL><INDENT>yield s1<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError('<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(s1, s2, other))<EOL><DEDENT>

Remove an address from a larger block.

        For example:

            addr1 = ip_network('192.0.2.0/28')
            addr2 = ip_network('192.0.2.1/32')
            addr1.address_exclude(addr2) =
                [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
                IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]

        or IPv6:

            addr1 = ip_network('2001:db8::1/32')
            addr2 = ip_network('2001:db8::1/128')
            addr1.address_exclude(addr2) =
                [ip_network('2001:db8::1/128'),
                ip_network('2001:db8::2/127'),
                ip_network('2001:db8::4/126'),
                ip_network('2001:db8::8/125'),
                ...
                ip_network('2001:db8:8000::/33')]

        Args:
            other: An IPv4Network or IPv6Network object of the same type.

        Returns:
            An iterator of the IPv(4|6)Network objects which is self
            minus other.

        Raises:
            TypeError: If self and other are of difffering address
              versions, or if other is not a network object.
            ValueError: If other is not completely contained by self.


<EOL>if self._version != other._version:<EOL><INDENT>raise TypeError('<STR_LIT>' % (<EOL>self, other))<EOL><DEDENT>if self.network_address < other.network_address:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>if self.network_address > other.network_address:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>if self.netmask < other.netmask:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>if self.netmask > other.netmask:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>return <NUM_LIT:0><EOL>

Compare two IP objects.

        This is only concerned about the comparison of the integer
        representation of the network addresses.  This means that the
        host bits aren't considered at all in this method.  If you want
        to compare host bits, you can easily enough do a
        'HostA._ip < HostB._ip'

        Args:
            other: An IP object.

        Returns:
            If the IP versions of self and other are the same, returns:

            -1 if self < other:
              eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
              IPv6Network('2001:db8::1000/124') <
                  IPv6Network('2001:db8::2000/124')
            0 if self == other
              eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
              IPv6Network('2001:db8::1000/124') ==
                  IPv6Network('2001:db8::1000/124')
            1 if self > other
              eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
                  IPv6Network('2001:db8::2000/124') >
                      IPv6Network('2001:db8::1000/124')

          Raises:
              TypeError if the IP versions are different.


return (self._version, self.network_address, self.netmask)<EOL>

Network-only key function.

        Returns an object that identifies this address' network and
        netmask. This function is a suitable "key" argument for sorted()
        and list.sort().


def subnets(self, prefixlen_diff=<NUM_LIT:1>, new_prefix=None):

if self._prefixlen == self._max_prefixlen:<EOL><INDENT>yield self<EOL>return<EOL><DEDENT>if new_prefix is not None:<EOL><INDENT>if new_prefix < self._prefixlen:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if prefixlen_diff != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>prefixlen_diff = new_prefix - self._prefixlen<EOL><DEDENT>if prefixlen_diff < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>new_prefixlen = self._prefixlen + prefixlen_diff<EOL>if not self._is_valid_netmask(str(new_prefixlen)):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' % (<EOL>new_prefixlen, self))<EOL><DEDENT>first = self.__class__('<STR_LIT>' %<EOL>(self.network_address,<EOL>self._prefixlen + prefixlen_diff))<EOL>yield first<EOL>current = first<EOL>while True:<EOL><INDENT>broadcast = current.broadcast_address<EOL>if broadcast == self.broadcast_address:<EOL><INDENT>return<EOL><DEDENT>new_addr = self._address_class(int(broadcast) + <NUM_LIT:1>)<EOL>current = self.__class__('<STR_LIT>' % (new_addr,<EOL>new_prefixlen))<EOL>yield current<EOL><DEDENT>

The subnets which join to make the current subnet.

        In the case that self contains only one IP
        (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
        for IPv6), yield an iterator with just ourself.

        Args:
            prefixlen_diff: An integer, the amount the prefix length
              should be increased by. This should not be set if
              new_prefix is also set.
            new_prefix: The desired new prefix length. This must be a
              larger number (smaller prefix) than the existing prefix.
              This should not be set if prefixlen_diff is also set.

        Returns:
            An iterator of IPv(4|6) objects.

        Raises:
            ValueError: The prefixlen_diff is too small or too large.
                OR
            prefixlen_diff and new_prefix are both set or new_prefix
              is a smaller number than the current prefix (smaller
              number means a larger network)


def supernet(self, prefixlen_diff=<NUM_LIT:1>, new_prefix=None):

if self._prefixlen == <NUM_LIT:0>:<EOL><INDENT>return self<EOL><DEDENT>if new_prefix is not None:<EOL><INDENT>if new_prefix > self._prefixlen:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if prefixlen_diff != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>prefixlen_diff = self._prefixlen - new_prefix<EOL><DEDENT>if self.prefixlen - prefixlen_diff < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' %<EOL>(self.prefixlen, prefixlen_diff))<EOL><DEDENT>t = self.__class__('<STR_LIT>' % (self.network_address,<EOL>self.prefixlen - prefixlen_diff),<EOL>strict=False)<EOL>return t.__class__('<STR_LIT>' % (t.network_address, t.prefixlen))<EOL>

The supernet containing the current network.

        Args:
            prefixlen_diff: An integer, the amount the prefix length of
              the network should be decreased by.  For example, given a
              /24 network and a prefixlen_diff of 3, a supernet with a
              /21 netmask is returned.

        Returns:
            An IPv4 network object.

        Raises:
            ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
              a negative prefix length.
                OR
            If prefixlen_diff and new_prefix are both set or new_prefix is a
              larger number than the current prefix (larger number means a
              smaller network)


return (self.network_address.is_multicast and<EOL>self.broadcast_address.is_multicast)<EOL>

Test if the address is reserved for multicast use.

        Returns:
            A boolean, True if the address is a multicast address.
            See RFC 2373 2.7 for details.


return (self.network_address.is_reserved and<EOL>self.broadcast_address.is_reserved)<EOL>

Test if the address is otherwise IETF reserved.

        Returns:
            A boolean, True if the address is within one of the
            reserved IPv6 Network ranges.


return (self.network_address.is_link_local and<EOL>self.broadcast_address.is_link_local)<EOL>

Test if the address is reserved for link-local.

        Returns:
            A boolean, True if the address is reserved per RFC 4291.


return (self.network_address.is_private and<EOL>self.broadcast_address.is_private)<EOL>

Test if this address is allocated for private networks.

        Returns:
            A boolean, True if the address is reserved per RFC 4193.


return (self.network_address.is_unspecified and<EOL>self.broadcast_address.is_unspecified)<EOL>

Test if the address is unspecified.

        Returns:
            A boolean, True if this is the unspecified address as defined in
            RFC 2373 2.5.2.


return (self.network_address.is_loopback and<EOL>self.broadcast_address.is_loopback)<EOL>

Test if the address is a loopback address.

        Returns:
            A boolean, True if the address is a loopback address as defined in
            RFC 2373 2.5.3.


if not ip_str:<EOL><INDENT>raise AddressValueError('<STR_LIT>')<EOL><DEDENT>octets = ip_str.split('<STR_LIT:.>')<EOL>if len(octets) != <NUM_LIT:4>:<EOL><INDENT>raise AddressValueError("<STR_LIT>" % ip_str)<EOL><DEDENT>try:<EOL><INDENT>bvs = map(self._parse_octet, octets)<EOL>return _compat_int_from_byte_vals(bvs, '<STR_LIT>')<EOL><DEDENT>except ValueError as exc:<EOL><INDENT>raise AddressValueError("<STR_LIT>" % (exc, ip_str))<EOL><DEDENT>

Turn the given IP string into an integer for comparison.

        Args:
            ip_str: A string, the IP ip_str.

        Returns:
            The IP ip_str as an integer.

        Raises:
            AddressValueError: if ip_str isn't a valid IPv4 Address.


if not octet_str:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not self._DECIMAL_DIGITS.issuperset(octet_str):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % octet_str)<EOL><DEDENT>if len(octet_str) > <NUM_LIT:3>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % octet_str)<EOL><DEDENT>octet_int = int(octet_str, <NUM_LIT:10>)<EOL>if octet_int > <NUM_LIT:7> and octet_str[<NUM_LIT:0>] == '<STR_LIT:0>':<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % octet_str)<EOL><DEDENT>if octet_int > <NUM_LIT:255>:<EOL><INDENT>raise ValueError("<STR_LIT>" % octet_int)<EOL><DEDENT>return octet_int<EOL>

Convert a decimal octet into an integer.

        Args:
            octet_str: A string, the number to parse.

        Returns:
            The octet as an integer.

        Raises:
            ValueError: if the octet isn't strictly a decimal from [0..255].


return '<STR_LIT:.>'.join(_compat_str(struct.unpack(b'<STR_LIT>', b)[<NUM_LIT:0>]<EOL>if isinstance(b, bytes)<EOL>else b)<EOL>for b in _compat_to_bytes(ip_int, <NUM_LIT:4>, '<STR_LIT>'))<EOL>

Turns a 32-bit integer into dotted decimal notation.

        Args:
            ip_int: An integer, the IP address.

        Returns:
            The IP address as a string in dotted decimal notation.


mask = netmask.split('<STR_LIT:.>')<EOL>if len(mask) == <NUM_LIT:4>:<EOL><INDENT>try:<EOL><INDENT>for x in mask:<EOL><INDENT>if int(x) not in self._valid_mask_octets:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>for idx, y in enumerate(mask):<EOL><INDENT>if idx > <NUM_LIT:0> and y > mask[idx - <NUM_LIT:1>]:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL><DEDENT>try:<EOL><INDENT>netmask = int(netmask)<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>return <NUM_LIT:0> <= netmask <= self._max_prefixlen<EOL>

Verify that the netmask is valid.

        Args:
            netmask: A string, either a prefix or dotted decimal
              netmask.

        Returns:
            A boolean, True if the prefix represents a valid IPv4
            netmask.


bits = ip_str.split('<STR_LIT:.>')<EOL>try:<EOL><INDENT>parts = [x for x in map(int, bits) if x in self._valid_mask_octets]<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>if len(parts) != len(bits):<EOL><INDENT>return False<EOL><DEDENT>if parts[<NUM_LIT:0>] < parts[-<NUM_LIT:1>]:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Test if the IP string is a hostmask (rather than a netmask).

        Args:
            ip_str: A string, the potential hostmask.

        Returns:
            A boolean, True if the IP string is a hostmask.


_BaseAddress.__init__(self, address)<EOL>_BaseV4.__init__(self, address)<EOL>if isinstance(address, _compat_int_types):<EOL><INDENT>self._check_int_address(address)<EOL>self._ip = address<EOL>return<EOL><DEDENT>if isinstance(address, bytes):<EOL><INDENT>self._check_packed_address(address, <NUM_LIT:4>)<EOL>bvs = _compat_bytes_to_byte_vals(address)<EOL>self._ip = _compat_int_from_byte_vals(bvs, '<STR_LIT>')<EOL>return<EOL><DEDENT>addr_str = _compat_str(address)<EOL>self._ip = self._ip_int_from_string(addr_str)<EOL>

Args:
    address: A string or integer representing the IP

      Additionally, an integer can be passed, so
      IPv4Address('192.0.2.1') == IPv4Address(3221225985).
      or, more generally
      IPv4Address(int(IPv4Address('192.0.2.1'))) ==
        IPv4Address('192.0.2.1')

Raises:
    AddressValueError: If ipaddress isn't a valid IPv4 address.


return v4_int_to_packed(self._ip)<EOL>

The binary representation of this address.


reserved_network = IPv4Network('<STR_LIT>')<EOL>return self in reserved_network<EOL>

Test if the address is otherwise IETF reserved.

         Returns:
             A boolean, True if the address is within the
             reserved IPv4 Network range.


private_10 = IPv4Network('<STR_LIT>')<EOL>private_172 = IPv4Network('<STR_LIT>')<EOL>private_192 = IPv4Network('<STR_LIT>')<EOL>return (self in private_10 or<EOL>self in private_172 or<EOL>self in private_192)<EOL>

Test if this address is allocated for private networks.

        Returns:
            A boolean, True if the address is reserved per RFC 1918.


multicast_network = IPv4Network('<STR_LIT>')<EOL>return self in multicast_network<EOL>

Test if the address is reserved for multicast use.

        Returns:
            A boolean, True if the address is multicast.
            See RFC 3171 for details.


unspecified_address = IPv4Address('<STR_LIT>')<EOL>return self == unspecified_address<EOL>

Test if the address is unspecified.

        Returns:
            A boolean, True if this is the unspecified address as defined in
            RFC 5735 3.


loopback_network = IPv4Network('<STR_LIT>')<EOL>return self in loopback_network<EOL>

Test if the address is a loopback address.

        Returns:
            A boolean, True if the address is a loopback per RFC 3330.


linklocal_network = IPv4Network('<STR_LIT>')<EOL>return self in linklocal_network<EOL>

Test if the address is reserved for link-local.

        Returns:
            A boolean, True if the address is link-local per RFC 3927.


def __init__(self, address, strict=True):

_BaseV4.__init__(self, address)<EOL>_BaseNetwork.__init__(self, address)<EOL>if isinstance(address, bytes):<EOL><INDENT>self.network_address = IPv4Address(address)<EOL>self._prefixlen = self._max_prefixlen<EOL>self.netmask = IPv4Address(self._ALL_ONES)<EOL>return<EOL><DEDENT>if isinstance(address, _compat_int_types):<EOL><INDENT>self.network_address = IPv4Address(address)<EOL>self._prefixlen = self._max_prefixlen<EOL>self.netmask = IPv4Address(self._ALL_ONES)<EOL>return<EOL><DEDENT>addr = _split_optional_netmask(address)<EOL>self.network_address = IPv4Address(self._ip_int_from_string(addr[<NUM_LIT:0>]))<EOL>if len(addr) == <NUM_LIT:2>:<EOL><INDENT>mask = addr[<NUM_LIT:1>].split('<STR_LIT:.>')<EOL>if len(mask) == <NUM_LIT:4>:<EOL><INDENT>if self._is_valid_netmask(addr[<NUM_LIT:1>]):<EOL><INDENT>self.netmask = IPv4Address(self._ip_int_from_string(<EOL>addr[<NUM_LIT:1>]))<EOL><DEDENT>elif self._is_hostmask(addr[<NUM_LIT:1>]):<EOL><INDENT>self.netmask = IPv4Address(<EOL>self._ip_int_from_string(addr[<NUM_LIT:1>]) ^ self._ALL_ONES)<EOL><DEDENT>else:<EOL><INDENT>raise NetmaskValueError('<STR_LIT>'<EOL>% addr[<NUM_LIT:1>])<EOL><DEDENT>self._prefixlen = self._prefix_from_ip_int(int(self.netmask))<EOL><DEDENT>else:<EOL><INDENT>if not self._is_valid_netmask(addr[<NUM_LIT:1>]):<EOL><INDENT>raise NetmaskValueError('<STR_LIT>'<EOL>% addr[<NUM_LIT:1>])<EOL><DEDENT>self._prefixlen = int(addr[<NUM_LIT:1>])<EOL>self.netmask = IPv4Address(self._ip_int_from_prefix(<EOL>self._prefixlen))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._prefixlen = self._max_prefixlen<EOL>self.netmask = IPv4Address(self._ip_int_from_prefix(<EOL>self._prefixlen))<EOL><DEDENT>if strict:<EOL><INDENT>if (IPv4Address(int(self.network_address) & int(self.netmask)) !=<EOL>self.network_address):<EOL><INDENT>raise ValueError('<STR_LIT>' % self)<EOL><DEDENT><DEDENT>self.network_address = IPv4Address(int(self.network_address) &<EOL>int(self.netmask))<EOL>if self._prefixlen == (self._max_prefixlen - <NUM_LIT:1>):<EOL><INDENT>self.hosts = self.__iter__<EOL><DEDENT>

Instantiate a new IPv4 network object.

        Args:
            address: A string or integer representing the IP [& network].
              '192.0.2.0/24'
              '192.0.2.0/255.255.255.0'
              '192.0.0.2/0.0.0.255'
              are all functionally the same in IPv4. Similarly,
              '192.0.2.1'
              '192.0.2.1/255.255.255.255'
              '192.0.2.1/32'
              are also functionaly equivalent. That is to say, failing to
              provide a subnetmask will create an object with a mask of /32.

              If the mask (portion after the / in the argument) is given in
              dotted quad form, it is treated as a netmask if it starts with a
              non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
              starts with a zero field (e.g. 0.255.255.255 == /8), with the
              single exception of an all-zero mask which is treated as a
              netmask == /0. If no mask is given, a default of /32 is used.

              Additionally, an integer can be passed, so
              IPv4Network('192.0.2.1') == IPv4Network(3221225985)
              or, more generally
              IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
                IPv4Interface('192.0.2.1')

        Raises:
            AddressValueError: If ipaddress isn't a valid IPv4 address.
            NetmaskValueError: If the netmask isn't valid for
              an IPv4 address.
            ValueError: If strict is True and a network address is not
              supplied.


if not ip_str:<EOL><INDENT>raise AddressValueError('<STR_LIT>')<EOL><DEDENT>parts = ip_str.split('<STR_LIT::>')<EOL>_min_parts = <NUM_LIT:3><EOL>if len(parts) < _min_parts:<EOL><INDENT>msg = "<STR_LIT>" % (_min_parts, ip_str)<EOL>raise AddressValueError(msg)<EOL><DEDENT>if '<STR_LIT:.>' in parts[-<NUM_LIT:1>]:<EOL><INDENT>try:<EOL><INDENT>ipv4_int = IPv4Address(parts.pop())._ip<EOL><DEDENT>except AddressValueError as exc:<EOL><INDENT>raise AddressValueError("<STR_LIT>" % (exc, ip_str))<EOL><DEDENT>parts.append('<STR_LIT>' % ((ipv4_int >> <NUM_LIT:16>) & <NUM_LIT>))<EOL>parts.append('<STR_LIT>' % (ipv4_int & <NUM_LIT>))<EOL><DEDENT>_max_parts = self._HEXTET_COUNT + <NUM_LIT:1><EOL>if len(parts) > _max_parts:<EOL><INDENT>msg = ("<STR_LIT>" %<EOL>(_max_parts - <NUM_LIT:1>, ip_str))<EOL>raise AddressValueError(msg)<EOL><DEDENT>skip_index = None<EOL>for i in range(<NUM_LIT:1>, len(parts) - <NUM_LIT:1>):<EOL><INDENT>if not parts[i]:<EOL><INDENT>if skip_index is not None:<EOL><INDENT>msg = "<STR_LIT>" % ip_str<EOL>raise AddressValueError(msg)<EOL><DEDENT>skip_index = i<EOL><DEDENT><DEDENT>if skip_index is not None:<EOL><INDENT>parts_hi = skip_index<EOL>parts_lo = len(parts) - skip_index - <NUM_LIT:1><EOL>if not parts[<NUM_LIT:0>]:<EOL><INDENT>parts_hi -= <NUM_LIT:1><EOL>if parts_hi:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise AddressValueError(msg % ip_str)  <EOL><DEDENT><DEDENT>if not parts[-<NUM_LIT:1>]:<EOL><INDENT>parts_lo -= <NUM_LIT:1><EOL>if parts_lo:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise AddressValueError(msg % ip_str)  <EOL><DEDENT><DEDENT>parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)<EOL>if parts_skipped < <NUM_LIT:1>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise AddressValueError(msg % (self._HEXTET_COUNT - <NUM_LIT:1>, ip_str))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if len(parts) != self._HEXTET_COUNT:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))<EOL><DEDENT>if not parts[<NUM_LIT:0>]:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise AddressValueError(msg % ip_str)  <EOL><DEDENT>if not parts[-<NUM_LIT:1>]:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise AddressValueError(msg % ip_str)  <EOL><DEDENT>parts_hi = len(parts)<EOL>parts_lo = <NUM_LIT:0><EOL>parts_skipped = <NUM_LIT:0><EOL><DEDENT>try:<EOL><INDENT>ip_int = <NUM_LIT:0><EOL>for i in range(parts_hi):<EOL><INDENT>ip_int <<= <NUM_LIT:16><EOL>ip_int |= self._parse_hextet(parts[i])<EOL><DEDENT>ip_int <<= <NUM_LIT:16> * parts_skipped<EOL>for i in range(-parts_lo, <NUM_LIT:0>):<EOL><INDENT>ip_int <<= <NUM_LIT:16><EOL>ip_int |= self._parse_hextet(parts[i])<EOL><DEDENT>return ip_int<EOL><DEDENT>except ValueError as exc:<EOL><INDENT>raise AddressValueError("<STR_LIT>" % (exc, ip_str))<EOL><DEDENT>

Turn an IPv6 ip_str into an integer.

        Args:
            ip_str: A string, the IPv6 ip_str.

        Returns:
            An int, the IPv6 address

        Raises:
            AddressValueError: if ip_str isn't a valid IPv6 Address.


<EOL>if not self._HEX_DIGITS.issuperset(hextet_str):<EOL><INDENT>raise ValueError("<STR_LIT>" % hextet_str)<EOL><DEDENT>if len(hextet_str) > <NUM_LIT:4>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % hextet_str)<EOL><DEDENT>return int(hextet_str, <NUM_LIT:16>)<EOL>

Convert an IPv6 hextet string into an integer.

        Args:
            hextet_str: A string, the number to parse.

        Returns:
            The hextet as an integer.

        Raises:
            ValueError: if the input isn't strictly a hex number from
              [0..FFFF].


best_doublecolon_start = -<NUM_LIT:1><EOL>best_doublecolon_len = <NUM_LIT:0><EOL>doublecolon_start = -<NUM_LIT:1><EOL>doublecolon_len = <NUM_LIT:0><EOL>for index, hextet in enumerate(hextets):<EOL><INDENT>if hextet == '<STR_LIT:0>':<EOL><INDENT>doublecolon_len += <NUM_LIT:1><EOL>if doublecolon_start == -<NUM_LIT:1>:<EOL><INDENT>doublecolon_start = index<EOL><DEDENT>if doublecolon_len > best_doublecolon_len:<EOL><INDENT>best_doublecolon_len = doublecolon_len<EOL>best_doublecolon_start = doublecolon_start<EOL><DEDENT><DEDENT>else:<EOL><INDENT>doublecolon_len = <NUM_LIT:0><EOL>doublecolon_start = -<NUM_LIT:1><EOL><DEDENT><DEDENT>if best_doublecolon_len > <NUM_LIT:1>:<EOL><INDENT>best_doublecolon_end = (best_doublecolon_start +<EOL>best_doublecolon_len)<EOL>if best_doublecolon_end == len(hextets):<EOL><INDENT>hextets += ['<STR_LIT>']<EOL><DEDENT>hextets[best_doublecolon_start:best_doublecolon_end] = ['<STR_LIT>']<EOL>if best_doublecolon_start == <NUM_LIT:0>:<EOL><INDENT>hextets = ['<STR_LIT>'] + hextets<EOL><DEDENT><DEDENT>return hextets<EOL>

Compresses a list of hextets.

        Compresses a list of strings, replacing the longest continuous
        sequence of "0" in the list with "" and adding empty strings at
        the beginning or at the end of the string such that subsequently
        calling ":".join(hextets) will produce the compressed version of
        the IPv6 address.

        Args:
            hextets: A list of strings, the hextets to compress.

        Returns:
            A list of strings.


if ip_int is None:<EOL><INDENT>ip_int = int(self._ip)<EOL><DEDENT>if ip_int > self._ALL_ONES:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>hex_str = '<STR_LIT>' % ip_int<EOL>hextets = ['<STR_LIT>' % int(hex_str[x:x + <NUM_LIT:4>], <NUM_LIT:16>) for x in range(<NUM_LIT:0>, <NUM_LIT:32>, <NUM_LIT:4>)]<EOL>hextets = self._compress_hextets(hextets)<EOL>return '<STR_LIT::>'.join(hextets)<EOL>

Turns a 128-bit integer into hexadecimal notation.

        Args:
            ip_int: An integer, the IP address.

        Returns:
            A string, the hexadecimal representation of the address.

        Raises:
            ValueError: The address is bigger than 128 bits of all ones.


if isinstance(self, IPv6Network):<EOL><INDENT>ip_str = _compat_str(self.network_address)<EOL><DEDENT>elif isinstance(self, IPv6Interface):<EOL><INDENT>ip_str = _compat_str(self.ip)<EOL><DEDENT>else:<EOL><INDENT>ip_str = _compat_str(self)<EOL><DEDENT>ip_int = self._ip_int_from_string(ip_str)<EOL>hex_str = '<STR_LIT>' % ip_int<EOL>parts = [hex_str[x:x + <NUM_LIT:4>] for x in range(<NUM_LIT:0>, <NUM_LIT:32>, <NUM_LIT:4>)]<EOL>if isinstance(self, (_BaseNetwork, IPv6Interface)):<EOL><INDENT>return '<STR_LIT>' % ('<STR_LIT::>'.join(parts), self._prefixlen)<EOL><DEDENT>return '<STR_LIT::>'.join(parts)<EOL>

Expand a shortened IPv6 address.

        Args:
            ip_str: A string, the IPv6 address.

        Returns:
            A string, the expanded IPv6 address.


_BaseAddress.__init__(self, address)<EOL>_BaseV6.__init__(self, address)<EOL>if isinstance(address, _compat_int_types):<EOL><INDENT>self._check_int_address(address)<EOL>self._ip = address<EOL>return<EOL><DEDENT>if isinstance(address, bytes):<EOL><INDENT>self._check_packed_address(address, <NUM_LIT:16>)<EOL>bvs = _compat_bytes_to_byte_vals(address)<EOL>self._ip = _compat_int_from_byte_vals(bvs, '<STR_LIT>')<EOL>return<EOL><DEDENT>addr_str = _compat_str(address)<EOL>self._ip = self._ip_int_from_string(addr_str)<EOL>

Instantiate a new IPv6 address object.

        Args:
            address: A string or integer representing the IP

              Additionally, an integer can be passed, so
              IPv6Address('2001:db8::') ==
                IPv6Address(42540766411282592856903984951653826560)
              or, more generally
              IPv6Address(int(IPv6Address('2001:db8::'))) ==
                IPv6Address('2001:db8::')

        Raises:
            AddressValueError: If address isn't a valid IPv6 address.


return v6_int_to_packed(self._ip)<EOL>


multicast_network = IPv6Network('<STR_LIT>')<EOL>return self in multicast_network<EOL>

Test if the address is reserved for multicast use.

        Returns:
            A boolean, True if the address is a multicast address.
            See RFC 2373 2.7 for details.


reserved_nets = [IPv6Network('<STR_LIT>'), IPv6Network('<STR_LIT>'),<EOL>IPv6Network('<STR_LIT>'), IPv6Network('<STR_LIT>'),<EOL>IPv6Network('<STR_LIT>'), IPv6Network('<STR_LIT>'),<EOL>IPv6Network('<STR_LIT>'), IPv6Network('<STR_LIT>'),<EOL>IPv6Network('<STR_LIT>'), IPv6Network('<STR_LIT>'),<EOL>IPv6Network('<STR_LIT>'), IPv6Network('<STR_LIT>'),<EOL>IPv6Network('<STR_LIT>'), IPv6Network('<STR_LIT>'),<EOL>IPv6Network('<STR_LIT>')]<EOL>return any(self in x for x in reserved_nets)<EOL>

Test if the address is otherwise IETF reserved.

        Returns:
            A boolean, True if the address is within one of the
            reserved IPv6 Network ranges.


linklocal_network = IPv6Network('<STR_LIT>')<EOL>return self in linklocal_network<EOL>

Test if the address is reserved for link-local.

        Returns:
            A boolean, True if the address is reserved per RFC 4291.