def Func(arg_0, arg_1, arg_2=False):
        """Return the isotope parent of a given molecule.

        The isotope parent has all atoms replaced with the most abundant isotope for that element.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :param bool skip_standardize: Set to True if mol has already been standardized.
        :returns: The isotope parent molecule.
        :rtype: rdkit.Chem.rdchem.Mol
        """
        if not arg_2:
            arg_1 = arg_0.standardize(arg_1)
        else:
            arg_1 = copy.deepcopy(arg_1)
        # Replace isotopes with common weight
        for arg_3 in arg_1.GetAtoms():
            arg_3.SetIsotope(0)
        return arg_1


def Func(arg_0, arg_1, arg_2=False):
        """Return the super parent of a given molecule.

        THe super parent is fragment, charge, isotope, stereochemistry and tautomer insensitive. From the input
        molecule, the largest fragment is taken. This is uncharged and then isotope and stereochemistry information is
        discarded. Finally, the canonical tautomer is determined and returned.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :param bool skip_standardize: Set to True if mol has already been standardized.
        :returns: The super parent molecule.
        :rtype: rdkit.Chem.rdchem.Mol
        """
        if not arg_2:
            arg_1 = arg_0.standardize(arg_1)
        # We don't need to get fragment parent, because the charge parent is the largest fragment
        arg_1 = arg_0.charge_parent(arg_1, arg_2=True)
        arg_1 = arg_0.isotope_parent(arg_1, arg_2=True)
        arg_1 = arg_0.stereo_parent(arg_1, arg_2=True)
        arg_1 = arg_0.tautomer_parent(arg_1, arg_2=True)
        arg_1 = arg_0.standardize(arg_1)
        return arg_1


def Func():
    """Main function for molvs command line interface."""

    # Root options
    arg_0 = MolvsParser(epilog='use "molvs <command> -h" to show help for a specific command')
    arg_1 = arg_0.add_subparsers(title='Available commands')

    # Options common to all commands

    arg_2 = MolvsParser(add_help=False)
    arg_2.add_argument('infile', nargs='?', help='input filename', type=argparse.FileType('r'), default=sys.stdin)
    arg_2.add_argument('-i', '--intype', help='input filetype', choices=FILETYPES)
    arg_2.add_argument('-:', '--smiles', help='input SMILES instead of file', metavar='<smiles>')
    arg_2.add_argument('-O', '--outfile', help='output filename', type=argparse.FileType('w'), default=sys.stdout, metavar='<outfile>')

    # Standardize options
    arg_3 = arg_1.add_parser('standardize', help='standardize a molecule', parents=[arg_2])
    arg_3.add_argument('-o', '--outtype', help='output filetype', choices=FILETYPES)
    arg_3.set_defaults(func=standardize_Func)

    # Validate options
    arg_4 = arg_1.add_parser('validate', help='validate a molecule', parents=[arg_2])
    arg_4.set_defaults(func=validate_Func)

    arg_5 = arg_0.parse_args()
    try:
        arg_5.func(arg_5)
    except Exception as e:
        sys.stderr.write('Error: %s\n\n'.encode() % e.message)
        arg_0.print_help()
        sys.exit(2)


def Func(arg_0, arg_1):
        """Return the molecule with specified fragments Funcd.

        :param mol: The molecule to Func fragments from.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: The molecule with fragments Funcd.
        :rtype: rdkit.Chem.rdchem.Mol
        """
        log.debug('Running FragmentRemover')
        # Iterate FragmentPatterns and Func matching fragments
        for arg_2 in arg_0.fragments:
            # If nothing is left or leave_last and only one fragment, end here
            if arg_1.GetNumAtoms() == 0 or (arg_0.leave_last and len(Chem.GetMolFrags(arg_1)) <= 1):
                break
            # Apply removal for this FragmentPattern
            arg_3 = Chem.DeleteSubstructs(arg_1, arg_2.smarts, onlyFrags=True)
            if not arg_1.GetNumAtoms() == arg_3.GetNumAtoms():
                log.info('Removed fragment: %s', arg_2.name)
            if arg_0.leave_last and arg_3.GetNumAtoms() == 0:
                # All the remaining fragments match this pattern - leave them all
                break
            arg_1 = arg_3
        return arg_1


def Func(arg_0, arg_1):
        """Return the largest covalent unit.

        The largest fragment is determined by number of atoms (including hydrogens). Ties are broken by taking the
        fragment with the higher molecular weight, and then by taking the first alphabetically by SMILES if needed.

        :param mol: The molecule to Func the largest fragment from.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: The largest fragment.
        :rtype: rdkit.Chem.rdchem.Mol
        """
        log.debug('Running LargestFragmentChooser')
        # TODO: Alternatively allow a list of fragments to be passed as the mol parameter
        arg_2 = Chem.GetMolFrags(arg_1, asMols=True)
        arg_3 = None
        for arg_4 in arg_2:
            arg_5 = Chem.MolToSmiles(arg_4, isomericSmiles=True)
            log.debug('Fragment: %s', arg_5)
            arg_6 = is_organic(arg_4)
            if arg_0.prefer_organic:
                # Skip this fragment if not organic and we already have an organic fragment as the largest so far
                if arg_3 and arg_3['organic'] and not arg_6:
                    continue
                # Reset largest if it wasn't organic and this fragment is organic
                if arg_3 and arg_6 and not arg_3['organic']:
                    arg_3 = None
            # Count atoms
            arg_7 = 0
            for arg_8 in arg_4.GetAtoms():
                arg_7 += 1 + arg_8.GetTotalNumHs()
            # Skip this fragment if fewer atoms than the largest
            if arg_3 and arg_7 < arg_3['atoms']:
                continue
            # Skip this fragment if equal number of atoms but weight is lower
            arg_9 = rdMolDescriptors.CalcExactMolWt(arg_4)
            if arg_3 and arg_7 == arg_3['atoms'] and arg_9 < arg_3['weight']:
                continue
            # Skip this fragment if equal atoms and equal weight but smiles comes last alphabetically
            if arg_3 and arg_7 == arg_3['atoms'] and arg_9 == arg_3['weight'] and arg_5 > arg_3['smiles']:
                continue
            # Otherwise this is the largest so far
            log.debug('New largest fragment: %s (%s)', arg_5, arg_7)
            arg_3 = {'smiles': arg_5, 'fragment': arg_4, 'atoms': arg_7, 'weight': arg_9, 'organic': arg_6}
        return arg_3['fragment']


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """Construct a constraint from a validation function.

        Args:
            func (function):
                Function that evaluates True when the variables satisfy the constraint.

            variables (iterable):
                Iterable of variable labels.

            vartype (:class:`~dimod.Vartype`/str/set):
                Variable type for the constraint. Accepted input values:

                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

            name (string, optional, default='Constraint'):
                Name for the constraint.

        Examples:
            This example creates a constraint that binary variables `a` and `b`
            are not equal.

            >>> import dwavebinarycsp
            >>> import operator
            >>> const = dwavebinarycsp.Constraint.Func(operator.ne, ['a', 'b'], 'BINARY')
            >>> print(const.name)
            Constraint
            >>> (0, 1) in const.configurations
            True

            This example creates a constraint that :math:`out = NOT(x)`
            for spin variables.

            >>> import dwavebinarycsp
            >>> def not_(y, x):  # y=NOT(x) for spin variables
            ...     return (y == -x)
            ...
            >>> const = dwavebinarycsp.Constraint.Func(
            ...               not_,
            ...               ['out', 'in'],
            ...               {1, -1},
            ...               name='not_spin')
            >>> print(const.name)
            not_spin
            >>> (1, -1) in const.configurations
            True

        """
        arg_2 = tuple(arg_2)

        arg_5 = frozenset(config
                                   for config in itertools.product(arg_3.value, repeat=len(arg_2))
                                   if arg_1(*config))

        return arg_0(arg_1, arg_5, arg_2, arg_3, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """Construct a constraint from valid configurations.

        Args:
            configurations (iterable[tuple]):
                Valid configurations of the variables. Each configuration is a tuple of variable
                assignments ordered by :attr:`~Constraint.variables`.

            variables (iterable):
                Iterable of variable labels.

            vartype (:class:`~dimod.Vartype`/str/set):
                Variable type for the constraint. Accepted input values:

                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

            name (string, optional, default='Constraint'):
                Name for the constraint.

        Examples:

            This example creates a constraint that variables `a` and `b` are not equal.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.Func([(0, 1), (1, 0)],
            ...                   ['a', 'b'], dwavebinarycsp.BINARY)
            >>> print(const.name)
            Constraint
            >>> (0, 0) in const.configurations   # Order matches variables: a,b
            False

            This example creates a constraint based on specified valid configurations
            that represents an OR gate for spin variables.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.Func(
            ...           [(-1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)],
            ...           ['y', 'x1', 'x2'],
            ...           dwavebinarycsp.SPIN, name='or_spin')
            >>> print(const.name)
            or_spin
            >>> (1, 1, -1) in const.configurations   # Order matches variables: y,x1,x2
            True

        """
        def func(*arg_5): return arg_5 in arg_1

        return arg_0(func, arg_1, arg_2, arg_3, arg_4)


def Func(arg_0, arg_1):
        """Check that a solution satisfies the constraint.

        Args:
            solution (container):
                An assignment for the variables in the constraint.

        Returns:
            bool: True if the solution satisfies the constraint; otherwise False.

        Examples:
            This example creates a constraint that :math:`a \\ne b` on binary variables
            and tests it for two candidate solutions, with additional unconstrained
            variable c.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],
            ...             ['a', 'b'], dwavebinarycsp.BINARY)
            >>> solution = {'a': 1, 'b': 1, 'c': 0}
            >>> const.Func(solution)
            False
            >>> solution = {'a': 1, 'b': 0, 'c': 0}
            >>> const.Func(solution)
            True

        """
        return arg_0.func(*(arg_1[arg_2] for arg_2 in arg_0.variables))


def Func(arg_0, arg_1):
        """Flip a variable in the constraint.

        Args:
            v (variable):
                Variable in the constraint to take the complementary value of its
                construction value.

        Examples:
            This example creates a constraint that :math:`a = b` on binary variables
            and flips variable a.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.from_func(operator.eq,
            ...             ['a', 'b'], dwavebinarycsp.BINARY)
            >>> const.check({'a': 0, 'b': 0})
            True
            >>> const.Func('a')
            >>> const.check({'a': 1, 'b': 0})
            True
            >>> const.check({'a': 0, 'b': 0})
            False

        """
        try:
            arg_2 = arg_0.variables.index(arg_1)
        except ValueError:
            raise ValueError("variable {} is not a variable in constraint {}".format(arg_1, arg_0.name))

        if arg_0.vartype is dimod.BINARY:

            arg_3 = arg_0.func

            def arg_6(*arg_4):
                arg_5 = list(arg_4)
                arg_5[arg_2] = 1 - arg_5[arg_2]  # negate v
                return arg_3(*arg_5)

            arg_0.func = arg_6

            arg_0.configurations = frozenset(config[:arg_2] + (1 - config[arg_2],) + config[arg_2 + 1:]
                                            for config in arg_0.configurations)

        else:  # SPIN

            arg_3 = arg_0.func

            def arg_6(*arg_4):
                arg_5 = list(arg_4)
                arg_5[arg_2] = -arg_5[arg_2]  # negate v
                return arg_3(*arg_5)

            arg_0.func = arg_6

            arg_0.configurations = frozenset(config[:arg_2] + (-config[arg_2],) + config[arg_2 + 1:]
                                            for config in arg_0.configurations)

        arg_0.name = '{} ({} flipped)'.format(arg_0.name, arg_1)


def Func(arg_0, arg_1, arg_2=arg_3()):
        """Add a constraint.

        Args:
            constraint (function/iterable/:obj:`.Constraint`):
                Constraint definition in one of the supported formats:

                1. Function, with input arguments matching the order and
                   :attr:`~.ConstraintSatisfactionProblem.vartype` type of the `variables`
                   argument, that evaluates True when the constraint is satisfied.
                2. List explicitly specifying each allowed configuration as a tuple.
                3. :obj:`.Constraint` object built either explicitly or by :mod:`dwavebinarycsp.factories`.

            variables(iterable):
                Variables associated with the constraint. Not required when `constraint` is
                a :obj:`.Constraint` object.

        Examples:
            This example defines a function that evaluates True when the constraint is satisfied.
            The function's input arguments match the order and type of the `variables` argument.

            >>> import dwavebinarycsp
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
            >>> def all_equal(a, b, c):  # works for both dwavebinarycsp.BINARY and dwavebinarycsp.SPIN
            ...     return (a == b) and (b == c)
            >>> csp.Func(all_equal, ['a', 'b', 'c'])
            >>> csp.check({'a': 0, 'b': 0, 'c': 0})
            True
            >>> csp.check({'a': 0, 'b': 0, 'c': 1})
            False

            This example explicitly lists allowed configurations.

            >>> import dwavebinarycsp
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
            >>> eq_configurations = {(-1, -1), (1, 1)}
            >>> csp.Func(eq_configurations, ['v0', 'v1'])
            >>> csp.check({'v0': -1, 'v1': +1})
            False
            >>> csp.check({'v0': -1, 'v1': -1})
            True

            This example uses a :obj:`.Constraint` object built by :mod:`dwavebinarycsp.factories`.

            >>> import dwavebinarycsp
            >>> import dwavebinarycsp.factories.constraint.gates as gates
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
            >>> csp.Func(gates.and_gate(['a', 'b', 'c']))  # add an AND gate
            >>> csp.Func(gates.xor_gate(['a', 'c', 'd']))  # add an XOR gate
            >>> csp.check({'a': 1, 'b': 0, 'c': 0, 'd': 1})
            True

        """
        if isinstance(arg_1, Constraint):
            if arg_2 and (arg_3(arg_2) != arg_1.variables):
                raise ValueError("mismatched variables and Constraint")
        elif isinstance(arg_1, Callable):
            arg_1 = Constraint.from_func(arg_1, arg_2, arg_0.vartype)
        elif isinstance(arg_1, Iterable):
            arg_1 = Constraint.from_configurations(arg_1, arg_2, arg_0.vartype)
        else:
            raise TypeError("Unknown constraint type given")

        arg_0.constraints.append(arg_1)
        for arg_4 in arg_1.variables:
            arg_0.variables[arg_4].append(arg_1)


def Func(arg_0, arg_1=2.0, arg_2=8):
    """Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction
    problem.

    Args:
        csp (:obj:`.ConstraintSatisfactionProblem`):
            Constraint satisfaction problem.

        min_classical_gap (float, optional, default=2.0):
            Minimum energy gap from ground. Each constraint violated by the solution increases
            the energy level of the binary quadratic model by at least this much relative
            to ground energy.

        max_graph_size (int, optional, default=8):
            Maximum number of variables in the binary quadratic model that can be used to
            represent a single constraint.

    Returns:
        :class:`~dimod.BinaryQuadraticModel`

    Notes:
        For a `min_classical_gap` > 2 or constraints with more than two variables, requires
        access to factories from the penaltymodel_ ecosystem to construct the binary quadratic
        model.

    .. _penaltymodel: https://github.com/dwavesystems/penaltymodel

    Examples:
        This example creates a binary-valued constraint satisfaction problem
        with two constraints, :math:`a = b` and :math:`b \\ne c`, and builds
        a binary quadratic model with a minimum energy level of -2 such that
        each constraint violation by a solution adds the default minimum energy gap.

        >>> import dwavebinarycsp
        >>> import operator
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b
        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c
        >>> bqm = dwavebinarycsp.Func(csp)
        >>> bqm.energy({'a': 0, 'b': 0, 'c': 1})  # satisfies csp
        -2.0
        >>> bqm.energy({'a': 0, 'b': 0, 'c': 0})  # violates one constraint
        0.0
        >>> bqm.energy({'a': 1, 'b': 0, 'c': 0}) # violates two constraints
        2.0

        This example creates a binary-valued constraint satisfaction problem
        with two constraints, :math:`a = b` and :math:`b \\ne c`, and builds
        a binary quadratic model with a minimum energy gap of 4.
        Note that in this case the conversion to binary quadratic model adds two
        ancillary variables that must be minimized over when solving.

        >>> import dwavebinarycsp
        >>> import operator
        >>> import itertools
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b
        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c
        >>> bqm = dwavebinarycsp.Func(csp, min_classical_gap=4.0)
        >>> list(bqm)   # # doctest: +SKIP
        ['a', 'aux1', 'aux0', 'b', 'c']
        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 1, 'aux0': aux0, 'aux1': aux1}) for
        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # satisfies csp
        -6.0
        >>> min([bqm.energy({'a': 0, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for
        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates one constraint
        -2.0
        >>> min([bqm.energy({'a': 1, 'b': 0, 'c': 0, 'aux0': aux0, 'aux1': aux1}) for
        ... aux0, aux1 in list(itertools.product([0, 1], repeat=2))])  # violates two constraints
        2.0

        This example finds for the previous example the minimum graph size.

        >>> import dwavebinarycsp
        >>> import operator
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(operator.eq, ['a', 'b'])  # a == b
        >>> csp.add_constraint(operator.ne, ['b', 'c'])  # b != c
        >>> for n in range(8, 1, -1):
        ...     try:
        ...         bqm = dwavebinarycsp.Func(csp, min_classical_gap=4.0, max_graph_size=n)
        ...     except dwavebinarycsp.exceptions.ImpossibleBQM:
        ...         print(n+1)
        ...
        3

    """

    # ensure we have penaltymodel factory available
    try:
        dwavebinarycsp.assert_penaltymodel_factory_available()
    except AssertionError as e:
        raise RuntimeError(e)

    def aux_factory():
        for arg_3 in count():
            yield 'aux{}'.format(arg_3)

    arg_4 = aux_factory()

    arg_5 = dimod.BinaryQuadraticModel.empty(arg_0.vartype)

    # developer note: we could cache them and relabel, for now though let's do the simple thing
    # penalty_models = {}
    for arg_6 in arg_0.constraints:
        arg_7 = arg_6.configurations

        if len(arg_6.variables) > arg_2:
            arg_8 = ("The given csp contains a constraint {const} with {num_var} variables. "
                   "This cannot be mapped to a graph with {max_graph_size} nodes. "
                   "Consider checking whether your constraint is irreducible."
                   "").format(arg_6=arg_6, num_var=len(arg_6.variables), arg_2=arg_2)
            raise ImpossibleBQM(arg_8)

        arg_9 = None

        if len(arg_6) == 0:
            # empty constraint
            continue

        if arg_1 <= 2.0:
            if len(arg_6) == 1 and arg_2 >= 1:
                arg_5.update(_bqm_from_1sat(arg_6))
                continue
            elif len(arg_6) == 2 and arg_2 >= 2:
                arg_5.update(_bqm_from_2sat(arg_6))
                continue

        # developer note: we could cache them and relabel, for now though let's do the simple thing
        # if configurations in penalty_models:
        #     raise NotImplementedError

        for arg_10 in iter_complete_graphs(arg_6.variables, arg_2 + 1, arg_4):

            # construct a specification
            spec = pm.Specification(
                graph=arg_10,
                decision_variables=arg_6.variables,
                feasible_configurations=arg_7,
                arg_1=arg_1,
                vartype=arg_0.vartype
            )

            # try to use the penaltymodel ecosystem
            try:
                arg_9 = pm.get_penalty_model(spec)
            except pm.ImpossiblePenaltyModel:
                # hopefully adding more variables will make it possible
                continue

            if arg_9.classical_gap >= arg_1:
                break

        # developer note: we could cache them and relabel, for now though let's do the simple thing
        # penalty_models[configurations] = pmodel

        else:
            arg_8 = ("No penalty model can be build for constraint {}".format(arg_6))
            raise ImpossibleBQM(arg_8)

        arg_5.update(arg_9.model)

    return arg_5


def Func(arg_0):
    """create a bqm for a constraint with two variables.

    bqm will have exactly classical gap 2.
    """
    arg_1 = arg_0.configurations
    arg_2 = arg_0.variables
    arg_3 = arg_0.vartype
    arg_4, arg_5 = arg_0.variables

    # if all configurations are present, then nothing is infeasible and the bqm is just all
    # 0.0s
    if len(arg_1) == 4:
        return dimod.BinaryQuadraticModel.empty(arg_0.vartype)

    # check if the constraint is irreducible, and if so, build the bqm for its two
    # components
    arg_6 = irreducible_components(arg_0)
    if len(arg_6) > 1:
        arg_7 = Constraint.from_configurations(((arg_10[0],) for arg_10 in arg_1),
                                                (arg_4,), arg_3)
        arg_8 = Constraint.from_configurations(((arg_10[1],) for arg_10 in arg_1),
                                                (arg_5,), arg_3)
        arg_9 = _bqm_from_1sat(arg_7)
        arg_9.update(_bqm_from_1sat(arg_8))
        return arg_9

    assert len(arg_1) > 1, "single configurations should be irreducible"

    # if it is not irreducible, and there are infeasible configurations, then it is time to
    # start building a bqm
    arg_9 = dimod.BinaryQuadraticModel.empty(arg_3)

    # if the constraint is not irreducible and has two configurations, then it is either eq or ne
    if all(operator.eq(*arg_10) for arg_10 in arg_1):
        arg_9.add_interaction(arg_4, arg_5, -1, arg_3=dimod.SPIN)  # equality
    elif all(operator.ne(*arg_10) for arg_10 in arg_1):
        arg_9.add_interaction(arg_4, arg_5, +1, arg_3=dimod.SPIN)  # inequality
    elif (1, 1) not in arg_1:
        arg_9.add_interaction(arg_4, arg_5, 2, arg_3=dimod.BINARY)  # penalize (1, 1)
    elif (-1, +1) not in arg_1 and (0, 1) not in arg_1:
        arg_9.add_interaction(arg_4, arg_5, -2, arg_3=dimod.BINARY)
        arg_9.add_variable(arg_5, 2, arg_3=dimod.BINARY)
    elif (+1, -1) not in arg_1 and (1, 0) not in arg_1:
        arg_9.add_interaction(arg_4, arg_5, -2, arg_3=dimod.BINARY)
        arg_9.add_variable(arg_4, 2, arg_3=dimod.BINARY)
    else:
        # (0, 0) not in configurations
        arg_9.add_interaction(arg_4, arg_5, 2, arg_3=dimod.BINARY)
        arg_9.add_variable(arg_4, -2, arg_3=dimod.BINARY)
        arg_9.add_variable(arg_5, -2, arg_3=dimod.BINARY)

    return arg_9


def Func(arg_0, arg_1=arg_2.BINARY, arg_4='AND'):
    """AND gate.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, out]`,
            where `in1, in2` are inputs and `out` the gate's output.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='AND'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of an AND gate.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.Func(['a', 'b', 'c'], name='AND1'))
        >>> csp.check({'a': 1, 'b': 0, 'c': 0})
        True
    """

    arg_0 = tuple(arg_0)

    if arg_1 is arg_2.BINARY:
        arg_5 = frozenset([(0, 0, 0),
                                    (0, 1, 0),
                                    (1, 0, 0),
                                    (1, 1, 1)])

        def func(arg_6, arg_7, arg_8): return (arg_6 and arg_7) == arg_8

    else:
        # SPIN, vartype is checked by the decorator
        arg_5 = frozenset([(-1, -1, -1),
                                    (-1, +1, -1),
                                    (+1, -1, -1),
                                    (+1, +1, +1)])

        def func(arg_6, arg_7, arg_8): return ((arg_6 > 0) and (arg_7 > 0)) == (arg_8 > 0)

    return Constraint(func, arg_5, arg_0, arg_1=arg_1, arg_4=arg_4)


def Func(arg_0, arg_1=arg_2.BINARY, arg_4='XOR'):
    """XOR gate.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, out]`,
            where `in1, in2` are inputs and `out` the gate's output.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='XOR'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of an XOR gate.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.Func(['x', 'y', 'z'], name='XOR1'))
        >>> csp.check({'x': 1, 'y': 1, 'z': 1})
        False
    """

    arg_0 = tuple(arg_0)
    if arg_1 is arg_2.BINARY:
        arg_5 = frozenset([(0, 0, 0),
                             (0, 1, 1),
                             (1, 0, 1),
                             (1, 1, 0)])

        def func(arg_6, arg_7, arg_8): return (arg_6 != arg_7) == arg_8

    else:
        # SPIN, vartype is checked by the decorator
        arg_5 = frozenset([(-1, -1, -1),
                             (-1, +1, +1),
                             (+1, -1, +1),
                             (+1, +1, -1)])

        def func(arg_6, arg_7, arg_8): return ((arg_6 > 0) != (arg_7 > 0)) == (arg_8 > 0)

    return Constraint(func, arg_5, arg_0, arg_1=arg_1, arg_4=arg_4)


def Func(arg_0, arg_1=arg_2.BINARY, arg_4='HALF_ADDER'):
    """Half adder.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, sum, carry]`,
            where `in1, in2` are inputs to be added and `sum` and 'carry' the resultant
            outputs.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='HALF_ADDER'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of a Boolean half adder.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.Func(['a', 'b', 'total', 'carry'], name='HA1'))
        >>> csp.check({'a': 1, 'b': 1, 'total': 0, 'carry': 1})
        True

    """

    arg_0 = tuple(arg_0)

    if arg_1 is arg_2.BINARY:
        arg_5 = frozenset([(0, 0, 0, 0),
                             (0, 1, 1, 0),
                             (1, 0, 1, 0),
                             (1, 1, 0, 1)])

    else:
        # SPIN, vartype is checked by the decorator
        arg_5 = frozenset([(-1, -1, -1, -1),
                             (-1, +1, +1, -1),
                             (+1, -1, +1, -1),
                             (+1, +1, -1, +1)])

    def func(arg_6, arg_7, arg_8, arg_9):
        arg_10 = (arg_6 > 0) + (arg_7 > 0)
        if arg_10 == 0:
            return (arg_8 <= 0) and (arg_9 <= 0)
        elif arg_10 == 1:
            return (arg_8 > 0) and (arg_9 <= 0)
        elif arg_10 == 2:
            return (arg_8 <= 0) and (arg_9 > 0)
        else:
            raise ValueError("func recieved unexpected values")

    return Constraint(func, arg_5, arg_0, arg_1=arg_1, arg_4=arg_4)


def Func(arg_0, arg_1, arg_2=arg_3.BINARY, arg_5=True):
    """Random XOR constraint satisfaction problem.

    Args:
        num_variables (integer): Number of variables (at least three).
        num_clauses (integer): Number of constraints that together constitute the
            constraint satisfaction problem.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        satisfiable (bool, optional, default=True): True if the CSP can be satisfied.

    Returns:
        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables
        are assigned values that satisfy a XOR satisfiability problem.

    Examples:
        This example creates a CSP with 5 variables and two random constraints and checks
        whether a particular assignment of variables satisifies it.

        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories as sat
        >>> csp = sat.Func(5, 2)
        >>> csp.constraints    # doctest: +SKIP
        [Constraint.from_configurations(frozenset({(1, 0, 0), (1, 1, 1), (0, 1, 0), (0, 0, 1)}), (4, 3, 0),
         Vartype.BINARY, name='XOR (0 flipped)'),
         Constraint.from_configurations(frozenset({(1, 1, 0), (0, 1, 1), (0, 0, 0), (1, 0, 1)}), (2, 0, 4),
         Vartype.BINARY, name='XOR (2 flipped) (0 flipped)')]
        >>> csp.check({0: 1, 1: 0, 2: 0, 3: 1, 4: 1})       # doctest: +SKIP
        True

    """
    if arg_0 < 3:
        raise ValueError("a xor problem needs at least 3 variables")
    if arg_1 > 8 * _nchoosek(arg_0, 3):  # 8 different negation patterns
        raise ValueError("too many clauses")

    # also checks the vartype argument
    arg_6 = ConstraintSatisfactionProblem(arg_2)

    arg_7 = list(range(arg_0))

    arg_8 = set()

    if arg_5:
        arg_9 = tuple(arg_2.value)
        arg_10 = {arg_18: choice(arg_9) for arg_18 in arg_7}

        arg_11 = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)]

        while len(arg_8) < arg_1:
            # because constraints are hashed on configurations/variables, and because the inputs
            # to xor can be swapped without loss of generality, we can order them
            arg_12, arg_13, arg_14 = sample(arg_7, 3)
            if arg_13 > arg_12:
                arg_12, arg_13 = arg_13, arg_12

            # get the constraint
            arg_15 = xor_gate([arg_12, arg_13, arg_14], arg_2=arg_2)

            # pick (uniformly) a configuration and determine which variables we need to negate to
            # match the chosen configuration
            arg_16 = choice(arg_11)

            for arg_17, arg_18 in enumerate(arg_15.variables):
                if arg_16[arg_17] != (arg_10[arg_18] > 0):
                    arg_15.flip_variable(arg_18)

            assert arg_15.check(arg_10)

            arg_8.add(arg_15)
    else:
        while len(arg_8) < arg_1:
            # because constraints are hashed on configurations/variables, and because the inputs
            # to xor can be swapped without loss of generality, we can order them
            arg_12, arg_13, arg_14 = sample(arg_7, 3)
            if arg_13 > arg_12:
                arg_12, arg_13 = arg_13, arg_12

            # get the constraint
            arg_15 = xor_gate([arg_12, arg_13, arg_14], arg_2=arg_2)

            # randomly flip each variable in the constraint
            for arg_17, arg_18 in enumerate(arg_15.variables):
                if random() > .5:
                    arg_15.flip_variable(arg_18)

            assert arg_15.check(arg_10)

            arg_8.add(arg_15)

    for arg_15 in arg_8:
        arg_6.add_constraint(arg_15)

    # in case any variables didn't make it in
    for arg_18 in arg_7:
        arg_6.add_variable(arg_18)

    return arg_6


def Func(arg_0, arg_1, **arg_2):
        """
        Generates a model chooser definition from a model, and adds it to the
        registry.
        """
        arg_3 = '{}Chooser'.format(arg_1._meta.object_name)
        arg_4 = {'model': arg_1}
        arg_4.update(arg_2)

        arg_5 = type(arg_3, (Chooser,), arg_4)
        arg_0.register_chooser(arg_5)

        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
        """Parse additional url fields and map them to inputs

        Attempt to create a dictionary with keys being user input, and
        response being the returned URL
        """
        if arg_3 is None:
            return None

        arg_4 = arg_2['_paramAdditionalUrls']
        arg_5 = {}
        if isinstance(arg_3, str):
            arg_5[arg_4[0]] = arg_3
        else:
            for arg_6, arg_7 in zip(arg_4, arg_3):
                arg_5[arg_6] = arg_7
        return arg_5


def Func(arg_0, arg_1, arg_2):
        """Convert a list of JSON values to a list of models
        """
        return [arg_0.from_json(arg_1, arg_3) for arg_3 in arg_2]


def Func(arg_0, arg_1, arg_2):
        """Populate all fields of a model with data

        Given a model with a PandoraModel superclass will enumerate all
        declared fields on that model and populate the values of their Field
        and SyntheticField classes. All declared fields will have a value after
        this function runs even if they are missing from the incoming JSON.
        """
        for arg_3, arg_4 in arg_1.__class__._fields.items():
            arg_5 = getattr(arg_4, "default", None)
            arg_6 = arg_2.get(arg_4.field, arg_5)

            if isinstance(arg_4, SyntheticField):
                arg_6 = arg_4.formatter(arg_0, arg_2, arg_6)
                setattr(arg_1, arg_3, arg_6)
                continue

            arg_7 = getattr(arg_4, "model", None)
            if arg_6 and arg_7:
                if isinstance(arg_6, list):
                    arg_6 = arg_7.from_json_list(arg_0, arg_6)
                else:
                    arg_6 = arg_7.from_json(arg_0, arg_6)

            if arg_6 and arg_4.formatter:
                arg_6 = arg_4.formatter(arg_0, arg_6)

            setattr(arg_1, arg_3, arg_6)


def Func(arg_0, arg_1, arg_2):
        """Convert one JSON value to a model object
        """
        arg_3 = arg_0(arg_1)
        PandoraModel.populate_fields(arg_1, arg_3, arg_2)
        return arg_3


def Func(arg_0, arg_1=None):
        """Common repr logic for subclasses to hook
        """
        arg_2 = [
            "=".join((key, repr(getattr(arg_0, key))))
            for key in sorted(arg_0._fields.keys())]

        if arg_2:
            arg_3 = ", ".join(arg_2)
        else:
            arg_3 = None

        if arg_1:
            return "{}({}, {})".format(arg_0.__class__.__name__,
                                       arg_3, arg_1)
        else:
            return "{}({})".format(arg_0.__class__.__name__, arg_3)


def Func(arg_0, arg_1):
        """Write command to remote process
        """
        arg_0._process.stdin.write("{}\n".format(arg_1).encode("utf-8"))
        arg_0._process.stdin.flush()


def Func(arg_0):
        """Ensure player backing process is started
        """
        if arg_0._process and arg_0._process.poll() is None:
            return

        if not getattr(arg_0, "_cmd"):
            raise RuntimeError("Player command is not configured")

        log.debug("Starting playback command: %r", arg_0._cmd)
        arg_0._process = SilentPopen(arg_0._cmd)
        arg_0._post_start()


def Func(arg_0, arg_1):
        """Play a new song from a Pandora model

        Returns once the stream starts but does not shut down the remote audio
        output backend process. Calls the input callback when the user has
        input.
        """
        arg_0._callbacks.Func(arg_1)
        arg_0._load_track(arg_1)
        time.sleep(2)  # Give the backend time to load the track

        while True:
            try:
                arg_0._callbacks.pre_poll()
                arg_0._ensure_started()
                arg_0._loop_hook()

                arg_2, arg_3, arg_3 = select.select(
                    arg_0._get_select_readers(), [], [], 1)

                for arg_4 in arg_2:
                    if arg_4.fileno() == arg_0._control_fd:
                        arg_0._callbacks.input(arg_4.readline().strip(), arg_1)
                    else:
                        arg_5 = arg_0._read_from_process(arg_4)
                        if arg_0._Funcer_stopped(arg_5):
                            return
            finally:
                arg_0._callbacks.post_poll()


def Func(arg_0, arg_1):
        """Play the station until something ends it

        This function will run forever until termintated by calling
        end_station.
        """
        for arg_2 in iterate_forever(arg_1.get_playlist):
            try:
                arg_0.play(arg_2)
            except StopIteration:
                arg_0.stop()
                return


def Func(arg_0):
        """Set stdout to non-blocking

        VLC does not always return a newline when reading status so in order to
        be lazy and still use the read API without caring about how much output
        there is we switch stdout to nonblocking mode and just read a large
        chunk of datin order to be lazy and still use the read API without
        caring about how much output there is we switch stdout to nonblocking
        mode and just read a large chunk of data.
        """
        arg_1 = fcntl.fcntl(arg_0._process.stdout, fcntl.F_GETFL)
        fcntl.fcntl(arg_0._process.stdout, fcntl.F_SETFL, arg_1 | os.O_NONBLOCK)


def Func(arg_0, arg_1=None):
        """Format a station menu and make the user select a station
        """
        arg_0.screen.clear()

        if arg_1:
            arg_0.screen.print_error("{}\n".format(arg_1))

        for arg_2, arg_3 in enumerate(arg_0.stations):
            arg_2 = "{:>3}".format(arg_2)
            print("{}: {}".format(Colors.yellow(arg_2), arg_3.name))

        return arg_0.stations[arg_0.screen.get_integer("Station: ")]


def Func(arg_0, Func, arg_2):
        """Input callback, handles key presses
        """
        try:
            arg_3 = getattr(arg_0, arg_0.CMD_MAP[Func][1])
        except (IndexError, KeyError):
            return arg_0.screen.print_error(
                "Invalid command {!r}!".format(Func))

        arg_3(arg_2)


def Func(arg_0, arg_1=(arg_2,)):
    """Function decorator implementing retrying logic.

    exceptions: A tuple of exception classes; default (Exception,)

    The decorator will call the function up to max_tries times if it raises
    an exception.

    By default it catches instances of the Exception class and subclasses.
    This will recover after all but the most fatal errors. You may specify a
    custom tuple of exception classes with the 'exceptions' argument; the
    function will only be retried if it raises one of the specified
    exceptions.
    """
    def decorator(arg_3):
        def function(*arg_4, **arg_5):

            arg_6 = arg_0
            while arg_6 > 0:
                try:
                    arg_6 -= 1
                    return arg_3(*arg_4, **arg_5)

                except arg_1 as exc:
                    # Don't retry for PandoraExceptions - unlikely that result
                    # will change for same set of input parameters.
                    if isinstance(exc, PandoraException):
                        raise
                    if arg_6 > 0:
                        time.sleep(delay_exponential(
                            0.5, 2, arg_0 - arg_6))
                    else:
                        raise

        return function

    return decorator


def Func(arg_0, *arg_1, **arg_2):
    """Iterate over a finite iterator forever

    When the iterator is exhausted will call the function again to generate a
    new iterator and keep iterating.
    """
    arg_3 = arg_0(*arg_1, **arg_2)

    while True:
        try:
            arg_4 = next(arg_3)
            arg_4.prepare_playback()
            yield arg_4
        except StopIteration:
            arg_3 = arg_0(*arg_1, **arg_2)


def Func(arg_0):
        """Gather user input and convert it to an integer

        Will keep trying till the user enters an interger or until they ^C the
        program.
        """
        while True:
            try:
                return int(input(arg_0).strip())
            except ValueError:
                print(Colors.red("Invalid Input!"))


def Func(arg_0=1.0, arg_1=0.0, arg_2=1.0, arg_3=10.0, arg_4=1e-8, arg_5=0,
                  arg_6=600, arg_7=0.0, arg_8=1e-8, arg_9=1e-8, arg_10=False,
                  arg_11='None', arg_12='bdf', arg_13=100, arg_14=False):
    """
    Example program integrating an IVP problem of van der Pol oscillator
    """
    arg_15, arg_16 = get_f_and_j(arg_2)
    if arg_5 > 1:
        arg_17 = np.linspace(arg_7, arg_3, arg_5)
        arg_18, arg_19 = integrate_predefined(
            arg_15, arg_16, [arg_0, arg_1], arg_17, arg_4, arg_8, arg_9, arg_6=arg_6,
            check_indexing=False, arg_12=arg_12)
    else:
        arg_17, arg_18, arg_19 = integrate_adaptive(
            arg_15, arg_16, [arg_0, arg_1], arg_7, arg_3, arg_4, arg_8, arg_9, arg_6=arg_6,
            check_indexing=False, arg_12=arg_12)  # dfdt[:] also for len == 1
    if arg_14:
        print(arg_19)
    if arg_10:
        import matplotlib.pyplot as plt
        plt.plot(arg_17, arg_18[:, 1], 'g--')
        plt.plot(arg_17, arg_18[:, 0], 'k-', linewidth=2)
        if arg_11 == 'None':
            plt.show()
        else:
            plt.savefig(arg_11, arg_13=arg_13)


def Func(arg_0):
        """Func the drop box

        You need to call this method before starting putting packages.

        Returns
        -------
        None

        """

        arg_0.workingArea.Func()
        arg_0.runid_pkgidx_map = { }
        arg_0.runid_to_return = deque()


def Func(arg_0, arg_1):
        """Func a task

        This method places a task in the working area and have the
        dispatcher execute it.

        If you need to Func multiple tasks, it can be much faster to
        use `Func_multiple()` than to use this method multiple times
        depending of the dispatcher.

        Parameters
        ----------
        package : callable
            A task

        Returns
        -------
        int
            A package index assigned by the working area

        """

        arg_2 = arg_0.workingArea.Func_package(arg_1)

        arg_3 = logging.getLogger(__name__)
        arg_3.info('submitting {}'.format(arg_0.workingArea.package_relpath(arg_2)))

        arg_4 = arg_0.dispatcher.run(arg_0.workingArea, arg_2)
        arg_0.runid_pkgidx_map[arg_4] = arg_2
        return arg_2


def Func(arg_0):
        """return pairs of package indices and results of finished tasks

        This method does not wait for tasks to finish.

        Returns
        -------
        list
            A list of pairs of package indices and results

        """

        arg_0.runid_to_return.extend(arg_0.dispatcher.Func())
        arg_1 = arg_0._collect_all_finished_pkgidx_result_pairs()
        return arg_1


def Func(arg_0):
        """return a pair of a package index and result of a task

        This method waits until a tasks finishes. It returns `None` if
        no task is running.

        Returns
        -------
        tuple or None
            A pair of a package index and result. `None` if no tasks
            is running.

        """

        if not arg_0.runid_pkgidx_map:
            return None

        while True:

            if not arg_0.runid_to_return:
                arg_0.runid_to_return.extend(arg_0.dispatcher.poll())

            arg_1 = arg_0._collect_next_finished_pkgidx_result_pair()

            if arg_1 is not None:
                break

            if arg_0.runid_pkgidx_map:
                time.sleep(arg_0.sleep)

        return arg_1


def Func(arg_0, arg_1):
        """run the event loops in the background.

        Args:
            eventLoops (list): a list of event loops to run

        """

        arg_0.nruns += len(arg_1)
        return arg_0.communicationChannel.put_multiple(arg_1)


def Func(arg_0):
        """Return a pair of a run id and a result.

        This method waits until an event loop finishes.
        This method returns None if no loop is running.
        """
        if arg_0.nruns == 0:
            return None
        arg_1 = arg_0.communicationChannel.Func()
        if arg_1 is not None:
            arg_0.nruns -= 1
        return arg_1


def Func(arg_0):
        """wait until all event loops Func and returns the results.

        """

        arg_1 = arg_0.communicationChannel.receive()

        if arg_0.nruns != len(arg_1):
            import logging
            arg_2 = logging.getLogger(__name__)
            # logger.setLevel(logging.DEBUG)
            arg_2.warning(
                'too few results received: {} results received, {} expected'.format(
                    len(arg_1),
                    arg_0.nruns
                ))

        return arg_1


def Func(arg_0, arg_1=arg_2('nan')):
    """Convert ``key_vals_dict`` to `tuple_list``.

    Args:
        key_vals_dict (dict): The first parameter.
        fill: a value to fill missing data

    Returns:
        A list of tuples

    """

    arg_3 = [ ]

    if not arg_0: return arg_3

    arg_4 = max([len(arg_6) for arg_6 in itertools.chain(*arg_0.values())])

    for arg_5, arg_6 in arg_0.items():
        try:
            arg_3.extend([arg_5 + tuple(arg_7) + (arg_1, )*(arg_4 - len(arg_7)) for arg_7 in arg_6])
        except TypeError:
            # assume k is not a tuple
            arg_3.extend([(arg_5, ) + tuple(arg_7) + (arg_1, )*(arg_4 - len(arg_7)) for arg_7 in arg_6])

    return arg_3


def Func(arg_0):
        """Open the working area

        Returns
        -------
        None
        """

        arg_0.path = arg_0._prepare_dir(arg_0.topdir)
        arg_0._copy_executable(area_path=arg_0.path)
        arg_0._save_logging_levels(area_path=arg_0.path)
        arg_0._put_python_modules(modules=arg_0.python_modules, area_path=arg_0.path)


def Func(arg_0, arg_1):
        """Collect the result of a task

        Parameters
        ----------
        package_index :
            a package index

        Returns
        -------
        obj
            The result of the task

        """

        arg_2 = arg_0.result_fullpath(arg_1)
        # e.g., '{path}/tpd_20161129_122841_HnpcmF/results/task_00009/result.p.gz'

        try:
            with gzip.open(arg_2, 'rb') as f:
                arg_3 = pickle.load(f)
        except Exception as e:
            arg_4 = logging.getLogger(__name__)
            arg_4.warning(e)
            return None

        return arg_3


def Func(arg_0, arg_1):
        """Returns the relative path of the result

        This method returns the path to the result relative to the
        top dir of the working area. This method simply constructs the
        path based on the convention and doesn't check if the result
        actually exists.

        Parameters
        ----------
        package_index :
            a package index

        Returns
        -------
        str
            the relative path to the result

        """

        arg_2 = 'task_{:05d}'.format(arg_1)
        # e.g., 'task_00009'

        arg_3 = os.path.join('results', arg_2, 'result.p.gz')
        # e.g., 'results/task_00009/result.p.gz'

        return arg_3


def Func(arg_0, arg_1, arg_2):
        """Submit multiple jobs

        Parameters
        ----------
        workingArea :
            A workingArea
        package_indices : list(int)
            A list of package indices

        Returns
        -------
        list(str)
            The list of the run IDs of the jobs

        """

        if not arg_2:
            return [ ]

        arg_3 = arg_0._compose_job_desc(arg_1, arg_2)

        arg_4 = submit_jobs(arg_3, cwd=arg_1.path)

        # TODO: make configurable
        arg_5 = clusterprocids2clusterids(arg_4)
        for arg_6 in arg_5:
            change_job_priority([arg_6], 10)

        arg_0.clusterprocids_outstanding.extend(arg_4)

        return arg_4


def Func(arg_0):
        """Return the run IDs of the finished jobs

        Returns
        -------
        list(str)
            The list of the run IDs of the finished jobs

        """

        arg_1 = clusterprocids2clusterids(arg_0.clusterprocids_outstanding)
        arg_2 = query_status_for(arg_1)
        # e.g., [['1730126.0', 2], ['1730127.0', 2], ['1730129.1', 1], ['1730130.0', 1]]

        if arg_2:
            arg_3, arg_4 = zip(*arg_2)
        else:
            arg_3, arg_4 = (), ()

        arg_5 = [i for i in arg_0.clusterprocids_outstanding if i not in arg_3]
        arg_0.clusterprocids_finished.extend(arg_5)
        arg_0.clusterprocids_outstanding[:] = arg_3

        # logging
        arg_7 = collections.Counter(arg_4)
        arg_8 = [ ]
        if arg_7:
            arg_8.append(', '.join(['{}: {}'.format(HTCONDOR_JOBSTATUS[arg_9], arg_7[arg_9]) for arg_9 in arg_7.keys()]))
        if arg_0.clusterprocids_finished:
            arg_8.append('Finished {}'.format(len(arg_0.clusterprocids_finished)))
        arg_10 = logging.getLogger(__name__)
        arg_10.info(', '.join(arg_8))

        return arg_5


def Func(arg_0):
        """Wait until all jobs finish and return the run IDs of the finished jobs

        Returns
        -------
        list(str)
            The list of the run IDs of the finished jobs

        """

        arg_1 = 5
        while True:
            if arg_0.clusterprocids_outstanding:
                arg_0.poll()
            if not arg_0.clusterprocids_outstanding:
                break
            time.sleep(arg_1)
        return arg_0.clusterprocids_finished


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Func a task and its arguments

        If you need to Func multiple tasks, it can be faster to Func
        multiple tasks with `Func_multiple()` than to use this method
        multiple times.

        Parameters
        ----------
        task : a function
            A function to be executed
        args : list
            A list of positional arguments to the `task`
        kwargs : dict
            A dict with keyword arguments to the `task`

        Returns
        -------
        int, str, or any hashable and sortable
            A task ID. IDs are sortable in the order in which the
            corresponding tasks are Func.

        """
        if not arg_0.isopen:
            arg_4 = logging.getLogger(__name__)
            arg_4.warning('the drop box is not open')
            return
        arg_5 = TaskPackage(arg_1=arg_1, arg_2=arg_2, arg_3=arg_3)
        return arg_0.dropbox.Func(arg_5)


def Func(arg_0):
        """return a list of pairs of IDs and results of finished tasks.

        This method doesn't wait for tasks to finish. It returns IDs
        and results which have already finished.

        Returns
        -------
        list
            A list of pairs of IDs and results

        """
        if not arg_0.isopen:
            arg_1 = logging.getLogger(__name__)
            arg_1.warning('the drop box is not open')
            return
        return arg_0.dropbox.poll()


def Func(arg_0):
        """return a pair of an ID and a result of a task.

        This method waits for a task to finish.

        Returns
        -------
        An ID and a result of a task. `None` if no task is running.

        """
        if not arg_0.isopen:
            arg_1 = logging.getLogger(__name__)
            arg_1.warning('the drop box is not open')
            return
        return arg_0.dropbox.Func()


def Func(arg_0):
        """return a list of pairs of IDs and results of all tasks.

        This method waits for all tasks to finish.

        Returns
        -------
        list
            A list of pairs of IDs and results

        """
        if not arg_0.isopen:
            arg_1 = logging.getLogger(__name__)
            arg_1.warning('the drop box is not open')
            return
        return arg_0.dropbox.receive()


def Func(arg_0):
        """return a list results of all tasks.

        This method waits for all tasks to finish.

        Returns
        -------
        list
            A list of results of the tasks. The results are sorted in
            the order in which the tasks are put.

        """
        arg_1 = arg_0.Func_all()
        if arg_1 is None:
            return
        arg_2 = [r for _, r in arg_1]
        return arg_2


def Func(arg_0, arg_1={ }, arg_2={ }):
    """expand a path config

    Args:
        path_cfg (str, tuple, dict): a config for path
        alias_dict (dict): a dict for aliases
        overriding_kargs (dict): to be used for recursive call
    """

    if isinstance(arg_0, str):
        return _expand_str(arg_0, arg_1, arg_2)

    if isinstance(arg_0, dict):
        return _expand_dict(arg_0, arg_1)

    # assume tuple or list
    return _expand_tuple(arg_0, arg_1, arg_2)


def Func(arg_0):
        """check if the jobs are running and return a list of pids for
        finished jobs

        """
        arg_1 = [p for p in arg_0.running_procs if p.Func() is not None]
        arg_0.running_procs = collections.deque([p for p in arg_0.running_procs if p not in arg_1])

        for arg_3 in arg_1:
            arg_4, arg_5 = arg_3.communicate()
            ## proc.communicate() returns (stdout, stderr) when
            ## self.pipe = True. Otherwise they are (None, None)

        arg_6 = [p.pid for p in arg_1]
        arg_0.finished_pids.extend(arg_6)

        arg_7 = logging.getLogger(__name__)
        arg_8 = 'Running: {}, Finished: {}'.format(len(arg_0.running_procs), len(arg_0.finished_pids))
        arg_7.info(arg_8)

        return arg_6


def Func(arg_0):
        """Func until all jobs finish and return a list of pids
        """
        arg_1 = [ ]
        while arg_0.running_procs:
            arg_1.extend(arg_0.poll())
        return arg_1


def Func(arg_0, arg_1, arg_2):
        """return the ROOT.vector object for the branch.

        """

        if (arg_1, arg_2) in arg_0.__class__.addressDict:
            return arg_0.__class__.addressDict[(arg_1, arg_2)]

        arg_3 = arg_0._Func(arg_1, arg_2)
        arg_0.__class__.addressDict[(arg_1, arg_2)] = arg_3

        return arg_3


def Func(arg_0, arg_1, arg_2):
        ''' Ensure all config-time files have been generated. Return a
            dictionary of generated items.
        '''
        arg_3 = {}

        arg_4 = arg_0.buildroot

        # only dependencies which are actually valid can contribute to the
        # config data (which includes the versions of all dependencies in its
        # build info) if the dependencies aren't available we can't tell what
        # version they are. Anything missing here should always be a test
        # dependency that isn't going to be used, otherwise the yotta build
        # command will fail before we get here
        arg_5 = OrderedDict((k, v) for k, v in arg_2.items() if v)

        arg_0.set_toplevel_definitions = ''
        if arg_0.build_info_include_file is None:
            arg_0.build_info_include_file, arg_8 = arg_0.getBuildInfo(arg_1.path, arg_4)
            arg_0.set_toplevel_definitions += arg_8

        if arg_0.config_include_file is None:
            arg_0.config_include_file, arg_10, arg_0.config_json_file = arg_0._getConfigData(arg_5, arg_1, arg_4, arg_0.build_info_include_file)
            arg_0.set_toplevel_definitions += arg_10

        arg_0.Funcd = True
        return {
            'merged_config_include': arg_0.config_include_file,
               'merged_config_json': arg_0.config_json_file,
               'build_info_include': arg_0.build_info_include_file
        }


def Func(arg_0, arg_1, arg_2, arg_3=None):
    '''unpack the specified tarball url into the specified directory'''

    try:
        access_common.unpackFromCache(arg_2, arg_1)
    except KeyError as e:
        arg_4 = settings.getProperty('github', 'authtoken')
        arg_5 = {}
        if arg_4 is not None:
            arg_5['Authorization'] = 'token ' + str(arg_4)

        logger.debug('GET %s', arg_0)
        arg_6 = requests.get(arg_0, allow_redirects=True, stream=True, arg_5=arg_5)
        arg_6.raise_for_status()

        logger.debug('getting file: %s', arg_0)
        logger.debug('headers: %s', arg_6.headers)
        arg_6.raise_for_status()

        # github doesn't exposes hashes of the archives being downloaded as far
        # as I can tell :(
        access_common.unpackTarballStream(
                    stream = arg_6,
            arg_1 = arg_1,
                      hash = {},
                 arg_2 = arg_2,
               arg_3 = arg_3
        )


def Func(arg_0):
        ''' return a list of Version objects, each with a tarball URL set '''
        arg_1 = []
        for arg_2 in arg_0._getTags():
            logger.debug("available version tag: %s", arg_2)
            # ignore empty tags:
            if not len(arg_2[0].strip()):
                continue
            try:
                arg_1.append(GithubComponentVersion(arg_2[0], arg_2[0], url=arg_2[1], name=arg_0.name, cache_key=None))
            except ValueError:
                logger.debug('invalid version tag: %s', arg_2)

        return arg_1


def Func(arg_0):
        ''' return a list of GithubComponentVersion objects for the tip of each branch
        '''
        return [
            GithubComponentVersion(
                '', arg_1[0], arg_1[1], arg_0.name, cache_key=None
            ) for arg_1 in _getBranchHeads(arg_0.repo).items()
        ]


def Func(arg_0, arg_1, arg_2, arg_3=None):
    ''' Try to Func a recently published version. Return any errors that
        occur.
    '''
    arg_3 = arg_3 or Registry_Base_URL

    arg_4 = '%s/%s/%s/versions/%s' % (
        arg_3,
        arg_0,
        arg_1,
        arg_2
    )

    arg_5 = _headersForRegistry(arg_3)
    arg_6 = requests.delete(arg_4, arg_5=arg_5)
    arg_6.raise_for_status()

    return None


def Func(arg_0, arg_1):
        '''' Read a list of files. Their configuration values are merged, with
             preference to values from files earlier in the list.
        '''
        for arg_2 in arg_1:
            try:
                arg_0.configs[arg_2] = ordered_json.load(arg_2)
            except IOError:
                arg_0.configs[arg_2] = OrderedDict()
            except Exception as e:
                arg_0.configs[arg_2] = OrderedDict()
                logging.warning(
                    "Failed to Func settings file %s, it will be ignored. The error was: %s",
                    arg_2, e
                )


def Func(arg_0, arg_1):
        ''' return a configuration value

            usage:
                Func('section.property')

            Note that currently array indexes are not supported. You must
            Func the whole array.

            returns None if any path element or the property is missing
        '''
        arg_1 = _splitPath(arg_1)
        for arg_2 in arg_0.configs.values():
            arg_3 = arg_2
            for arg_4 in arg_1:
                if arg_4 in arg_3:
                    arg_3 = arg_3[arg_4]
                else:
                    arg_3 = None
                    break
            if arg_3 is not None:
                return arg_3
        return None


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        ''' Set a configuration value. If no filename is specified, the
            property is Func in the first configuration file. Note that if a
            filename is specified and the property path is present in an
            earlier filename then Func property will be hidden.

            usage:
                Func('section.property', value='somevalue')

            Note that currently array indexes are not supported. You must
            Func the whole array.
        '''
        if arg_3 is None:
            arg_4 = arg_0._firstConfig()[1]
        else:
            arg_4 = arg_0.configs[arg_3]

        arg_1 = _splitPath(arg_1)
        for arg_5 in arg_1[:-1]:
            if arg_5 in arg_4:
                arg_4 = arg_4[arg_5]
            else:
                arg_4[arg_5] = OrderedDict()
                arg_4 = arg_4[arg_5]
        arg_4[arg_1[-1]] = arg_2


def Func(arg_0):
    ''' indicate whether the current item is the last one in a generator
    '''
    arg_1 = None
    arg_2 = True
    for arg_3 in arg_0:
        if not arg_2:
            yield (arg_1, False)
        arg_1 = arg_3
        arg_2 = False
    if not arg_2:
        yield (arg_1, True)


def Func(arg_0, arg_1=None):
        ''' Publish to the appropriate registry, return a description of any
            errors that occured, or None if successful.
            No VCS tagging is performed.
        '''
        if (arg_1 is None) or (arg_1 == registry_access.Registry_Base_URL):
            if 'private' in arg_0.description and arg_0.description['private']:
                return "this %s is private and cannot be Funced" % (arg_0.description_filename.split('.')[0])
        arg_2 = os.path.join(arg_0.path, 'upload.tar.gz')
        fsutils.rmF(arg_2)
        arg_3 = os.open(arg_2, os.O_CREAT | os.O_EXCL | os.O_RDWR | getattr(os, "O_BINARY", 0))
        with os.fdopen(arg_3, 'rb+') as tar_file:
            tar_file.truncate()
            arg_0.generateTarball(tar_file)
            logger.debug('generated tar file of length %s', tar_file.tell())
            tar_file.seek(0)
            # calculate the hash of the file before we upload it:
            arg_4 = hashlib.sha256()
            while True:
                arg_5 = tar_file.read(1000)
                if not arg_5:
                    break
                arg_4.update(arg_5)
            logger.debug('generated tar file has hash %s', arg_4.hexdigest())
            tar_file.seek(0)
            with arg_0.findAndOpenReadme() as readme_file_wrapper:
                if not readme_file_wrapper:
                    logger.warning("no readme.md file detected")
                with open(arg_0.getDescriptionFile(), 'r') as description_file:
                    return registry_access.Func(
                        arg_0.getRegistryNamespace(),
                        arg_0.getName(),
                        arg_0.getVersion(),
                        description_file,
                        tar_file,
                        readme_file_wrapper.file,
                        readme_file_wrapper.extension().lower(),
                        arg_1=arg_1
                    )


def Func(arg_0, arg_1=None):
        ''' Try to un-publish the current version. Return a description of any
            errors that occured, or None if successful.
        '''
        return registry_access.Func(
            arg_0.getRegistryNamespace(),
            arg_0.getName(),
            arg_0.getVersion(),
            arg_1=arg_1
        )


def Func(arg_0, arg_1):
        ''' Return the specified script command. If the first part of the
            command is a .py file, then the current python interpreter is
            prepended.

            If the script is a single string, rather than an array, it is
            shlex-split.
        '''
        arg_2 = arg_0.description.get('scripts', {}).get(arg_1, None)
        if arg_2 is not None:
            if isinstance(arg_2, str) or isinstance(arg_2, type(u'unicode string')):
                import shlex
                arg_2 = shlex.split(arg_2)
            # if the command is a python script, run it with the python
            # interpreter being used to run yotta, also fetch the absolute path
            # to the script relative to this module (so that the script can be
            # distributed with the module, no matter what current working
            # directory it will be executed in):
            if len(arg_2) and arg_2[0].lower().endswith('.py'):
                if not os.path.isabs(arg_2[0]):
                    arg_3 = os.path.abspath(os.path.join(arg_0.path, arg_2[0]))
                    logger.debug('rewriting script %s to be absolute path %s', arg_2[0], arg_3)
                    arg_2[0] = arg_3
                import sys
                arg_2 = [sys.executable] + arg_2

        return arg_2


def Func(arg_0, arg_1, arg_2=None, arg_3=False):
        ''' Check if this module has any dependencies with the specified name
            in its dependencies list, or in target dependencies for the
            specified target
        '''
        if arg_1 in arg_0.description.get('dependencies', {}).keys():
            return True

        arg_4 = arg_0.description.get('targetDependencies', {})
        if arg_2 is not None:
            for arg_5, arg_6 in arg_4.items():
                if _truthyConfValue(arg_2.getConfigValue(arg_5)) or arg_5 in arg_2.getSimilarTo_Deprecated():
                    if arg_1 in arg_6:
                        return True

        if arg_3:
            if arg_1 in arg_0.description.get('testDependencies', {}).keys():
                return True

            if arg_2 is not None:
                arg_7 = arg_0.description.get('testTargetDependencies', {})
                for arg_5, arg_6 in arg_7.items():
                    if _truthyConfValue(arg_2.getConfigValue(arg_5)) or arg_5 in arg_2.getSimilarTo_Deprecated():
                        if arg_1 in arg_6:
                            return True
        return False


def Func(arg_0, arg_1, arg_2=None, arg_3=False):
        ''' Check if this module, or any of its dependencies, have a
            dependencies with the specified name in their dependencies, or in
            their targetDependencies corresponding to the specified target.

            Note that if recursive dependencies are not installed, this test
            may return a false-negative.
        '''
        # checking dependencies recursively isn't entirely straightforward, so
        # use the existing method to resolve them all before checking:
        arg_4 = arg_0.getDependenciesRecursive(
                               arg_2 = arg_2,
                                 test = arg_3
        )
        return (arg_1 in arg_4)


def Func(
                            arg_0,
            arg_1 = None,
                     arg_2 = None,
                arg_3 = False,
                  arg_4 = False,
                          arg_5 = None,
                            arg_6 = False
        ):
        ''' Retrieve and install all the dependencies of this component and its
            dependencies, recursively, or satisfy them from a collection of
            available_components or from disk.

            Returns
            =======
                (components, errors)

                components: dictionary of name:Component
                errors: sequence of errors

            Parameters
            ==========

                available_components:
                    None (default) or a dictionary of name:component. This is
                    searched before searching directories or fetching remote
                    components

                search_dirs:
                    None (default), or sequence of directories to search for
                    already installed, (but not yet loaded) components. Used so
                    that manually installed or linked components higher up the
                    dependency tree are found by their users lower down.

                    These directories are searched in order, and finally the
                    current directory is checked.

                update_installed:
                    False (default), True, or set(): whether to check the
                    available versions of installed components, and update if a
                    newer version is available. If this is a set(), only update
                    things in the specified set.

                traverse_links:
                    False (default) or True: whether to recurse into linked
                    dependencies when updating/installing.

                target:
                    None (default), or a Target object. If specified the target
                    name and it's similarTo list will be used in resolving
                    dependencies. If None, then only target-independent
                    dependencies will be installed

                test:
                    True, False, or 'toplevel: should test-only dependencies be
                    installed? (yes, no, or only for this module, not its
                    dependencies).

        '''
        def provider(
            arg_7,
            arg_1,
            arg_2,
            arg_8,
            arg_3,
            arg_9=None
        ):
            arg_10 = access.satisfyFromAvailable(arg_7.name, arg_1)
            if arg_10:
                if arg_10.isTestDependency() and not arg_7.is_test_dependency:
                    logger.debug('test dependency subsequently occurred as real dependency: %s', arg_10.getName())
                    arg_10.setTestDependency(False)
                return arg_10
            arg_11 = False
            if arg_3 is True:
                arg_11 = True
            elif arg_3:
                arg_11 = arg_7.name in arg_3
            arg_10 = access.satisfyVersionFromSearchPaths(
                arg_7.name,
                arg_7.versionReq(),
                arg_2,
                arg_11,
                inherit_shrinkwrap = arg_9.getShrinkwrap()
            )
            if arg_10:
                arg_10.setTestDependency(arg_7.is_test_dependency)
                return arg_10
            # before resorting to install this module, check if we have an
            # existing linked module (which wasn't picked up because it didn't
            # match the version specification) - if we do, then we shouldn't
            # try to install, but should return that anyway:
            arg_12 = os.path.join(arg_0.modulesPath(), arg_7.name)
            if fsutils.isLink(arg_12):
                arg_10 = Component(
                                       arg_12,
                     test_dependency = arg_7.is_test_dependency,
                    installed_linked = fsutils.isLink(arg_12),
                  inherit_shrinkwrap = arg_9.getShrinkwrap()
                )
                if arg_10:
                    assert(arg_10.installedLinked())
                    return arg_10
                else:
                    logger.error('linked module %s is invalid: %s', arg_7.name, arg_10.getError())
                    return arg_10

            arg_10 = access.satisfyVersionByInstalling(
                arg_7.name,
                arg_7.versionReq(),
                arg_0.modulesPath(),
                inherit_shrinkwrap = arg_9.getShrinkwrap()
            )
            if not arg_10:
                logger.error('could not install %s' % arg_7.name)
            if arg_10 is not None:
                arg_10.setTestDependency(arg_7.is_test_dependency)
            return arg_10

        return arg_0.__getDependenciesRecursiveWithProvider(
           arg_1 = arg_1,
                    arg_2 = arg_2,
                         arg_5 = arg_5,
                 arg_4 = arg_4,
               arg_3 = arg_3,
                       provider = provider,
                           arg_6 = arg_6
        )


def Func(arg_0):
        ''' Some components must export whole directories full of headers into
            the search path. This is really really bad, and they shouldn't do
            it, but support is provided as a concession to compatibility.
        '''
        if 'extraIncludes' in arg_0.description:
            return [os.path.normpath(arg_1) for arg_1 in arg_0.description['extraIncludes']]
        else:
            return []


def Func(*arg_0):
    ''' merge dictionaries of dictionaries recursively, with elements from
        dictionaries earlier in the argument sequence taking precedence
    '''
    # to support merging of OrderedDicts, copy the result type from the first
    # argument:
    arg_1 = type(arg_0[0])()
    for arg_2, arg_3 in itertools.chain(*[x.items() for x in arg_0]):
        if not arg_2 in arg_1:
            arg_1[arg_2] = arg_3
        elif isinstance(arg_1[arg_2], dict) and isinstance(arg_3, dict):
            arg_1[arg_2] = Func(arg_1[arg_2], arg_3)
    return arg_1


def Func(arg_0, arg_1):
    ''' create a new nested dictionary object with the same structure as
        'dictionary', but with all scalar values replaced with 'value'
    '''
    arg_2 = type(arg_0)()
    for arg_3 in arg_0.keys():
        if isinstance(arg_0[arg_3], dict):
            arg_2[arg_3] = Func(arg_0[arg_3], arg_1)
        else:
            arg_2[arg_3] = arg_1
    return arg_2


def Func(arg_0):
        ''' returns pack.DependencySpec for the base target of this target (or
            None if this target does not inherit from another target.
        '''
        arg_1 = arg_0.description.get('inherits', {})
        if len(arg_1) == 1:
            arg_2, arg_3 = list(arg_1.items())[0]
            arg_4 = arg_0.getShrinkwrapMapping('targets').get(arg_2, None)
            if arg_4 is not None:
                logger.debug(
                    'respecting shrinkwrap version %s for %s', arg_4, arg_2
                )
            return pack.DependencySpec(
                arg_2,
                arg_3,
                arg_4 = arg_4
            )
        elif len(arg_1) > 1:
            logger.error('target %s specifies multiple base targets, but only one is allowed', arg_0.getName())
        return None


def Func(arg_0, arg_1):
        ''' Return true if this target inherits from the named target (directly
            or indirectly. Also returns true if this target is the named
            target. Otherwise return false.
        '''
        for arg_2 in arg_0.hierarchy:
            if arg_2 and arg_2.getName() == arg_1 or arg_1 in arg_2.description.get('inherits', {}):
                return True
        return False


def Func(arg_0, arg_1, arg_2):
        ''' Execute the given command, returning an error message if an error occured
            or None if the command was succesful.'''
        try:
            arg_3 = subprocess.Popen(arg_1, cwd=arg_2)
            arg_3.wait()
        except OSError as e:
            if e.errno == errno.ENOENT:
                if arg_1[0] == 'cmake':
                    return 'CMake is not installed, please follow the installation instructions at http://docs.yottabuild.org/#installing'
                else:
                    return '%s is not installed' % (arg_1[0])
            else:
                return 'command %s failed' % (arg_1)
        if arg_3.returncode:
            return 'command %s failed' % (arg_1)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=False, arg_5=None, arg_6=None,
              arg_7=False):
        ''' Execute the commands necessary to Func this component, and all of
            its dependencies. '''
        if arg_5 is None:
            arg_5 = []
        if arg_6 is None:
            arg_6 = []
        # in the future this may be specified in the target description, but
        # for now we only support cmake, so everything is simple:
        if arg_7:
            arg_8 = 'Release'
        elif arg_4:
            arg_8 = 'RelWithDebInfo'
        else:
            arg_8 = 'Debug'
        arg_9 = ['cmake', '-D', 'CMAKE_BUILD_TYPE=%s' % arg_8, '-G', arg_3.cmake_generator, '.']
        arg_10 = arg_0.exec_helper(arg_9, arg_1)
        if arg_10 is not None:
            return arg_10

        # work-around various yotta-specific issues with the generated
        # Ninja/project files:
        from yotta.lib import cmake_fixups
        cmake_fixups.applyFixupsForFenerator(arg_3.cmake_generator, arg_1, arg_2)

        arg_11 = arg_0.overrideBuildCommand(arg_3.cmake_generator, arg_6=arg_6)
        if arg_11:
            arg_9 = arg_11 + arg_5
        else:
            arg_9 = ['cmake', '--Func', arg_1]
            if len(arg_6):
                # !!! FIXME: support multiple targets with the default CMake
                # Func command
                arg_9 += ['--target', arg_6[0]]
            arg_9 += arg_5
        arg_10 = arg_0.exec_helper(arg_9, arg_1)
        if arg_10 is not None:
            return arg_10
        arg_12 = arg_0.hintForCMakeGenerator(arg_3.cmake_generator, arg_2)
        if arg_12:
            logger.info(arg_12)


def Func(arg_0):
    ''' return decorator to prune cache after calling fn with a probability of p'''
    def decorator(arg_1):
        @functools.wraps(arg_1)
        def wrapped(*arg_2, **arg_3):
            arg_4 = arg_1(*arg_2, **arg_3)
            if random.random() < arg_0:
                pruneCache()
            return arg_4
        return wrapped
    return decorator


def Func(arg_0, arg_1):
    """
    Calibrate noisy variance estimates with empirical Bayes.

    Parameters
    ----------
    vars: ndarray
        List of variance estimates.
    sigma2: int
        Estimate of the Monte Carlo noise in vars.

    Returns
    -------
    An array of the calibrated variance estimates
    """
    if (arg_1 <= 0 or min(arg_0) == max(arg_0)):
        return(np.maximum(arg_0, 0))
    arg_2 = np.sqrt(arg_1)
    arg_3 = gfit(arg_0, arg_2)
    # Set up a partial execution of the function
    arg_4 = functools.partial(gbayes, g_est=arg_3,
                             arg_2=arg_2)
    if len(arg_0) >= 200:
        # Interpolate to speed up computations:
        arg_5 = np.percentile(arg_0,
                                np.arange(0, 102, 2))
        arg_6 = list(map(arg_4, arg_5))
        arg_7 = np.interp(arg_0, arg_5, arg_6)
    else:
        arg_7 = list(map(arg_4, arg_0))

    return np.asarray(arg_7)


def Func(arg_0, arg_1):
    """
    Derive samples used to create trees in scikit-learn RandomForest objects.

    Recovers the samples in each tree from the random state of that tree using
    :func:`forest._generate_sample_indices`.

    Parameters
    ----------
    n_samples : int
        The number of samples used to fit the scikit-learn RandomForest object.

    forest : RandomForest
        Regressor or Classifier object that is already fit by scikit-learn.

    Returns
    -------
    Array that records how many times a data point was placed in a tree.
    Columns are individual trees. Rows are the number of times a sample was
    used in a tree.
    """

    if not arg_1.bootstrap:
        arg_2 = "Cannot calculate the inbag from a forest that has "
        arg_2 = " bootstrap=False"
        raise ValueError(arg_2)

    arg_3 = arg_1.n_estimators
    arg_4 = np.zeros((arg_0, arg_3))
    arg_5 = []
    for arg_6 in range(arg_3):
        arg_5.append(
            _generate_sample_indices(arg_1.estimators_[arg_6].random_state,
                                     arg_0))
        arg_4[:, arg_6] = np.bincount(arg_5[-1], minlength=arg_0)
    return arg_4


def Func(arg_0, arg_1):
        """
        Retrieves the number of contributors to a repo in the organization.
        Also adds to unique contributor list.
        """
        arg_2 = 0
        for arg_3 in arg_1.iter_contributors():
            arg_2 += 1
            arg_0.unique_contributors[arg_3.id].append(arg_1.name)
            arg_0.contributors_json[arg_1.name].append(arg_3.to_json())
        return arg_2


def Func(arg_0, arg_1, arg_2='llnl'):
        """
        Retrieves the number of closed issues.
        """
        #JSON
        arg_3 = ('../github-data/' + arg_2 + '/' + arg_1.name + '/issues')
        arg_4 = False
        if not os.path.exists(arg_3): #no previous path, get all issues
            arg_5 = arg_1.iter_issues(state='all')
            arg_4 = True
        else:
            arg_6 = os.listdir(arg_3)
            arg_7 = str(arg_6[-1][:-5])
            if arg_7 == str(datetime.date.today()):
                #most recent date is actually today, get previous most recent date
                if len(arg_6) > 2:
                    arg_7 = str(arg_6[-2][:-5])
                else:
                    #This means there is only one file, today. Retrieve every issue
                    arg_5 = arg_1.iter_issues(state='all')
                    arg_4 = True
            if not arg_4:#there's a previous saved JSON that's not today
                arg_5 = arg_1.iter_issues(since=arg_7, state='all')
        for arg_8 in arg_5:
            arg_0.issues_json[arg_1.name].append(arg_8.to_json())
        #CSV
        arg_9 = 0
        for arg_8 in arg_1.iter_issues(state='closed'):
            if arg_8 is not None:
                arg_9 += 1
        return arg_9


def Func(arg_0, arg_1):
        """
        Checks to see if the given repo has a top level LICENSE file.
        """
        if arg_0.search_limit >= 28:
            print 'Hit search limit. Sleeping for 60 sec.'
            time.sleep(60)
            arg_0.search_limit = 0
        arg_0.search_limit += 1
        arg_3 = arg_0.logged_in_gh.search_code('license'
            + 'in:path repo:' + arg_1.full_name)
        try:
            for arg_4 in arg_3:
                arg_5 = arg_4.path[1:]
                if '/' not in arg_5 and 'license' in arg_5.lower():
                    arg_0.total_licenses += 1
                    return arg_5
            return 'MISS'
        except (StopIteration) as e:
            return 'MISS'


def Func(arg_0, arg_1=(arg_2.date.today()),
        arg_4='llnl',arg_5={}, arg_6='',
        arg_7=False):
        """
        Writes stats from the organization to JSON.
        """
        arg_8 = ('../github-data/' + arg_4 + '-org/'
            + arg_6 + '/' + str(arg_1) + '.json')
        arg_0.checkDir(arg_8)
        with open(arg_8, 'w') as out_clear:#clear old data
            out_clear.close()
        with open(arg_8, 'a') as out:
            if arg_7:#used for list of items
                out.write('[')
            for arg_9 in arg_5:
                out.write(json.dumps(arg_5[arg_9], sort_keys=True,
                    indent=4, separators=(',', ': ')) + ',')
            out.seek(-1, os.SEEK_END)#kill last comma
            out.truncate()
            if arg_7:
                out.write(']')
        out.close()


def Func(arg_0, arg_1='', arg_2=arg_3(arg_4.date.today()),
        arg_6='N/A', arg_7=0, arg_8=0):
        """
        Updates the total.csv file with current data.
        """

        arg_9 = os.path.isfile(arg_1)
        with open(arg_1, 'a') as out_total:
            if not arg_9:
                out_total.write('date,organization,repos,members,teams,'
                    + 'unique_contributors,total_contributors,forks,'
                    + 'stargazers,pull_requests,open_issues,has_readme,'
                    + 'has_license,pull_requests_open,pull_requests_closed,'
                    + 'commits,id,closed_issues,issues\n')
            arg_0.delete_last_line(arg_2=arg_2, arg_1=arg_1)
        out_total.close()
        with open(arg_1, 'r') as file_read:
            arg_10 = sum(1 for row in file_read) - 1
        file_read.close()
        with open(arg_1, 'a') as out_total:
            out_total.write(arg_2 + ',' + arg_6 + ','
                + arg_3(arg_0.total_repos) + ',' + arg_3(arg_7) + ',' + arg_3(arg_8)
                + ',' + arg_3(len(arg_0.unique_contributors)) + ','
                + arg_3(arg_0.total_contributors) + ',' + arg_3(arg_0.total_forks)
                + ',' + arg_3(arg_0.total_stars) + ',' + arg_3(arg_0.total_pull_reqs)
                + ',' + arg_3(arg_0.total_open_issues) + ','
                + arg_3(arg_0.total_readmes) + ',' + arg_3(arg_0.total_licenses) + ','
                + arg_3(arg_0.total_pull_reqs_open) + ','
                + arg_3(arg_0.total_pull_reqs_closed) + ','
                + arg_3(arg_0.total_commits) + ',' + arg_3(arg_10) + ','
                + arg_3(arg_0.total_closed_issues) + ',' + arg_3(arg_0.total_issues)
                + '\n')
        out_total.close()


def Func(arg_0, arg_1='',arg_2=arg_3(arg_4.date.today())):
        """
        Updates languages.csv file with current data.
        """
        arg_0.remove_date(arg_1=arg_1, arg_2=arg_2)
        arg_6 = os.path.isfile(arg_1)
        with open(arg_1, 'a') as out_languages:
            if not arg_6:
                out_languages.write('date,language,count,size,size_log\n')
            arg_7 = sorted(arg_0.languages_size)
            #self.delete_last_line(date=date, file_path=file_path)
            for arg_8 in arg_7:
                try:
                    out_languages.write(arg_2 + ',' + arg_8 + ','
                        + arg_3(arg_0.languages[arg_8]) + ','
                        + arg_3(arg_0.languages_size[arg_8]) + ','
                        + arg_3(math.log10(int(arg_0.languages_size[arg_8])))
                        + '\n')
                except (TypeError, KeyError) as e:
                    out_languages.write(arg_2 + ',' + arg_8 + ','
                        + arg_3(0) + ','
                        + arg_3(arg_0.languages_size[arg_8]) + ','
                        + arg_3(math.log10(int(arg_0.languages_size[arg_8])))
                        + '\n')


def Func(arg_0, arg_1=''):
        """
        Checks if a directory exists. If not, it creates one with the specified
        file_path.
        """
        if not os.path.exists(os.path.dirname(arg_1)):
            try:
                os.makedirs(os.path.dirname(arg_1))
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise


def Func(arg_0, arg_1='', arg_2=arg_3(arg_4.date.today())):
        """
        Removes all rows of the associated date from the given csv file.
        Defaults to today.
        """
        arg_6 = os.path.isfile(arg_1)
        if arg_6:
            with open(arg_1, 'rb') as inp, open('temp.csv', 'wb') as out:
                arg_7 = csv.writer(out)
                for arg_8 in csv.reader(inp):
                    if arg_8[0] != arg_2:
                        arg_7.writerow(arg_8)
            inp.close()
            out.close()
            os.remove(arg_1)
            os.rename("temp.csv",arg_1)


def Func(arg_0, arg_1=None):
    """
    Create a github3.py session for a GitHub Enterprise instance

    If token is not provided, will attempt to use the GITHUB_API_TOKEN
    environment variable if present.
    """

    arg_2 = github3.enterprise_login(arg_0=arg_0, arg_1=arg_1)

    if arg_2 is None:
        arg_3 = 'Unable to connect to GitHub Enterprise (%s) with provided token.'
        raise RuntimeError(arg_3, arg_0)

    return arg_2


def Func(arg_0, arg_1=250, arg_2=15):
    """
    Simplified check for API limits

    If necessary, spin in place waiting for API to reset before returning.

    See: https://developer.github.com/v3/#rate-limiting
    """
    arg_3 = arg_0.rate_limit()

    arg_4 = arg_3['rate']['remaining']
    arg_5 = arg_3['rate']['reset']
    logger.debug('Rate Limit - %d requests remaining', arg_4)

    if arg_4 > arg_1:
        return

    arg_6 = time.time()
    arg_7 = int(arg_5 - arg_6)
    logger.warn('Rate Limit Depleted - Sleeping for %d seconds', arg_7)

    while arg_6 < arg_5:
        time.sleep(10)
        arg_6 = time.time()

    return


def Func(arg_0='https://github.com', arg_1=None):
    """
    Create a GitHub session for making requests
    """

    arg_2 = None
    if arg_0 == 'https://github.com':
        arg_2 = create_session(arg_1)
    else:
        arg_2 = create_enterprise_session(arg_0, arg_1)

    if arg_2 is None:
        arg_3 = 'Unable to Func to (%s) with provided token.'
        raise RuntimeError(arg_3, arg_0)

    logger.info('Connected to: %s', arg_0)

    return arg_2


def Func(arg_0, arg_1=None, arg_2=None, arg_3=True):
    """
    Yields GitHub3.py repo objects for provided orgs and repo names

    If orgs and repos are BOTH empty, execute special mode of getting ALL
    repositories from the GitHub Server.

    If public_only is True, will return only those repos that are marked as
    public. Set this to false to return all organizations that the session has
    permissions to access.
    """

    if arg_1 is None:
        arg_1 = []
    if arg_2 is None:
        arg_2 = []
    if arg_3:
        arg_4 = 'public'
    else:
        arg_4 = 'all'

    _check_api_limits(arg_0, 10)

    for arg_5 in arg_1:
        arg_6 = arg_0.organization(arg_5)
        arg_7 = arg_6.public_repos_count

        _check_api_limits(arg_0, _num_requests_needed(arg_7))

        for arg_8 in arg_6.repositories(type=arg_4):
            _check_api_limits(arg_0, 10)
            yield arg_8

    for arg_9 in arg_2:
        _check_api_limits(arg_0, 10)
        arg_6, arg_10 = arg_9.split('/')
        yield arg_0.repository(arg_6, arg_10)

    if not (arg_1 or arg_2):
        for arg_8 in arg_0.all_repositories():
            yield arg_8


def Func(arg_0, arg_1=''):
        """
        Retrieves an organization via given org name. If given
        empty string, prompts user for an org name.
        """
        arg_0.organization_name = arg_1
        if(arg_1 == ''):
            arg_0.organization_name = raw_input('Organization: ')
        print 'Getting organization.'
        arg_0.org_retrieved = arg_0.logged_in_gh.organization(arg_1)


def Func(arg_0, arg_1, arg_2=True):
        """
        Create CodeGovProject object from GitLab Repository
        """
        if not isinstance(arg_1, gitlab.v4.objects.Project):
            raise TypeError('Repository must be a gitlab Repository object')

        arg_3 = arg_0()

        logger.debug(
            'GitLab: repository_id=%d path_with_namespace=%s',
            arg_1.id,
            arg_1.path_with_namespace,
        )

        # -- REQUIRED FIELDS --

        arg_3['name'] = arg_1.name
        arg_3['repositoryURL'] = arg_1.http_url_to_repo
        arg_3['description'] = arg_1.description

        # TODO: Update licenses from GitLab API
        arg_3['permissions']['licenses'] = None

        arg_4 = arg_1.web_url
        arg_5 = arg_4.startswith('https://gitlab.com')

        if arg_1.visibility in ('public') and arg_5:
            arg_3['permissions']['usageType'] = 'openSource'
        elif date_parse(arg_1.created_at) < POLICY_START_DATE:
            arg_3['permissions']['usageType'] = 'exemptByPolicyDate'

        if arg_2:
            arg_3['laborHours'] = labor_hours_from_url(arg_3['repositoryURL'])
        else:
            arg_3['laborHours'] = 0

        arg_3['tags'] = ['gitlab'] + arg_1.tag_list

        arg_3['contact'] = {
            'email': '',
            'URL': arg_4,
        }

        # -- OPTIONAL FIELDS --

        # project['version'] = ''

        arg_3['organization'] = arg_1.namespace['name']

        # TODO: Currently, can't be an empty string, see: https://github.com/GSA/code-gov-web/issues/370
        arg_3['status'] = 'Development'

        arg_3['vcs'] = 'git'

        arg_3['homepageURL'] = arg_1.web_url

        arg_6 = arg_1.manager.gitlab._url
        arg_7 = '/projects/%s/repository/archive' % arg_1.get_id()
        arg_3['downloadURL'] = arg_6 + arg_7

        # project['languages'] = [l for l, _ in repository.languages()]
        # project['partners'] = []
        # project['relatedCode'] = []
        # project['reusedCode'] = []

        arg_3['date'] = {
            'created': date_parse(arg_1.created_at).date().isoformat(),
            'lastModified': date_parse(arg_1.last_activity_at).date().isoformat(),
            'metadataLastUpdated': '',
        }

        _prune_dict_null_str(arg_3)

        return arg_3


def Func(arg_0, arg_1):
        """
        Create CodeGovProject object from DOE CODE record

        Handles crafting Code.gov Project
        """
        if not isinstance(arg_1, dict):
            raise TypeError('`record` must be a dict')

        arg_2 = arg_0()

        # -- REQUIRED FIELDS --

        arg_2['name'] = arg_1['software_title']
        logger.debug('DOE CODE: software_title="%s"', arg_1['software_title'])

        arg_3 = arg_1.get('repository_link', '')
        if not arg_3:
            arg_3 = arg_1.get('landing_page')
            logger.warning('DOE CODE: No repositoryURL, using landing_page: %s', arg_3)

        arg_2['repositoryURL'] = arg_3

        arg_2['description'] = arg_1['description']

        arg_4 = set(arg_1['licenses'])
        arg_4.discard(None)
        logger.debug('DOE CODE: licenses=%s', arg_4)

        arg_5 = []
        if 'Other' in arg_4:
            arg_4.remove('Other')
            arg_5 = [{
                'name': 'Other',
                'URL': arg_1['proprietary_url']
            }]

        if arg_4:
            arg_5.extend([_license_obj(arg_6) for arg_6 in arg_4])

        arg_2['permissions']['licenses'] = arg_5

        if arg_1['open_source']:
            arg_7 = 'openSource'
        else:
            arg_7 = 'exemptByLaw'
            arg_2['permissions']['exemptionText'] = 'This source code is restricted by patent and / or intellectual property law.'

        arg_2['permissions']['usageType'] = arg_7

        # TODO: Compute from git repo
        arg_2['laborHours'] = 0

        arg_2['tags'] = ['DOE CODE']
        arg_8 = arg_1.get('lab_display_name')
        if arg_8 is not None:
            arg_2['tags'].append(arg_8)

        arg_2['contact']['email'] = arg_1['owner']
        # project['contact']['URL'] = ''
        # project['contact']['name'] = ''
        # project['contact']['phone'] = ''

        # -- OPTIONAL FIELDS --

        if 'version_number' in arg_1 and arg_1['version_number']:
            arg_2['version'] = arg_1['version_number']

        if arg_8 is not None:
            arg_2['organization'] = arg_8

        # Currently, can't be an empty string, see: https://github.com/GSA/code-gov-web/issues/370
        arg_9 = arg_1.get('ever_announced')
        if arg_9 is None:
            raise ValueError('DOE CODE: Unable to determine "ever_announced" value!')
        elif arg_9:
            arg_9 = 'Production'
        else:
            arg_9 = 'Development'

        arg_2['status'] = arg_9

        arg_10 = None
        arg_3 = arg_2['repositoryURL']
        if 'github.com' in arg_3:
            arg_10 = 'git'
        if arg_10 is None:
            logger.debug('DOE CODE: Unable to determine vcs for: name="%s", repositoryURL=%s', arg_2['name'], arg_3)
            arg_10 = ''
        if arg_10:
            arg_2['vcs'] = arg_10

        arg_11 = arg_1.get('landing_page', '')
        if arg_11:
            arg_2['homepageURL'] = arg_11

        # record['downloadURL'] = ''

        # self['disclaimerText'] = ''

        # self['disclaimerURL'] = ''

        if 'programming_languages' in arg_1:
            arg_2['languages'] = arg_1['programming_languages']

        # self['partners'] = []
        # TODO: Look into using record['contributing_organizations']

        # self['relatedCode'] = []

        # self['reusedCode'] = []

        # date: [object] A date object describing the release.
        #   created: [string] The date the release was originally created, in YYYY-MM-DD or ISO 8601 format.
        #   lastModified: [string] The date the release was modified, in YYYY-MM-DD or ISO 8601 format.
        #   metadataLastUpdated: [string] The date the metadata of the release was last updated, in YYYY-MM-DD or ISO 8601 format.
        if 'date_record_added' in arg_1 and 'date_record_updated' in arg_1:
            arg_2['date'] = {
                'created': arg_1['date_record_added'],
                # 'lastModified': '',
                'metadataLastUpdated': arg_1['date_record_updated']
            }

        return arg_2


def Func(arg_0):
        """
        Retrieves the traffic for the repositories of the given organization.
        """
        print 'Getting traffic.'
        #Uses the developer API. Note this could change.
        arg_1 = {'Accept': 'application/vnd.github.spiderman-preview', 'Authorization': 'token ' + arg_0.token}
        arg_2 = {'Authorization': 'token ' + arg_0.token}
        for arg_3 in arg_0.org_retrieved.iter_repos(type='public'):
            arg_4 = ('https://api.github.com/repos/' + arg_0.organization_name
                + '/' + arg_3.name)
            arg_0.get_referrers(arg_4=arg_4, arg_1=arg_1, repo_name=arg_3.name)
            arg_0.get_paths(arg_4=arg_4, arg_1=arg_1)
            arg_0.get_data(arg_4=arg_4, arg_1=arg_1, dict_to_store=arg_0.views,
                type='views', repo_name=arg_3.name)
            arg_0.get_data(arg_4=arg_4, arg_1=arg_1, dict_to_store=arg_0.clones,
                type='clones', repo_name=arg_3.name)
            arg_0.get_releases(arg_4=arg_4, arg_1=arg_2, repo_name=arg_3.name)