def versions_from_parentdir(parentdir_prefix, root, verbose):

dirname = os.path.basename(root)<EOL>if not dirname.startswith(parentdir_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % (root, dirname, parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None}<EOL>

Try to determine the version from the parent directory name.

    Source tarballs conventionally unpack into a directory that includes
    both the project name and a version string.


<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>

Extract version information from the given file.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):

if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs-tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None<EOL>}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>"}<EOL>

Get version information from git keywords.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):

if not os.path.exists(os.path.join(root, "<STR_LIT>")):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>describe_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>]  <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out)  <EOL><DEDENT>return pieces<EOL>

Get version from 'git describe' in the root of the source tree.

    This only gets called if the git-archive 'subst' keywords were *not*
    expanded, and _version.py hasn't already been rewritten with a short
    version string, meaning we're inside a checked out source tree.


if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>

Return a + if we don't already have one, else return a .


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"]}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>"  <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None}<EOL>

Render the given version pieces into the requested style.


<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>'):<EOL><INDENT>root = os.path.dirname(root)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>"}<EOL><DEDENT>try:<EOL><INDENT>pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)<EOL>return render(pieces, cfg.style)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>"}<EOL>

Get version information or return default if unable to do so.


def read_stream(schema, stream, *, buffer_size=io.DEFAULT_BUFFER_SIZE):

reader = _lancaster.Reader(schema)<EOL>buf = stream.read(buffer_size)<EOL>remainder = b'<STR_LIT>'<EOL>while len(buf) > <NUM_LIT:0>:<EOL><INDENT>values, n = reader.read_seq(buf)<EOL>yield from values<EOL>remainder = buf[n:]<EOL>buf = stream.read(buffer_size)<EOL>if len(buf) > <NUM_LIT:0> and len(remainder) > <NUM_LIT:0>:<EOL><INDENT>ba = bytearray()<EOL>ba.extend(remainder)<EOL>ba.extend(buf)<EOL>buf = memoryview(ba).tobytes()<EOL><DEDENT><DEDENT>if len(remainder) > <NUM_LIT:0>:<EOL><INDENT>raise EOFError('<STR_LIT>'<EOL>'<STR_LIT>'.format(len(remainder)))<EOL><DEDENT>

Using a schema, deserialize a stream of consecutive Avro values.

    :param str schema: json string representing the Avro schema
    :param file-like stream: a buffered stream of binary input
    :param int buffer_size: size of bytes to read from the stream each time
    :return: yields a sequence of python data structures deserialized
        from the stream


def read_stream_tuples(schema, stream, *, buffer_size=io.DEFAULT_BUFFER_SIZE):

reader = _lancaster.Reader(schema, _get_datetime_flags(schema))<EOL>buf = stream.read(buffer_size)<EOL>remainder = b'<STR_LIT>'<EOL>while len(buf) > <NUM_LIT:0>:<EOL><INDENT>values, n = reader.read_seq_tuples(buf)<EOL>yield from values<EOL>remainder = buf[n:]<EOL>buf = stream.read(buffer_size)<EOL>if len(buf) > <NUM_LIT:0> and len(remainder) > <NUM_LIT:0>:<EOL><INDENT>ba = bytearray()<EOL>ba.extend(remainder)<EOL>ba.extend(buf)<EOL>buf = memoryview(ba).tobytes()<EOL><DEDENT><DEDENT>if len(remainder) > <NUM_LIT:0>:<EOL><INDENT>raise EOFError('<STR_LIT>'<EOL>'<STR_LIT>'.format(len(remainder)))<EOL><DEDENT>

Using a schema, deserialize a stream of consecutive Avro values
    into tuples.

    This assumes the input is avro records of simple values (numbers,
    strings, etc.).

    :param str schema: json string representing the Avro schema, field
        names may include 'is_datetime' boolean fields to force
        decoding long values of epoch nanoseconds into datetime
        objects
    :param file-like stream: a buffered stream of binary input
    :param int buffer_size: size of bytes to read from the stream each time
    :return: yields a sequence of python tuples deserialized from the stream


root = os.path.realpath(os.path.abspath(os.getcwd()))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[<NUM_LIT:0>])))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL><DEDENT>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>err = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise VersioneerBadRootError(err)<EOL><DEDENT>try:<EOL><INDENT>me = os.path.realpath(os.path.abspath(__file__))<EOL>if os.path.splitext(me)[<NUM_LIT:0>] != os.path.splitext(versioneer_py)[<NUM_LIT:0>]:<EOL><INDENT>print("<STR_LIT>"<EOL>% (os.path.dirname(me), versioneer_py))<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT>return root<EOL>

Get the project root directory.

    We require that all commands are run from the project root, i.e. the
    directory that contains setup.py, setup.cfg, and versioneer.py .


<EOL>setup_cfg = os.path.join(root, "<STR_LIT>")<EOL>parser = configparser.SafeConfigParser()<EOL>with open(setup_cfg, "<STR_LIT:r>") as f:<EOL><INDENT>parser.readfp(f)<EOL><DEDENT>VCS = parser.get("<STR_LIT>", "<STR_LIT>")  <EOL>def get(parser, name):<EOL><INDENT>if parser.has_option("<STR_LIT>", name):<EOL><INDENT>return parser.get("<STR_LIT>", name)<EOL><DEDENT>return None<EOL><DEDENT>cfg = VersioneerConfig()<EOL>cfg.VCS = VCS<EOL>cfg.style = get(parser, "<STR_LIT>") or "<STR_LIT>"<EOL>cfg.versionfile_source = get(parser, "<STR_LIT>")<EOL>cfg.versionfile_build = get(parser, "<STR_LIT>")<EOL>cfg.tag_prefix = get(parser, "<STR_LIT>")<EOL>if cfg.tag_prefix in ("<STR_LIT>", '<STR_LIT>'):<EOL><INDENT>cfg.tag_prefix = "<STR_LIT>"<EOL><DEDENT>cfg.parentdir_prefix = get(parser, "<STR_LIT>")<EOL>cfg.verbose = get(parser, "<STR_LIT>")<EOL>return cfg<EOL>

Read the project setup.cfg file to determine Versioneer config.


def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>

Decorator to mark a method as the handler for a particular VCS.


def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):

assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL><DEDENT>return None<EOL><DEDENT>return stdout<EOL>


<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>

Extract version information from the given file.


if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs-tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None<EOL>}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>"}<EOL>

Get version information from git keywords.


if not os.path.exists(os.path.join(root, "<STR_LIT>")):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>describe_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>]  <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out)  <EOL><DEDENT>return pieces<EOL>

Get version from 'git describe' in the root of the source tree.

    This only gets called if the git-archive 'subst' keywords were *not*
    expanded, and _version.py hasn't already been rewritten with a short
    version string, meaning we're inside a checked out source tree.


def do_vcs_install(manifest_in, versionfile_source, ipy):

GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>files = [manifest_in, versionfile_source]<EOL>if ipy:<EOL><INDENT>files.append(ipy)<EOL><DEDENT>try:<EOL><INDENT>me = __file__<EOL>if me.endswith("<STR_LIT>") or me.endswith("<STR_LIT>"):<EOL><INDENT>me = os.path.splitext(me)[<NUM_LIT:0>] + "<STR_LIT>"<EOL><DEDENT>versioneer_file = os.path.relpath(me)<EOL><DEDENT>except NameError:<EOL><INDENT>versioneer_file = "<STR_LIT>"<EOL><DEDENT>files.append(versioneer_file)<EOL>present = False<EOL>try:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith(versionfile_source):<EOL><INDENT>if "<STR_LIT>" in line.strip().split()[<NUM_LIT:1>:]:<EOL><INDENT>present = True<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if not present:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT>")<EOL>f.write("<STR_LIT>" % versionfile_source)<EOL>f.close()<EOL>files.append("<STR_LIT>")<EOL><DEDENT>run_command(GITS, ["<STR_LIT>", "<STR_LIT>"] + files)<EOL>

Git-specific installation logic for Versioneer.

    For Git, this means creating/changing .gitattributes to mark _version.py
    for export-time keyword substitution.


dirname = os.path.basename(root)<EOL>if not dirname.startswith(parentdir_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % (root, dirname, parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None}<EOL>

Try to determine the version from the parent directory name.

    Source tarballs conventionally unpack into a directory that includes
    both the project name and a version string.


try:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>if not mo:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return json.loads(mo.group(<NUM_LIT:1>))<EOL>

Try to determine the version from _version.py if present.


os.unlink(filename)<EOL>contents = json.dumps(versions, sort_keys=True,<EOL>indent=<NUM_LIT:1>, separators=("<STR_LIT:U+002C>", "<STR_LIT>"))<EOL>with open(filename, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(SHORT_VERSION_PY % contents)<EOL><DEDENT>print("<STR_LIT>" % (filename, versions["<STR_LIT:version>"]))<EOL>

Write the given version number to the given _version.py file.


if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>

Return a + if we don't already have one, else return a .


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"]}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>"  <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None}<EOL>

Render the given version pieces into the requested style.


if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>assert cfg.VCS is not None, "<STR_LIT>"<EOL>handlers = HANDLERS.get(cfg.VCS)<EOL>assert handlers, "<STR_LIT>" % cfg.VCS<EOL>verbose = verbose or cfg.verbose<EOL>assert cfg.versionfile_source is not None,"<STR_LIT>"<EOL>assert cfg.tag_prefix is not None, "<STR_LIT>"<EOL>versionfile_abs = os.path.join(root, cfg.versionfile_source)<EOL>get_keywords_f = handlers.get("<STR_LIT>")<EOL>from_keywords_f = handlers.get("<STR_LIT>")<EOL>if get_keywords_f and from_keywords_f:<EOL><INDENT>try:<EOL><INDENT>keywords = get_keywords_f(versionfile_abs)<EOL>ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>ver = versions_from_file(versionfile_abs)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % (versionfile_abs, ver))<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>from_vcs_f = handlers.get("<STR_LIT>")<EOL>if from_vcs_f:<EOL><INDENT>try:<EOL><INDENT>pieces = from_vcs_f(cfg.tag_prefix, root, verbose)<EOL>ver = render(pieces, cfg.style)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None, "<STR_LIT:error>": "<STR_LIT>"}<EOL>

Get the project version from whatever source is available.

    Returns dict with two keys: 'version' and 'full'.


return get_versions()["<STR_LIT:version>"]<EOL>

Get the short version string for this project.


if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>cmds = {}<EOL>from distutils.core import Command<EOL>class cmd_version(Command):<EOL><INDENT>description = "<STR_LIT>"<EOL>user_options = []<EOL>boolean_options = []<EOL>def initialize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def finalize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def run(self):<EOL><INDENT>vers = get_versions(verbose=True)<EOL>print("<STR_LIT>" % vers["<STR_LIT:version>"])<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>if vers["<STR_LIT:error>"]:<EOL><INDENT>print("<STR_LIT>" % vers["<STR_LIT:error>"])<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT:version>"] = cmd_version<EOL>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.build_py import build_py as _build_py<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.build_py import build_py as _build_py<EOL><DEDENT>class cmd_build_py(_build_py):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>_build_py.run(self)<EOL>if cfg.versionfile_build:<EOL><INDENT>target_versionfile = os.path.join(self.build_lib,<EOL>cfg.versionfile_build)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_py<EOL>if "<STR_LIT>" in sys.modules:  <EOL><INDENT>from cx_Freeze.dist import build_exe as _build_exe<EOL>class cmd_build_exe(_build_exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_build_exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_exe<EOL>del cmds["<STR_LIT>"]<EOL><DEDENT>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.sdist import sdist as _sdist<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.sdist import sdist as _sdist<EOL><DEDENT>class cmd_sdist(_sdist):<EOL><INDENT>def run(self):<EOL><INDENT>versions = get_versions()<EOL>self._versioneer_generated_versions = versions<EOL>self.distribution.metadata.version = versions["<STR_LIT:version>"]<EOL>return _sdist.run(self)<EOL><DEDENT>def make_release_tree(self, base_dir, files):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>_sdist.make_release_tree(self, base_dir, files)<EOL>target_versionfile = os.path.join(base_dir, cfg.versionfile_source)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile,<EOL>self._versioneer_generated_versions)<EOL><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_sdist<EOL>return cmds<EOL>

Get the custom setuptools/distutils subclasses used by Versioneer.


root = get_root()<EOL>try:<EOL><INDENT>cfg = get_config_from_root(root)<EOL><DEDENT>except (EnvironmentError, configparser.NoSectionError,<EOL>configparser.NoOptionError) as e:<EOL><INDENT>if isinstance(e, (EnvironmentError, configparser.NoSectionError)):<EOL><INDENT>print("<STR_LIT>",<EOL>file=sys.stderr)<EOL>with open(os.path.join(root, "<STR_LIT>"), "<STR_LIT:a>") as f:<EOL><INDENT>f.write(SAMPLE_CONFIG)<EOL><DEDENT><DEDENT>print(CONFIG_ERROR, file=sys.stderr)<EOL>return <NUM_LIT:1><EOL><DEDENT>print("<STR_LIT>" % cfg.versionfile_source)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG % {"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT>ipy = os.path.join(os.path.dirname(cfg.versionfile_source),<EOL>"<STR_LIT>")<EOL>if os.path.exists(ipy):<EOL><INDENT>try:<EOL><INDENT>with open(ipy, "<STR_LIT:r>") as f:<EOL><INDENT>old = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>old = "<STR_LIT>"<EOL><DEDENT>if INIT_PY_SNIPPET not in old:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>with open(ipy, "<STR_LIT:a>") as f:<EOL><INDENT>f.write(INIT_PY_SNIPPET)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>ipy = None<EOL><DEDENT>manifest_in = os.path.join(root, "<STR_LIT>")<EOL>simple_includes = set()<EOL>try:<EOL><INDENT>with open(manifest_in, "<STR_LIT:r>") as f:<EOL><INDENT>for line in f:<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>for include in line.split()[<NUM_LIT:1>:]:<EOL><INDENT>simple_includes.add(include)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if "<STR_LIT>" not in simple_includes:<EOL><INDENT>print("<STR_LIT>")<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>if cfg.versionfile_source not in simple_includes:<EOL><INDENT>print("<STR_LIT>" %<EOL>cfg.versionfile_source)<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>" % cfg.versionfile_source)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>do_vcs_install(manifest_in, cfg.versionfile_source, ipy)<EOL>return <NUM_LIT:0><EOL>

Main VCS-independent setup function for installing Versioneer.


found = set()<EOL>setters = False<EOL>errors = <NUM_LIT:0><EOL>with open("<STR_LIT>", "<STR_LIT:r>") as f:<EOL><INDENT>for line in f.readlines():<EOL><INDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT><DEDENT><DEDENT>if len(found) != <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>if setters:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>return errors<EOL>

Validate the contents of setup.py against Versioneer's expectations.


return parser.parse(text).parsed<EOL>

Simple convenience function to unwrap the array of parameters.


<EOL>with open(filename, '<STR_LIT:rb>') as stream:<EOL><INDENT>content = stream.read().decode('<STR_LIT:utf-8>')<EOL><DEDENT>data = json.loads(content)<EOL>session = Session()<EOL>for item in data:<EOL><INDENT>table = Base.metadata.tables[item['<STR_LIT>'].split('<STR_LIT:.>')[-<NUM_LIT:1>]]<EOL>item['<STR_LIT>']['<STR_LIT:id>'] = item['<STR_LIT>']<EOL>session.connection().execute(table.insert().values(**item['<STR_LIT>']))<EOL><DEDENT>session.commit()<EOL>

Loads the passed fixture into the database following the
django format.


<EOL>response, _ = self.client.options(self.right_path)<EOL>assert response.status == http.client.OK<EOL>assert header not in response<EOL>response, _ = self.client.options(<EOL>self.right_path,<EOL>headers={<EOL>'<STR_LIT>': self.right_origin,<EOL>'<STR_LIT>': self.default_method})<EOL>assert response.status == http.client.OK<EOL>assert header not in response<EOL>response, _ = self.client.options(<EOL>self.right_path, headers={'<STR_LIT>': '<STR_LIT:*>'})<EOL>assert response.status == http.client.OK<EOL>assert header not in response<EOL>response, _ = self.client.options(self.left_path)<EOL>assert response.status == http.client.OK<EOL>assert header not in response<EOL>response, _ = self.client.options(<EOL>self.left_path,<EOL>headers={<EOL>'<STR_LIT>': self.left_origin,<EOL>'<STR_LIT>': self.default_method})<EOL>assert response.status == http.client.OK<EOL>assert header not in response<EOL>

Test each Access-Control-Allow header here, since they
all do the same thing.


<EOL>if isinstance(text, six.binary_type):<EOL><INDENT>text = text.decode(encoding)<EOL><DEDENT>return Query(text, split_segments(text))<EOL>

Parse the querystring into a normalized form.


buf = StringIO()<EOL>segments = []<EOL>combinators = []<EOL>last_group = False<EOL>iterator = iter(text)<EOL>last_negation = False<EOL>for character in iterator:<EOL><INDENT>if character in COMBINATORS:<EOL><INDENT>if last_negation:<EOL><INDENT>buf.write(constants.OPERATOR_NEGATION)<EOL><DEDENT>val = buf.getvalue()<EOL>reset_stringio(buf)<EOL>if not last_group and not len(val):<EOL><INDENT>raise ValueError('<STR_LIT>' % character)<EOL><DEDENT>if len(val):<EOL><INDENT>segments.append(parse_segment(val))<EOL><DEDENT>combinators.append(COMBINATORS[character])<EOL><DEDENT>elif character == constants.GROUP_BEGIN:<EOL><INDENT>if buf.tell():<EOL><INDENT>raise ValueError('<STR_LIT>' % character)<EOL><DEDENT>seg = split_segments(iterator, True)<EOL>if last_negation:<EOL><INDENT>seg = UnarySegmentCombinator(seg)<EOL><DEDENT>segments.append(seg)<EOL>last_group = True<EOL>continue<EOL><DEDENT>elif character == constants.GROUP_END:<EOL><INDENT>val = buf.getvalue()<EOL>if not buf.tell() or not closing_paren:<EOL><INDENT>raise ValueError('<STR_LIT>' % character)<EOL><DEDENT>segments.append(parse_segment(val))<EOL>return combine(segments, combinators)<EOL><DEDENT>elif character == constants.OPERATOR_NEGATION and not buf.tell():<EOL><INDENT>last_negation = True<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>if last_negation:<EOL><INDENT>buf.write(constants.OPERATOR_NEGATION)<EOL><DEDENT>if last_group:<EOL><INDENT>raise ValueError('<STR_LIT>' % character)<EOL><DEDENT>buf.write(character)<EOL><DEDENT>last_negation = False<EOL>last_group = False<EOL><DEDENT>else:<EOL><INDENT>if closing_paren:<EOL><INDENT>raise ValueError('<STR_LIT>' % constants.GROUP_END)<EOL><DEDENT>if not last_group:<EOL><INDENT>segments.append(parse_segment(buf.getvalue()))<EOL><DEDENT><DEDENT>return combine(segments, combinators)<EOL>


if constants.DIRECTIVE in key:<EOL><INDENT>return key.split(constants.DIRECTIVE, <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>return key, None<EOL><DEDENT>

Takes a key of type (foo:bar) and returns either the key and the
directive, or the key and None (for no directive.)


if not len(text):<EOL><INDENT>return NoopQuerySegment()<EOL><DEDENT>q = QuerySegment()<EOL>equalities = zip(constants.OPERATOR_EQUALITIES, itertools.repeat(text))<EOL>equalities = map(lambda x: (x[<NUM_LIT:0>], x[<NUM_LIT:1>].split(x[<NUM_LIT:0>], <NUM_LIT:1>)), equalities)<EOL>equalities = list(filter(lambda x: len(x[<NUM_LIT:1>]) > <NUM_LIT:1>, equalities))<EOL>key_len = len(min((x[<NUM_LIT:1>][<NUM_LIT:0>] for x in equalities), key=len))<EOL>equalities = filter(lambda x: len(x[<NUM_LIT:1>][<NUM_LIT:0>]) == key_len, equalities)<EOL>op, (key, value) = min(equalities, key=lambda x: len(x[<NUM_LIT:1>][<NUM_LIT:1>]))<EOL>key, directive = parse_directive(key)<EOL>if directive:<EOL><INDENT>op = constants.OPERATOR_EQUALITY_FALLBACK<EOL>q.directive = directive<EOL><DEDENT>path = key.split(constants.SEP_PATH)<EOL>last = path[-<NUM_LIT:1>]<EOL>if last.endswith(constants.OPERATOR_NEGATION):<EOL><INDENT>last = last[:-<NUM_LIT:1>]<EOL>q.negated = not q.negated<EOL><DEDENT>if last == constants.PATH_NEGATION:<EOL><INDENT>path.pop(-<NUM_LIT:1>)<EOL>q.negated = not q.negated<EOL><DEDENT>q.values = value.split(constants.SEP_VALUE)<EOL>if path[-<NUM_LIT:1>] in constants.OPERATOR_SUFFIXES:<EOL><INDENT>if op not in constants.OPERATOR_FALLBACK:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>q.operator = constants.OPERATOR_SUFFIX_MAP[path[-<NUM_LIT:1>]]<EOL>path.pop(-<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>q.operator = constants.OPERATOR_EQUALITY_MAP[op]<EOL><DEDENT>if not len(path):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>q.path = path<EOL>return q<EOL>


o = StringIO()<EOL>o.write('<STR_LIT:(>')<EOL>if self.negated:<EOL><INDENT>o.write('<STR_LIT>')<EOL><DEDENT>o.write('<STR_LIT:.>'.join(self.path))<EOL>if self.values:<EOL><INDENT>o.write('<STR_LIT>' % REVERSED_OPERATOR_SUFFIX_MAP[self.operator])<EOL><DEDENT>o.write('<STR_LIT>'.join(map(lambda x: "<STR_LIT>".format(str(x)), self.values)))<EOL>o.write('<STR_LIT:)>')<EOL>return o.getvalue()<EOL>

Format this query segment in a human-readable representation
intended for debugging.


Initialize authentication protocol; establish parameters.


return None<EOL>

Gets the a user if they are authenticated; else None.

        @retval False    Unable to authenticate.
        @retval None     Able to authenticate but failed.
        @retval <user>   User object representing the current user.


raise http.exceptions.Forbidden()<EOL>

Callback that is invoked when after a user is determined to
be unauthenticated.


def get_user(self, request, method, *args):

return None<EOL>

Callback that is invoked when a user is attempting to be
authenticated with a set of credentials.


try:<EOL><INDENT>self.serialize(data)<EOL>return True<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>

Tests this serializer to see if it can serialize.


if data is not None and self.response is not None:<EOL><INDENT>self.response['<STR_LIT:Content-Type>'] = self.media_types[<NUM_LIT:0>]<EOL>self.response.write(data)<EOL><DEDENT>return data<EOL>

Transforms the object into an acceptable format for transmission.

@throws ValueError
    To indicate this serializer does not support the encoding of the
    specified object.


def is_accessible(self, user, method, resource):

return True<EOL>

Determines the accessibility to a resource endpoint for a particular
method. An inaccessible resource is indistinguishable from a
non-existant resource.

@param[in] user
    The user in question that is being checked.

@param[in] method
    The method in question that is being performed (eg. 'GET').

@param[in] resource
    The resource instance that is being authorized.

@returns
    Returns true if the user can access the resource for
    the passed operation; otherwise, false.


raise http.exceptions.Forbidden()<EOL>

Informs the client that the resource is inaccessible.


def is_authorized(self, user, operation, resource, item):

return True<EOL>

Determines authroization to a specific resource object.

        @param[in] user
            The user in question that is being checked.

        @param[in] operation
            The operation in question that is being performed (eg. 'read').

        @param[in] resource
            The resource instance that is being authorized.

        @param[in] item
            The specific instance of an object returned by a `read` from
            the `resource`.

        @returns
            Returns true to indicate authorization or false to indicate
            otherwise.


raise http.exceptions.Forbidden()<EOL>

Informs the client that it is not authrozied for the resource.


def filter(self, user, operation, resource, iterable):

return iterable<EOL>

Filters an iterable to contain only the items for which the user
is authorized to perform the operation on.

@param[in] user
    The user in question that is being checked.

@param[in] operation
    The operation in question that is being performed (eg. 'read').

@param[in] resource
    The resource instance that is being authorized.

@param[in] iterable
    The iterable of objects to be checked. This method is called
    from the model connector so the actual value of this parameter
    depends on the model connector (eg. it may be a django queryset).

@returns
    Returns an iterable containing the remaining objects.


raise http.exceptions.NotFound()<EOL>


return tuple(sequence._headers.get(name, '<STR_LIT>').split('<STR_LIT:U+002C>'))<EOL>

Returns the passed header as a tuple.

        Implements a facade so that the response headers can override
        this to provide a mutable sequence header.


return str(string.capwords(name, '<STR_LIT:->'))<EOL>

Normalizes the case of the passed name to be Http-Header-Case.


Retrieves a header with the passed name.

        @param[in] name
            The case-insensitive name of the header to retrieve.


Retrieves the number of headers in the request.


Returns an iterable for all headers in the request.


Tests if the passed header exists in the request.


return self._sequence[name].index(value)<EOL>

Return the index in the list of the first item whose value is x in
the values of the named header.


return self._sequence[name].count(value)<EOL>

Return the number of times a value appears in the list of the values
of the named header.


return self._sequence[name]<EOL>

Retrieves the passed header as a tuple of its values.


self._resource = weakref.proxy(resource)<EOL>

Binds this to the passed resource object.

        This is used so that the request and response classes can access
        metadata and configuration on the resource handling this request
        so helper methods on the request and response like `serialize` work
        in full knowledge of configuration supplied to the resource.


raise NotImplementedError()<EOL>

Retrieves the upper-cased version of the protocol (eg. HTTP).


return self.headers.get('<STR_LIT>') or '<STR_LIT:127.0.0.1>'<EOL>

Retrieves the hostname, normally from the `Host` header.


raise NotImplementedError()<EOL>

Retrieves the mount point portion of the path of this request.


raise NotImplementedError()<EOL>

Retrieves the text after the first ? in the path.


raise NotImplementedError()<EOL>

Returns the complete URI of the request.


<EOL>content_type = self.headers.get('<STR_LIT:Content-Type>')<EOL>if content_type:<EOL><INDENT>ptype, _, params = mimeparse.parse_mime_type(content_type)<EOL>default = '<STR_LIT:utf-8>' if ptype == '<STR_LIT>' else '<STR_LIT>'<EOL>return params.get('<STR_LIT>', default)<EOL><DEDENT>

The name of the encoding used to decode the stream’s bytes
into strings, and to encode strings into bytes.

Reads the charset value from the `Content-Type` header, if available;
else, returns nothing.


return None<EOL>

Read and return the request data.

        @note Connectors should override this method.


def read(self, deserialize=False, format=None):

if deserialize:<EOL><INDENT>data, _ = self.deserialize(format=format)<EOL>return data<EOL><DEDENT>content = self._read()<EOL>if not content:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if type(content) is six.binary_type:<EOL><INDENT>content = content.decode(self.encoding)<EOL><DEDENT>return content<EOL>

Read and return the request data.

        @param[in] deserialize
            True to deserialize the resultant text using a determiend format
            or the passed format.

        @param[in] format
            A specific format to deserialize in; if provided, no detection is
            done. If not provided, the content-type header is looked at to
            determine an appropriate deserializer.


return self._resource.deserialize(self, format=format)<EOL>

Deserializes the request body using a determined deserializer.

        @param[in] format
            A specific format to deserialize in; if provided, no detection is
            done. If not provided, the content-type header is looked at to
            determine an appropriate deserializer.

        @returns
            A tuple of the deserialized data and an instance of the
            deserializer used.


length = self.headers.get('<STR_LIT>')<EOL>return int(length) if length else <NUM_LIT:0><EOL>

Returns the length of the request body, if known.


return self.headers[name]<EOL>

Retrieves a header with the passed name.


return self.headers.get(name, default)<EOL>


return self.headers.getlist(name)<EOL>

Retrieves a the multi-valued list of the header with
the passed name.


return name in self.headers<EOL>

Tests if the passed header exists in the request.


return self.headers.keys()<EOL>


return self.headers.values()<EOL>


return self.headers.items()<EOL>


@abc.abstractmethod<EOL><INDENT>def __setitem__(self, name, value):<DEDENT>

Stores a header with the passed name.

        @param[in] name
            The name to store the header as. This is passed through
            `Headers.normalize` before storing on the response.

        @param[in] value
            The value to store for the header; for multi-valued headers,
            this can be a comma-separated list of values.


Removes a header with the passed name.

        @param[in] name
            The case-insensitive name of the header to remove
            from the response.


return self._sequence[name].append(value)<EOL>

Add a value to the end of the list for the named header.


return self._sequence[name].extend(values)<EOL>

Extend the list for the named header by appending all values.


return self._sequence[name].insert(index, value)<EOL>

Insert a value at the passed index in the named header.


return self._sequence[name].remove(value)<EOL>

Remove the first item with the passed value from the
list for the named header.


return self._sequence[name].pop(index)<EOL>

Remove the item at the given position in the named header list.


return self._sequence[name].sort()<EOL>


return self._sequence[name].reverse()<EOL>

Reverse the elements of the list, in place.


if self.closed:<EOL><INDENT>raise exceptions.InvalidOperation('<STR_LIT>')<EOL><DEDENT>

Raises an exception if the response is closed.


self.require_not_closed()<EOL>if self.streaming:<EOL><INDENT>raise exceptions.InvalidOperation('<STR_LIT>')<EOL><DEDENT>

Raises an exception if the response is not open.


raise NotImplementedError()<EOL>


return self._body<EOL>

Returns the current value of the response body.


self._body = value<EOL>

Sets the response body to the passed value.

        @note
            During asynchronous or streaming responses, remember that
            the `body` property refers to the portion of the response *not*
            sent to the client.


Binds this to the passed resource object.

        @sa armet.http.request.Request.bind


<EOL>self.require_not_closed()<EOL>if not self.streaming or self.asynchronous:<EOL><INDENT>if '<STR_LIT>' not in self.headers:<EOL><INDENT>self.headers['<STR_LIT>'] = self.tell()<EOL><DEDENT><DEDENT>self.flush()<EOL>self._closed = True<EOL>

Flush and close the stream.

        This is called automatically by the base resource on resources
        unless the resource is operating asynchronously; in that case,
        this method MUST be called in order to signal the end of the request.
        If not the request will simply hang as it is waiting for some
        thread to tell it to return to the client.


return self._closed<EOL>


return self._length<EOL>


def write(self, chunk, serialize=False, format=None):

<EOL>self.require_not_closed()<EOL>if chunk is None:<EOL><INDENT>return<EOL><DEDENT>if serialize or format is not None:<EOL><INDENT>self.serialize(chunk, format=format)<EOL>return  <EOL><DEDENT>if type(chunk) is six.binary_type:<EOL><INDENT>self._length += len(chunk)<EOL>self._stream.write(chunk)<EOL><DEDENT>elif isinstance(chunk, six.string_types):<EOL><INDENT>encoding = self.encoding<EOL>if encoding is not None:<EOL><INDENT>chunk = chunk.encode(encoding)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidOperation(<EOL>'<STR_LIT>')<EOL><DEDENT>self._length += len(chunk)<EOL>self._stream.write(chunk)<EOL><DEDENT>elif isinstance(chunk, collections.Iterable):<EOL><INDENT>for section in chunk:<EOL><INDENT>self.write(section)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidOperation(<EOL>'<STR_LIT>')<EOL><DEDENT>

Writes the given chunk to the output buffer.

        @param[in] chunk
            Either a byte array, a unicode string, or a generator. If `chunk`
            is a generator then calling `self.write(<generator>)` is
            equivalent to:

            @code
                for x in <generator>:
                    self.write(x)
                    self.flush()
            @endcode

        @param[in] serialize
            True to serialize the lines in a determined serializer.

        @param[in] format
            A specific format to serialize in; if provided, no detection is
            done. If not provided, the accept header (as well as the URL
            extension) is looked at to determine an appropriate serializer.


return self._resource.serialize(data, response=self, format=format)<EOL>

Serializes the data into this response using a serializer.

        @param[in] data
            The data to be serialized.

        @param[in] format
            A specific format to serialize in; if provided, no detection is
            done. If not provided, the accept header (as well as the URL
            extension) is looked at to determine an appropriate serializer.

        @returns
            A tuple of the serialized text and an instance of the
            serializer used.


<EOL>self.require_not_closed()<EOL>chunk = self._stream.getvalue()<EOL>self._stream.truncate(<NUM_LIT:0>)<EOL>self._stream.seek(<NUM_LIT:0>)<EOL>self.body = chunk if (self._body is None) else (self._body + chunk)<EOL>if self.asynchronous:<EOL><INDENT>self.streaming = True<EOL><DEDENT>

Flush the write buffers of the stream.

        This results in writing the current contents of the write buffer to
        the transport layer, initiating the HTTP/1.1 response. This initiates
        a streaming response. If the `Content-Length` header is not given
        then the chunked `Transfer-Encoding` is applied.


self.write(*args, **kwargs)<EOL>self.flush()<EOL>

Writes the passed chunk and flushes it to the client.


self.send(*args, **kwargs)<EOL>self.close()<EOL>

Writes the passed chunk, flushes it to the client,
and terminates the connection.


return self.headers[name]<EOL>

Retrieves a header with the passed name.


self.headers[name] = value<EOL>


del self.headers<EOL>


return self.tell()<EOL>

Retrieves the actual length of the response.


return not self._closed<EOL>


return name in self.headers<EOL>

Tests if the passed header exists in the response.


return self.headers.append(name, value)<EOL>

Add a value to the end of the list for the named header.


return self.headers.extend(name, values)<EOL>

Extend the list for the named header by appending all values.


return self.headers.insert(index, value)<EOL>

Insert a value at the passed index in the named header.


return self.headers.remove(name, value)<EOL>

Remove the first item with the passed value from the
list for the named header.


return self.headers.popvalue(name, index)<EOL>

Remove the item at the given position in the named header list.


return self.headers.index(name, value)<EOL>

Return the index in the list of the first item whose value is x in
the values of the named header.


return self.headers.count(name, value)<EOL>

Return the number of times a value appears in the list of the values
of the named header.


return self.headers.sort(name)<EOL>


return self.headers.reverse(name)<EOL>

Reverse the elements of the list, in place.


return self.headers.getlist(name)<EOL>

Retrieves the passed header as a sequence of its values.


def deserialize(self, request=None, text=None):

if text is None:<EOL><INDENT>text = request.read()<EOL><DEDENT>return text<EOL>

Parses the request content into a format consumable by python.

        @throws ValueError
            To indicate this deserializer cannot deserialize the
            passed text.


value = value.strip()<EOL>value = re.sub(r'<STR_LIT>', r'<STR_LIT>', value)<EOL>value = re.sub(r'<STR_LIT>', r'<STR_LIT:->', value)<EOL>value = re.sub(r'<STR_LIT>', r'<STR_LIT>', value)<EOL>value = value.lower()<EOL>return value<EOL>


try:<EOL><INDENT>return importlib.import_module(name)<EOL><DEDENT>except ImportError:<EOL><INDENT>return None<EOL><DEDENT>

Attempt to import a module; returns None if unsuccessful.


if isinstance(value, collections.Mapping):<EOL><INDENT>if collection is None:<EOL><INDENT>collection = {}<EOL><DEDENT>collection.update(**value)<EOL><DEDENT>elif isinstance(value, six.string_types):<EOL><INDENT>if collection is None:<EOL><INDENT>collection = []<EOL><DEDENT>collection.append(value)<EOL><DEDENT>elif isinstance(value, collections.Iterable):<EOL><INDENT>if collection is None:<EOL><INDENT>collection = []<EOL><DEDENT>collection.extend(value)<EOL><DEDENT>else:<EOL><INDENT>if collection is None:<EOL><INDENT>collection = []<EOL><DEDENT>collection.append(value)<EOL><DEDENT>return collection<EOL>


@functools.wraps(default)<EOL>def wrapped(x, y):<EOL><INDENT>if isinstance(y, six.string_types) and not isinstance(x.type, sa.Enum):<EOL><INDENT>return x.ilike("<STR_LIT:%>" + y + "<STR_LIT:%>")<EOL><DEDENT>else:<EOL><INDENT>return default(x, y)<EOL><DEDENT><DEDENT>return wrapped<EOL>

Helper function that performs an `ilike` query if a string value
    is passed, otherwise the normal default operation.


specifiers = "<STR_LIT>".join(specifiers.split())<EOL>for specifier in specifiers.split('<STR_LIT:U+002C>'):<EOL><INDENT>if len(specifier) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>count = specifier.count('<STR_LIT:->')<EOL>if (count and specifier[<NUM_LIT:0>] == '<STR_LIT:->') or not count:<EOL><INDENT>yield int(specifier), int(specifier)<EOL>continue<EOL><DEDENT>specifier = list(map(int, specifier.split('<STR_LIT:->')))<EOL>if len(specifier) == <NUM_LIT:2>:<EOL><INDENT>if specifier[<NUM_LIT:0>] < <NUM_LIT:0> or specifier[<NUM_LIT:1>] < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if specifier[<NUM_LIT:1>] < specifier[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>yield tuple(specifier)<EOL>continue<EOL><DEDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Consumes set specifiers as text and forms a generator to retrieve
the requested ranges.

@param[in] specifiers
    Expected syntax is from the byte-range-specifier ABNF found in the
    [RFC 2616]; eg. 15-17,151,-16,26-278,15

@returns
    Consecutive tuples that describe the requested range; eg. (1, 72) or
    (1, 1) [read as 1 to 72 or 1 to 1].


<EOL>header = request.headers.get('<STR_LIT>')<EOL>if not header:<EOL><INDENT>return items<EOL><DEDENT>prefix = RANGE_SPECIFIER + '<STR_LIT:=>'<EOL>if not header.find(prefix) == <NUM_LIT:0>:<EOL><INDENT>raise exceptions.RequestedRangeNotSatisfiable()<EOL><DEDENT>else:<EOL><INDENT>ranges = parse(header[len(prefix):])<EOL><DEDENT>ranges = list(ranges)<EOL>if len(ranges) > <NUM_LIT:1>:<EOL><INDENT>raise exceptions.RequestedRangeNotSatisfiable(<EOL>'<STR_LIT>')<EOL><DEDENT>start, end = ranges[<NUM_LIT:0>]<EOL>max_length = request.resource.count(items)<EOL>end = min(end, max_length)<EOL>response.status = client.PARTIAL_CONTENT<EOL>response.headers['<STR_LIT>'] = '<STR_LIT>' % (start, end, max_length)<EOL>response.headers['<STR_LIT>'] = RANGE_SPECIFIER<EOL>items = items[start:end + <NUM_LIT:1>]<EOL>return items<EOL>

Paginate an iterable during a request.

    Magically splicling an iterable in our supported ORMs allows LIMIT and
    OFFSET queries. We should probably delegate this to the ORM or something
    in the future.


config = dict(use.config)<EOL>use.config.update(kwargs)<EOL>return config<EOL>

Updates the active resource configuration to the passed
keyword arguments.

Invoking this method without passing arguments will just return the
active resource configuration.

@returns
    The previous configuration.


<EOL>return self._get[target](target)<EOL>

Retrieve the value of this attribute from the passed object.


if not self._set:<EOL><INDENT>return<EOL><DEDENT>if self.path is None:<EOL><INDENT>self.set = lambda *a: None<EOL>return None<EOL><DEDENT>if self._segments[target.__class__]:<EOL><INDENT>self.get(target)<EOL><DEDENT>if self._segments[target.__class__]:<EOL><INDENT>return<EOL><DEDENT>parent_getter = compose(*self._getters[target.__class__][:-<NUM_LIT:1>])<EOL>target = parent_getter(target)<EOL>func = self._make_setter(self.path.split('<STR_LIT:.>')[-<NUM_LIT:1>], target.__class__)<EOL>func(target, value)<EOL>def setter(target, value):<EOL><INDENT>func(parent_getter(target), value)<EOL><DEDENT>self.set = setter<EOL>

Set the value of this attribute for the passed object.


<EOL>return value<EOL>

Prepare the value for serialization and presentation to the client.


<EOL>return value<EOL>

Cleans the value from deserialization into consumption by python.


return self.__class__(**self.__dict__)<EOL>

Construct an identical attribute.

        Used by the resource metaclass to ensure all attributes are unique
        instances. This is done so that when getters and setters are resolved
        the caches don't clobber base classes (for inherited attributes).


<EOL>resource.meta.asynchronous = True<EOL>return resource<EOL>

Instructs a decorated resource that it is to be asynchronous.

    An asynchronous resource means that `response.close()` must be called
    explicitly as returning from a method (eg. `get`) does not close
    the connection.

    @note
        This can also be configured by setting `asynchronous` to `True`
        on `<resource>.Meta`. The benefit of the decorator is that this
        can be applied to specific methods as well as the entire class
        body.


def inner(function):<EOL><INDENT>name = kwargs.pop('<STR_LIT:name>', None)<EOL>if name is None:<EOL><INDENT>name = utils.dasherize(function.__name__)<EOL><DEDENT>methods = kwargs.pop('<STR_LIT>', None)<EOL>if isinstance(methods, six.string_types):<EOL><INDENT>methods = methods,<EOL><DEDENT>handler = (function, methods)<EOL>if name not in _resources:<EOL><INDENT>_handlers[name] = []<EOL>from armet import resources<EOL>kwargs['<STR_LIT:name>'] = name<EOL>class LightweightResource(resources.Resource):<EOL><INDENT>Meta = type(str('<STR_LIT:Meta>'), (), kwargs)<EOL>def route(self, request, response):<EOL><INDENT>for handler, methods in _handlers[name]:<EOL><INDENT>if methods is None or request.method in methods:<EOL><INDENT>return handler(request, response)<EOL><DEDENT><DEDENT>resources.Resource.route(self)<EOL><DEDENT><DEDENT>_resources[name] = LightweightResource<EOL><DEDENT>_handlers[name].append(handler)<EOL>return _resources[name]<EOL><DEDENT>return inner<EOL>

Wraps the decorated function in a lightweight resource.


return resource._request_read(url)<EOL>

Perform a `read` request in the passed `resource` context against
the given `url`.

Returns what a `read` would return (the managed target item).


if self.slug is not None:<EOL><INDENT>return self.meta.detail_allowed_operations<EOL><DEDENT>return self.meta.list_allowed_operations<EOL>

Retrieves the allowed operations for this request.


if not set(args).issubset(self.allowed_operations):<EOL><INDENT>raise http.exceptions.Forbidden()<EOL><DEDENT>

Assets if the requested operations are allowed in this context.


if data is not None:<EOL><INDENT>data = self.prepare(data)<EOL>self.response.write(data, serialize=True)<EOL><DEDENT>

Fills the response object from the passed data.


<EOL>self.assert_operations('<STR_LIT>')<EOL>items = self.read()<EOL>if not items:<EOL><INDENT>raise http.exceptions.NotFound()<EOL><DEDENT>if (isinstance(items, Iterable)<EOL>and not isinstance(items, six.string_types)) and items:<EOL><INDENT>items = pagination.paginate(self.request, self.response, items)<EOL><DEDENT>self.make_response(items)<EOL>


if self.slug is not None:<EOL><INDENT>raise http.exceptions.NotImplemented()<EOL><DEDENT>self.assert_operations('<STR_LIT>')<EOL>data = self._clean(None, self.request.read(deserialize=True))<EOL>item = self.create(data)<EOL>self.response.status = http.client.CREATED<EOL>self.make_response(item)<EOL>


if self.slug is None:<EOL><INDENT>raise http.exceptions.NotImplemented()<EOL><DEDENT>target = self.read()<EOL>data = self._clean(target, self.request.read(deserialize=True))<EOL>if target is not None:<EOL><INDENT>self.assert_operations('<STR_LIT>')<EOL>try:<EOL><INDENT>self.update(target, data)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise http.exceptions.NotImplemented()<EOL><DEDENT>self.make_response(target)<EOL><DEDENT>else:<EOL><INDENT>self.assert_operations('<STR_LIT>')<EOL>target = self.create(data)<EOL>self.response.status = http.client.CREATED<EOL>self.make_response(target)<EOL><DEDENT>


if self.slug is None:<EOL><INDENT>raise http.exceptions.NotImplemented()<EOL><DEDENT>self.assert_operations('<STR_LIT>')<EOL>self.destroy()<EOL>self.response.status = http.client.NO_CONTENT<EOL>self.make_response()<EOL>


from armet.resources.managed.request import read<EOL>if self.slug is None:<EOL><INDENT>raise http.exceptions.NotImplemented()<EOL><DEDENT>target = self.read()<EOL>links = self._parse_link_headers(request['<STR_LIT>'])<EOL>for link in links:<EOL><INDENT>self.relate(target, read(self, link['<STR_LIT>']))<EOL><DEDENT>self.response.status = http.client.NO_CONTENT<EOL>self.make_response()<EOL>

Processes a `LINK` request.

        A `LINK` request is asking to create a relation from the currently
        represented URI to all of the `Link` request headers.


from armet.resources.managed.request import read<EOL>if self.slug is None:<EOL><INDENT>raise http.exceptions.NotImplemented()<EOL><DEDENT>target = self.read()<EOL>links = self._parse_link_headers(request['<STR_LIT>'])<EOL>for link in links:<EOL><INDENT>self.unrelate(target, read(self, link['<STR_LIT>']))<EOL><DEDENT>self.response.status = http.client.NO_CONTENT<EOL>self.make_response()<EOL>

Processes a `UNLINK` request.

        A `UNLINK` request is asking to revoke a relation from the currently
        represented URI to all of the `Link` request headers.


def _merge(options, name, bases, default=None):

result = None<EOL>for base in bases:<EOL><INDENT>if base is None:<EOL><INDENT>continue<EOL><DEDENT>value = getattr(base, name, None)<EOL>if value is None:<EOL><INDENT>continue<EOL><DEDENT>result = utils.cons(result, value)<EOL><DEDENT>value = options.get(name)<EOL>if value is not None:<EOL><INDENT>result = utils.cons(result, value)<EOL><DEDENT>return result or default<EOL>


def __init__(self, meta, name, data, bases):

<EOL>self.debug = meta.get('<STR_LIT>')<EOL>if self.debug is None:<EOL><INDENT>self.debug = False<EOL><DEDENT>self.abstract = data.get('<STR_LIT>')<EOL>self.name = meta.get('<STR_LIT:name>')<EOL>if self.name is None:<EOL><INDENT>dashed = utils.dasherize(name).strip()<EOL>if dashed:<EOL><INDENT>self.name = re.sub(r'<STR_LIT>', '<STR_LIT>', dashed)<EOL><DEDENT>else:<EOL><INDENT>self.name = name<EOL><DEDENT><DEDENT>elif callable(self.name):<EOL><INDENT>self.name = self.name(name)<EOL><DEDENT>self.asynchronous = meta.get('<STR_LIT>', False)<EOL>self.connectors = connectors = _merge(meta, '<STR_LIT>', bases, {})<EOL>if not connectors.get('<STR_LIT:http>') and not self.abstract:<EOL><INDENT>raise ImproperlyConfigured('<STR_LIT>')<EOL><DEDENT>for key in connectors:<EOL><INDENT>connector = connectors[key]<EOL>if isinstance(connector, six.string_types):<EOL><INDENT>if connector in getattr(included_connectors, key):<EOL><INDENT>connectors[key] = '<STR_LIT>'.format(connector)<EOL><DEDENT><DEDENT><DEDENT>self.options = options = _merge(meta, '<STR_LIT>', bases, {})<EOL>for name in options:<EOL><INDENT>setattr(self, name, meta.get(name))<EOL><DEDENT>self.patterns = meta.get('<STR_LIT>', [])<EOL>for index, pattern in enumerate(self.patterns):<EOL><INDENT>if isinstance(pattern, six.string_types):<EOL><INDENT>pattern = (None, pattern)<EOL><DEDENT>self.patterns[index] = (pattern[<NUM_LIT:0>], re.compile(pattern[<NUM_LIT:1>]))<EOL><DEDENT>self.trailing_slash = meta.get('<STR_LIT>', True)<EOL>self.http_allowed_methods = meta.get('<STR_LIT>')<EOL>if self.http_allowed_methods is None:<EOL><INDENT>self.http_allowed_methods = (<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT:GET>',<EOL>'<STR_LIT:POST>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>self.http_allowed_headers = meta.get('<STR_LIT>')<EOL>if self.http_allowed_headers is None:<EOL><INDENT>self.http_allowed_headers = (<EOL>'<STR_LIT:Content-Type>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>self.http_exposed_headers = meta.get('<STR_LIT>')<EOL>if self.http_exposed_headers is None:<EOL><INDENT>self.http_exposed_headers = (<EOL>'<STR_LIT:Content-Type>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>self.http_allowed_origins = meta.get('<STR_LIT>')<EOL>if self.http_allowed_origins is None:<EOL><INDENT>self.http_allowed_origins = ()<EOL><DEDENT>self.legacy_redirect = meta.get('<STR_LIT>', True)<EOL>self.serializers = serializers = meta.get('<STR_LIT>')<EOL>if not serializers:<EOL><INDENT>self.serializers = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:url>': '<STR_LIT>'<EOL>}<EOL><DEDENT>for name, serializer in six.iteritems(self.serializers):<EOL><INDENT>if isinstance(serializer, six.string_types):<EOL><INDENT>segments = serializer.split('<STR_LIT:.>')<EOL>module = '<STR_LIT:.>'.join(segments[:-<NUM_LIT:1>])<EOL>module = import_module(module)<EOL>self.serializers[name] = getattr(module, segments[-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>self.allowed_serializers = meta.get('<STR_LIT>')<EOL>if not self.allowed_serializers:<EOL><INDENT>self.allowed_serializers = tuple(self.serializers.keys())<EOL><DEDENT>for name in self.allowed_serializers:<EOL><INDENT>if name not in self.serializers:<EOL><INDENT>raise ImproperlyConfigured(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(name))<EOL><DEDENT><DEDENT>self.default_serializer = meta.get('<STR_LIT>')<EOL>if not self.default_serializer:<EOL><INDENT>if '<STR_LIT>' in self.allowed_serializers:<EOL><INDENT>self.default_serializer = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>self.default_serializer = self.allowed_serializers[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if self.default_serializer not in self.allowed_serializers:<EOL><INDENT>raise ImproperlyConfigured(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(self.default_serializer))<EOL><DEDENT>self.deserializers = deserializers = meta.get('<STR_LIT>')<EOL>if not deserializers:<EOL><INDENT>self.deserializers = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:url>': '<STR_LIT>'<EOL>}<EOL><DEDENT>for name, deserializer in six.iteritems(self.deserializers):<EOL><INDENT>if isinstance(deserializer, six.string_types):<EOL><INDENT>segments = deserializer.split('<STR_LIT:.>')<EOL>module = '<STR_LIT:.>'.join(segments[:-<NUM_LIT:1>])<EOL>module = import_module(module)<EOL>self.deserializers[name] = getattr(module, segments[-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>self.allowed_deserializers = meta.get('<STR_LIT>')<EOL>if not self.allowed_deserializers:<EOL><INDENT>self.allowed_deserializers = tuple(self.deserializers.keys())<EOL><DEDENT>for name in self.allowed_deserializers:<EOL><INDENT>if name not in self.deserializers:<EOL><INDENT>raise ImproperlyConfigured(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(name))<EOL><DEDENT><DEDENT>self.authentication = meta.get('<STR_LIT>')<EOL>if self.authentication is None:<EOL><INDENT>self.authentication = (authentication.Authentication(),)<EOL><DEDENT>self.authorization = meta.get('<STR_LIT>')<EOL>if self.authorization is None:<EOL><INDENT>self.authorization = authorization.Authorization()<EOL><DEDENT>

Initializes the options object and defaults configuration not
specified.

@param[in] meta
    Dictionary of the merged meta attributes.

@param[in] name
    Name of the resource class this is being instantiataed for.


@classmethod<EOL><INDENT>def redirect(cls, request, response):<DEDENT>

if cls.meta.legacy_redirect:<EOL><INDENT>if request.method in ('<STR_LIT:GET>', '<STR_LIT>',):<EOL><INDENT>response.status = http.client.MOVED_PERMANENTLY<EOL><DEDENT>else:<EOL><INDENT>response.status = http.client.TEMPORARY_REDIRECT<EOL><DEDENT><DEDENT>else:<EOL><INDENT>response.status = http.client.PERMANENT_REDIRECT<EOL><DEDENT>response.close()<EOL>

Redirect to the canonical URI for this resource.


@classmethod<EOL><INDENT>def view(cls, request, response):<DEDENT>

<EOL>test = cls.meta.trailing_slash<EOL>if test ^ request.path.endswith('<STR_LIT:/>'):<EOL><INDENT>path = request.path + '<STR_LIT:/>' if test else request.path[:-<NUM_LIT:1>]<EOL>response['<STR_LIT>'] = '<STR_LIT>'.format(<EOL>request.protocol.lower(),<EOL>request.host,<EOL>request.mount_point,<EOL>path,<EOL>'<STR_LIT:?>' + request.query if request.query else '<STR_LIT>')<EOL>return cls.redirect(request, response)<EOL><DEDENT>try:<EOL><INDENT>obj = cls(request, response)<EOL>request.bind(obj)<EOL>response.bind(obj)<EOL>obj._request = request<EOL>result = obj.dispatch(request, response)<EOL>if not response.asynchronous:<EOL><INDENT>if (isinstance(result, collections.Iterable) and<EOL>not isinstance(result, six.string_types)):<EOL><INDENT>return cls.stream(response, result)<EOL><DEDENT>else:<EOL><INDENT>response.end(result)<EOL>if response.body:<EOL><INDENT>return response.body<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except http.exceptions.BaseHTTPException as e:<EOL><INDENT>response.status = e.status<EOL>response.headers.update(e.headers)<EOL>if e.content:<EOL><INDENT>response.send(e.content, serialize=True, format='<STR_LIT>')<EOL><DEDENT>response.close()<EOL>if response.body:<EOL><INDENT>return response.body<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>logger.exception('<STR_LIT>')<EOL>if not response.streaming and not response.closed:<EOL><INDENT>response.status = http.client.INTERNAL_SERVER_ERROR<EOL>response.headers.clear()<EOL>response.close()<EOL><DEDENT><DEDENT>

Entry-point of the request / response cycle; Handles resource creation
and delegation.

@param[in] requset
    The HTTP request object; containing accessors for information
    about the request.

@param[in] response
    The HTTP response object; contains accessors for modifying
    the information that will be sent to the client.


<EOL>for resource, pattern in cls.meta.patterns:<EOL><INDENT>match = re.match(pattern, path)<EOL>if match is not None:<EOL><INDENT>return resource, match.groupdict(), match.string[match.end():]<EOL><DEDENT><DEDENT>return None if not cls.meta.patterns else False<EOL>

Parses out parameters and separates them out of the path.

        This uses one of the many defined patterns on the options class. But,
        it defaults to a no-op if there are no defined patterns.


@classmethod<EOL><INDENT>def traverse(cls, request, params=None):<DEDENT>

<EOL>result = cls.parse(request.path)<EOL>if result is None:<EOL><INDENT>return cls, {}<EOL><DEDENT>elif not result:<EOL><INDENT>raise http.exceptions.NotFound()<EOL><DEDENT>resource, data, rest = result<EOL>if params:<EOL><INDENT>data.update(params)<EOL><DEDENT>if resource is None:<EOL><INDENT>return cls, data<EOL><DEDENT>if data.get('<STR_LIT:path>') is not None:<EOL><INDENT>request.path = data.pop('<STR_LIT:path>')<EOL><DEDENT>elif rest is not None:<EOL><INDENT>request.path = rest<EOL><DEDENT>result = resource.traverse(request, params=data)<EOL>return result<EOL>

Traverses down the path and determines the accessed resource.

        This makes use of the patterns array to implement simple traversal.
        This defaults to a no-op if there are no defined patterns.


@classmethod<EOL><INDENT>def stream(cls, response, sequence):<DEDENT>

<EOL>iterator = iter(sequence)<EOL>data = {'<STR_LIT>': next(iterator)}<EOL>response.streaming = True<EOL>def streamer():<EOL><INDENT>while True:<EOL><INDENT>if response.asynchronous:<EOL><INDENT>yield data['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>response.send(data['<STR_LIT>'])<EOL>yield response.body<EOL>response.body = None<EOL><DEDENT>try:<EOL><INDENT>data['<STR_LIT>'] = next(iterator)<EOL><DEDENT>except StopIteration:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if not response.asynchronous:<EOL><INDENT>response.close()<EOL><DEDENT><DEDENT>return streamer()<EOL>

Helper method used in conjunction with the view handler to
stream responses to the client.


@utils.boundmethod<EOL><INDENT>def deserialize(self, request=None, text=None, format=None):<DEDENT>

if isinstance(self, Resource):<EOL><INDENT>if not request:<EOL><INDENT>request = self._request<EOL><DEDENT><DEDENT>Deserializer = None<EOL>if format:<EOL><INDENT>Deserializer = self.meta.deserializers[format]<EOL><DEDENT>if not Deserializer:<EOL><INDENT>media_ranges = request.get('<STR_LIT:Content-Type>')<EOL>if media_ranges:<EOL><INDENT>media_types = six.iterkeys(self._deserializer_map)<EOL>media_type = mimeparse.best_match(media_types, media_ranges)<EOL>if media_type:<EOL><INDENT>format = self._deserializer_map[media_type]<EOL>Deserializer = self.meta.deserializers[format]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if Deserializer:<EOL><INDENT>try:<EOL><INDENT>deserializer = Deserializer()<EOL>data = deserializer.deserialize(request=request, text=text)<EOL>return data, deserializer<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>raise http.exceptions.UnsupportedMediaType()<EOL>

Deserializes the text using a determined deserializer.

        @param[in] request
            The request object to pull information from; normally used to
            determine the deserialization format (when `format` is
            not provided).

        @param[in] text
            The text to be deserialized. Can be left blank and the
            request will be read.

        @param[in] format
            A specific format to deserialize in; if provided, no detection is
            done. If not provided, the content-type header is looked at to
            determine an appropriate deserializer.

        @returns
            A tuple of the deserialized data and an instance of the
            deserializer used.


@utils.boundmethod<EOL><INDENT>def serialize(self, data, response=None, request=None, format=None):<DEDENT>

if isinstance(self, Resource):<EOL><INDENT>if not request:<EOL><INDENT>request = self._request<EOL><DEDENT><DEDENT>Serializer = None<EOL>if format:<EOL><INDENT>Serializer = self.meta.serializers[format]<EOL><DEDENT>if not Serializer:<EOL><INDENT>media_ranges = (request.get('<STR_LIT>') or '<STR_LIT>').strip()<EOL>if not media_ranges:<EOL><INDENT>media_ranges = '<STR_LIT>'<EOL><DEDENT>if media_ranges != '<STR_LIT>':<EOL><INDENT>media_types = six.iterkeys(self._serializer_map)<EOL>media_type = mimeparse.best_match(media_types, media_ranges)<EOL>if media_type:<EOL><INDENT>format = self._serializer_map[media_type]<EOL>Serializer = self.meta.serializers[format]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>default = self.meta.default_serializer<EOL>Serializer = self.meta.serializers[default]<EOL><DEDENT><DEDENT>if Serializer:<EOL><INDENT>try:<EOL><INDENT>serializer = Serializer(request, response)<EOL>return serializer.serialize(data), serializer<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>available = {}<EOL>for name in self.meta.allowed_serializers:<EOL><INDENT>Serializer = self.meta.serializers[name]<EOL>instance = Serializer(request, None)<EOL>if instance.can_serialize(data):<EOL><INDENT>available[name] = Serializer.media_types[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>raise http.exceptions.NotAcceptable(available)<EOL>

Serializes the data using a determined serializer.

        @param[in] data
            The data to be serialized.

        @param[in] response
            The response object to serialize the data to.
            If this method is invoked as an instance method, the response
            object can be omitted and it will be taken from the instance.

        @param[in] request
            The request object to pull information from; normally used to
            determine the serialization format (when `format` is not provided).
            May be used by some serializers as well to pull additional headers.
            If this method is invoked as an instance method, the request
            object can be omitted and it will be taken from the instance.

        @param[in] format
            A specific format to serialize in; if provided, no detection is
            done. If not provided, the accept header (as well as the URL
            extension) is looked at to determine an appropriate serializer.

        @returns
            A tuple of the serialized text and an instance of the
            serializer used.


@classmethod<EOL><INDENT>def _process_cross_domain_request(cls, request, response):<DEDENT>

<EOL>origin = request.get('<STR_LIT>')<EOL>if not origin:<EOL><INDENT>return<EOL><DEDENT>if not (origin in cls.meta.http_allowed_origins or<EOL>'<STR_LIT:*>' == cls.meta.http_allowed_origins):<EOL><INDENT>return<EOL><DEDENT>method = request.get('<STR_LIT>')<EOL>if method and method not in cls.meta.http_allowed_methods:<EOL><INDENT>return<EOL><DEDENT>headers = request.get('<STR_LIT>', ())<EOL>if headers:<EOL><INDENT>headers = [h.strip() for h in headers.split('<STR_LIT:U+002C>')]<EOL><DEDENT>allowed_headers = [h.lower() for h in cls.meta.http_allowed_headers]<EOL>if any(h.lower() not in allowed_headers for h in headers):<EOL><INDENT>return<EOL><DEDENT>response['<STR_LIT>'] = origin<EOL>response['<STR_LIT>'] = '<STR_LIT:true>'<EOL>allowed_methods = '<STR_LIT:U+002CU+0020>'.join(cls.meta.http_allowed_methods)<EOL>response['<STR_LIT>'] = allowed_methods<EOL>allowed_headers = '<STR_LIT:U+002CU+0020>'.join(cls.meta.http_allowed_headers)<EOL>if allowed_headers:<EOL><INDENT>response['<STR_LIT>'] = allowed_headers<EOL><DEDENT>exposed_headers = '<STR_LIT:U+002CU+0020>'.join(cls.meta.http_exposed_headers)<EOL>if exposed_headers:<EOL><INDENT>response['<STR_LIT>'] = exposed_headers<EOL><DEDENT>

Facilitate Cross-Origin Requests (CORs).


<EOL>self.require_authentication(request)<EOL>self.require_accessibility(request.user, request.method)<EOL>self._process_cross_domain_request(request, response)<EOL>return self.route(request, response)<EOL>

Entry-point of the dispatch cycle for this resource.

        Performs common work such as authentication, decoding, etc. before
        handing complete control of the result to a function with the
        same name as the request method.


request.user = user = None<EOL>if request.method == '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>for auth in self.meta.authentication:<EOL><INDENT>user = auth.authenticate(request)<EOL>if user is False:<EOL><INDENT>continue<EOL><DEDENT>if user is None and not auth.allow_anonymous:<EOL><INDENT>auth.unauthenticated()<EOL><DEDENT>request.user = user<EOL>return<EOL><DEDENT>if not user and not auth.allow_anonymous:<EOL><INDENT>auth.unauthenticated()<EOL><DEDENT>


def require_accessibility(self, user, method):

if method == '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>authz = self.meta.authorization<EOL>if not authz.is_accessible(user, method, self):<EOL><INDENT>authz.unaccessible()<EOL><DEDENT>

Ensure we are allowed to access this resource.


allowed = cls.meta.http_allowed_methods<EOL>if request.method not in allowed:<EOL><INDENT>raise http.exceptions.MethodNotAllowed(allowed)<EOL><DEDENT>

Ensure that we're allowed to use this HTTP method.


<EOL>self.require_http_allowed_method(request)<EOL>function = getattr(self, request.method.lower(), None)<EOL>if function is None:<EOL><INDENT>raise http.exceptions.NotImplemented()<EOL><DEDENT>return function(request, response)<EOL>

Processes every request.

        Directs control flow to the appropriate HTTP/1.1 method.


<EOL>response['<STR_LIT>'] = '<STR_LIT:U+002CU+0020>'.join(self.meta.http_allowed_methods)<EOL>response.status = http.client.OK<EOL>

Process an `OPTIONS` request.

        Used to initiate a cross-origin request. All handling specific to
        CORS requests is done on every request however this method also
        returns a list of available methods.


str_list = [random.choice(string.digits + string.ascii_letters) for i in range(length)]<EOL>return '<STR_LIT>'.join(str_list)<EOL>

Generate random string with parameter length.
Example:

    >>> from eggit.egg_string import random_string
    >>> random_string(8)
    'q4f2eaT4'
    >>>


try:<EOL><INDENT>dtf = DTFormat()<EOL>struct_time = time.strptime(datetime_str, dtf.datetime_format)<EOL>return time.mktime(struct_time)<EOL><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT>

'2018-01-01 00:00:00' (str) --> 1514736000

:param str datetime_str: datetime string
:return: unix timestamp (int) or None
:rtype: int or None


try:<EOL><INDENT>dft = DTFormat()<EOL>return datetime.strptime(datetime_str, dft.datetime_format)<EOL><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT>

Get datetime object from datetime string

example:
    DateTimeUtils.get_datetime_object('2018-01-01 00:00:00')

:param str string: datetime string
:return: datetime object
:rtype: datetime


if isinstance(datetime_obj, datetime):<EOL><INDENT>dft = DTFormat()<EOL>return datetime_obj.strftime(dft.datetime_format)<EOL><DEDENT>return None<EOL>

Get datetime string from datetime object

:param datetime datetime_obj: datetime object
:return: datetime string
:rtype: str


dft = DTFormat()<EOL>return datetime.now().strftime(dft.datetime_format)<EOL>

Get now datetime str like '2018-01-01 00:00:00' (str)

:return: datetime string
:rtype: str


if isinstance(timestamp, (int, float, str)):<EOL><INDENT>try:<EOL><INDENT>timestamp = float(timestamp)<EOL>if timestamp.is_integer():<EOL><INDENT>timestamp = int(timestamp)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT>temp = str(timestamp).split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>if len(temp) == <NUM_LIT>:<EOL><INDENT>timestamp = timestamp / <NUM_LIT><EOL><DEDENT>if len(temp) < <NUM_LIT:10>:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>return datetime.fromtimestamp(timestamp)<EOL>

1514736000 --> datetime object

:param int timestamp: unix timestamp (int)
:return: datetime object or None
:rtype: datetime or None


return DateTimeUtils.get_datetime_string(DateTimeUtils.timestamp_to_datetime(timestamp))<EOL>

1514736000 --> '2018-01-01 00:00:00' (str)

:param int timestamp: unix timestamp
:return: datetime str
:rtype: str


try:<EOL><INDENT>return int(str_val)<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT>

Convert string to int::

    >>> from eggit.converters import Converter
    >>> result = Converter.str_to_int('123')
    >>> print(result)
    123
    >>> result = Converter.str_to_int('abc')
    >>> print(result)
    None
    >>> result = Converter.str_to_int('1.2')
    >>> print(result)
    None

:param str str_val: the string value
:return: the target integer value
:rtype: int or None


if (str_val.lower() == '<STR_LIT:true>'):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Convert string to boolean::

    >>> from eggit.converters import Converter
    >>> Converter.str_to_bool('True')  # or true
    True
    >>> Converter.str_to_bool('False')  # or false
    False
    >>> Converter.str_to_bool('OtherString')
    False

:param str_val: the source string value
:return: the target boolean value
:rtype: bool


def __init__(self, current_page, total_page_count, items, total_item_count, page_size=<NUM_LIT:10>):

self.current_page = current_page<EOL>self.total_page_count = total_page_count<EOL>self.items = items<EOL>self.total_item_count = total_item_count<EOL>self.page_size = page_size<EOL>

:param int current_page: Current page number
:param int total_page_count: Total page count
:param object items: Paging data
:param int total_item_count: Total item count
:param int page_size: How many items per page


return dict(<EOL>current_page=self.current_page,<EOL>total_page_count=self.total_page_count,<EOL>items=self.items,<EOL>total_item_count=self.total_item_count,<EOL>page_size=self.page_size<EOL>)<EOL>

Convert Paginator instance to dict

:return: Paging data
:rtype: dict


with open(path, '<STR_LIT:r>') as f:<EOL><INDENT>_cookies = {}<EOL>for row in f.read().split('<STR_LIT:;>'):<EOL><INDENT>k, v = row.strip().split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>_cookies[k] = v<EOL><DEDENT>return _cookies<EOL><DEDENT>

将 cookie 字符串转化为字典

:param path: cookies 文件路径
:return: cookies 字典


if os.path.exists(directory):<EOL><INDENT>if os.path.isdir(directory):<EOL><INDENT>for d in os.listdir(directory):<EOL><INDENT>path = os.path.join(directory, d)<EOL>if os.path.isdir(path):<EOL><INDENT>delete_empty_dir(path)<EOL><DEDENT><DEDENT><DEDENT>if not os.listdir(directory):<EOL><INDENT>os.rmdir(directory)<EOL>print("<STR_LIT>" + directory)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>


print("<STR_LIT>".format(label))<EOL>for index, stat in enumerate(stats):<EOL><INDENT>if index < limit:<EOL><INDENT>print(stat)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>


def wrapper(func):<EOL><INDENT>@wraps(func)<EOL>def inner(*args, **kwargs):<EOL><INDENT>tracemalloc.start()<EOL>_start = tracemalloc.take_snapshot()<EOL>_result = func(*args, **kwargs)<EOL>_end = tracemalloc.take_snapshot()<EOL>stats = _end.compare_to(_start, group_by)<EOL>_print(stats, limit, func.__name__ + '<STR_LIT>')<EOL>return _result<EOL><DEDENT>return inner<EOL><DEDENT>return wrapper<EOL>

追踪函数内存消耗情况

:param group_by: 统计分组，有 'filename', 'lineno', 'traceback' 可选
:param limit: 限制输出行数


@contextmanager<EOL>def memoryit_block(group_by='<STR_LIT>', limit=<NUM_LIT:10>, label='<STR_LIT>'):

tracemalloc.start()<EOL>_start = tracemalloc.take_snapshot()<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>_end = tracemalloc.take_snapshot()<EOL>stats = _end.compare_to(_start, group_by)<EOL>_print(stats, limit, label)<EOL><DEDENT>

追踪代码块内存消耗情况

:param group_by: 统计分组，有 'filename', 'lineno', 'traceback' 可选
:param limit: 限制输出行数
:param label: 代码块标签


return '<STR_LIT>'.format(string)<EOL>


start = time.time()<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>_format(unit, time.time() - start, label)<EOL><DEDENT>

测试代码块耗时

:param unit: 时间单位，有 's','m','h' 可选（seconds，minutes，hours）
:param label: 代码块标签


def wrapper(func):<EOL><INDENT>@wraps(func)<EOL>def inner(*args, **kwargs):<EOL><INDENT>start = time.time()<EOL>_result = func(*args, **kwargs)<EOL>_format(unit, time.time() - start, func.__name__ + '<STR_LIT>')<EOL>return _result<EOL><DEDENT>return inner<EOL><DEDENT>return wrapper<EOL>

测试函数耗时

:param unit: 时间单位，有 's','m','h' 可选（seconds，minutes，hours）


def wrapper(func):<EOL><INDENT>@wraps(func)<EOL>def inner(*args, **kwargs):<EOL><INDENT>pro = Profile()<EOL>pro.runcall(func, *args, **kwargs)<EOL>stats = Stats(pro)<EOL>stats.strip_dirs()<EOL>stats.sort_stats(field)<EOL>print("<STR_LIT>".format(func.__name__))<EOL>stats.print_stats()<EOL>stats.print_callers()<EOL><DEDENT>return inner<EOL><DEDENT>return wrapper<EOL>

测试函数运行消耗情况

:param field: 输出内容排序方式。
    可选参数为 "stdname", "calls", "time", "cumulative"


def dump(obj, fp, startindex=<NUM_LIT:1>, separator=DEFAULT, index_separator=DEFAULT):

if startindex < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(startindex))<EOL><DEDENT>try:<EOL><INDENT>firstkey = next(iter(obj.keys()))<EOL><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT>if isinstance(firstkey, six.text_type):<EOL><INDENT>converter = six.u<EOL><DEDENT>else:<EOL><INDENT>converter = six.b<EOL><DEDENT>default_separator = converter('<STR_LIT:|>')<EOL>default_index_separator = converter('<STR_LIT:_>')<EOL>newline = converter('<STR_LIT:\n>')<EOL>if separator is DEFAULT:<EOL><INDENT>separator = default_separator<EOL><DEDENT>if index_separator is DEFAULT:<EOL><INDENT>index_separator = default_index_separator<EOL><DEDENT>for key, value in six.iteritems(obj):<EOL><INDENT>if isinstance(value, (list, tuple, set)):<EOL><INDENT>for index, item in enumerate(value, start=startindex):<EOL><INDENT>fp.write(key)<EOL>fp.write(index_separator)<EOL>fp.write(converter(str(index)))<EOL>fp.write(separator)<EOL>fp.write(item)<EOL>fp.write(newline)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fp.write(key)<EOL>fp.write(separator)<EOL>fp.write(value)<EOL>fp.write(newline)<EOL><DEDENT><DEDENT>

Dump an object in req format to the fp given.

    :param Mapping obj: The object to serialize.  Must have a keys method.
    :param fp: A writable that can accept all the types given.
    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.
    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.


def dumps(obj, startindex=<NUM_LIT:1>, separator=DEFAULT, index_separator=DEFAULT):

try:<EOL><INDENT>firstkey = next(iter(obj.keys()))<EOL><DEDENT>except StopIteration:<EOL><INDENT>return str()<EOL><DEDENT>if isinstance(firstkey, six.text_type):<EOL><INDENT>io = StringIO()<EOL><DEDENT>else:<EOL><INDENT>io = BytesIO()<EOL><DEDENT>dump(<EOL>obj=obj,<EOL>fp=io,<EOL>startindex=startindex,<EOL>separator=separator,<EOL>index_separator=index_separator,<EOL>)<EOL>return io.getvalue()<EOL>

Dump an object in req format to a string.

    :param Mapping obj: The object to serialize.  Must have a keys method.
    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.
    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.


def load(fp, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):

converter = None<EOL>output = cls()<EOL>arraykeys = set()<EOL>for line in fp:<EOL><INDENT>if converter is None:<EOL><INDENT>if isinstance(line, six.text_type):<EOL><INDENT>converter = six.u<EOL><DEDENT>else:<EOL><INDENT>converter = six.b<EOL><DEDENT>default_separator = converter('<STR_LIT:|>')<EOL>default_index_separator = converter('<STR_LIT:_>')<EOL>newline = converter('<STR_LIT:\n>')<EOL>if separator is DEFAULT:<EOL><INDENT>separator = default_separator<EOL><DEDENT>if index_separator is DEFAULT:<EOL><INDENT>index_separator = default_index_separator<EOL><DEDENT><DEDENT>key, value = line.strip().split(separator, <NUM_LIT:1>)<EOL>keyparts = key.split(index_separator)<EOL>try:<EOL><INDENT>index = int(keyparts[-<NUM_LIT:1>])<EOL>endwithint = True<EOL><DEDENT>except ValueError:<EOL><INDENT>endwithint = False<EOL><DEDENT>if len(keyparts) > <NUM_LIT:1> and endwithint:<EOL><INDENT>basekey = key.rsplit(index_separator, <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>if basekey not in arraykeys:<EOL><INDENT>arraykeys.add(basekey)<EOL><DEDENT>if basekey in output:<EOL><INDENT>if not isinstance(output[basekey], dict):<EOL><INDENT>output[basekey] = {-<NUM_LIT:1>: output[basekey]}<EOL><DEDENT><DEDENT>else:<EOL><INDENT>output[basekey] = {}<EOL><DEDENT>output[basekey][index] = value<EOL><DEDENT>else:<EOL><INDENT>if key in output and isinstance(output[key], dict):<EOL><INDENT>output[key][-<NUM_LIT:1>] = value<EOL><DEDENT>else:<EOL><INDENT>output[key] = value<EOL><DEDENT><DEDENT><DEDENT>for key in arraykeys:<EOL><INDENT>output[key] = list_cls(pair[<NUM_LIT:1>] for pair in sorted(six.iteritems(output[key])))<EOL><DEDENT>return output<EOL>

Load an object from the file pointer.

    :param fp: A readable filehandle.
    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.
    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.
    :param cls: A callable that returns a Mapping that is filled with pairs.  The most common alternate option would be OrderedDict.
    :param list_cls: A callable that takes an iterable and returns a sequence.


def loads(s, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):

if isinstance(s, six.text_type):<EOL><INDENT>io = StringIO(s)<EOL><DEDENT>else:<EOL><INDENT>io = BytesIO(s)<EOL><DEDENT>return load(<EOL>fp=io,<EOL>separator=separator,<EOL>index_separator=index_separator,<EOL>cls=cls,<EOL>list_cls=list_cls,<EOL>)<EOL>

Loads an object from a string.

    :param s: An object to parse
    :type s: bytes or str
    :param separator: The separator between key and value.  Defaults to u'|' or b'|', depending on the types.
    :param index_separator: The separator between key and index.  Defaults to u'_' or b'_', depending on the types.
    :param cls: A callable that returns a Mapping that is filled with pairs.  The most common alternate option would be OrderedDict.
    :param list_cls: A callable that takes an iterable and returns a sequence.


encoded = urlsafe_b64encode(data)<EOL>return encoded.replace(b'<STR_LIT:=>', b'<STR_LIT>')<EOL>

:param data: Data the encode.
:type data: bytes
:return: Base 64 encoded data with padding removed.
:rtype: bytes


missing_padding = len(data) % <NUM_LIT:4><EOL>if missing_padding != <NUM_LIT:0>:<EOL><INDENT>data += b'<STR_LIT:=>' * (<NUM_LIT:4> - missing_padding)<EOL><DEDENT>return urlsafe_b64decode(data)<EOL>

:param data: Base 64 encoded data to decode.
:type data: bytes
:return: Base 64 decoded data.
:rtype: bytes