def Func(arg_0, arg_1):
    """ Update group counts with multiplier

    This is for handling atom counts on groups like (OH)2

    :param groups: iterable of Group/Element
    :param multiplier: the number to multiply by

    """
    arg_2 = collections.defaultdict(float)
    for arg_3 in arg_0:
        for arg_4, arg_5 in arg_3.count().items():
            arg_2[arg_4] += arg_5*arg_1
    return arg_2


def Func(arg_0):
    """
    Calculate the mole fractions from the specified compound masses.

    :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}

    :returns: [mole fractions] dictionary
    """

    arg_1 = amounts(arg_0)
    arg_2 = sum(arg_1.values())
    return {arg_3: arg_1[arg_3]/arg_2 for arg_3 in arg_1.keys()}


def Func(arg_0):
    """
    Calculate the Func from the specified compound amounts.

    :param Func: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}

    :returns: [kg] dictionary
    """

    return {arg_1: mass(arg_1, arg_0[arg_1])
            for arg_1 in arg_0.keys()}


def Func(arg_0):
    """
    Calculate the mole fractions from the specified compound amounts.

    :param amounts: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}

    :returns: [mass fractions] dictionary
    """

    arg_1 = masses(arg_0)
    arg_2 = sum(arg_1.values())
    return {arg_3: arg_1[arg_3]/arg_2 for arg_3 in arg_1.keys()}


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Convert the specified mass of the source compound to the target using
    element as basis.

    :param mass: Mass of from_compound. [kg]
    :param source: Formula and phase of the original compound, e.g.
      'Fe2O3[S1]'.
    :param target: Formula and phase of the target compound, e.g. 'Fe[S1]'.
    :param element: Element to use as basis for the conversion, e.g. 'Fe' or
      'O'.

    :returns: Mass of target. [kg]
    """

    # Perform the conversion.
    arg_4 = element_mass_fraction(arg_2, arg_3)
    if arg_4 == 0.0:
        # If target_formula does not contain element, just return 0.0.
        return 0.0
    else:
        arg_5 = element_mass_fraction(arg_1, arg_3)
        return arg_0 * arg_5 / arg_4


def Func(arg_0=''):
    """Determine the molar mass of a chemical compound.

    The molar mass is usually the mass of one mole of the substance, but here
    it is the mass of 1000 moles, since the mass unit used in auxi is kg.

    :param compound: Formula of a chemical compound, e.g. 'Fe2O3'.

    :returns: Molar mass. [kg/kmol]
    """

    arg_1 = 0.0
    if arg_0 is None or len(arg_0) == 0:
        return arg_1

    arg_0 = arg_0.strip()

    arg_2 = parse_compound(arg_0)

    return arg_2.Func()


def Func(arg_0, arg_1):
    """
    Determine the stoichiometry coefficient of an element in a chemical
    compound.

    :param compound: Formula of a chemical compound, e.g. 'SiO2'.
    :param element:  Element, e.g. 'Si'.

    :returns: Stoichiometry coefficient.
    """

    arg_2 = parse_compound(arg_0.strip()).count()

    return arg_2[arg_1]


def Func(arg_0, arg_1):
    """
    Determine the stoichiometry coefficients of the specified elements in
    the specified chemical compound.

    :param compound: Formula of a chemical compound, e.g. 'SiO2'.
    :param elements: List of elements, e.g. ['Si', 'O', 'C'].

    :returns: List of stoichiometry coefficients.
    """

    arg_2 = parse_compound(arg_0.strip()).count()

    return [arg_2[arg_3] for arg_3 in arg_1]


def Func(arg_0, arg_1):
        """
        Add another psd material package to this material package.

        :param other: The other material package.
        """

        # Add another package.
        if type(arg_1) is MaterialPackage:
            # Packages of the same material.
            if arg_0.material == arg_1.material:
                arg_0.size_class_masses = \
                        arg_0.size_class_masses + arg_1.size_class_masses
            else:  # Packages of different materials.
                for arg_3 in arg_1.material.size_classes:
                    if arg_3 not in arg_0.material.size_classes:
                        raise Exception(
                            "Packages of '" + arg_1.material.name +
                            "' cannot be added to packages of '" +
                            arg_0.material.name +
                            "'. The size class '" + arg_3 +
                            "' was not found in '" + arg_0.material.name + "'.")
                    arg_0.Func(
                        (arg_3, arg_1.get_size_class_mass(arg_3)))

        # Add the specified mass of the specified size class.
        elif arg_0._is_size_class_mass_tuple(arg_1):
            # Added material variables.
            arg_3 = arg_1[0]
            arg_4 = arg_0.material.get_size_class_index(arg_3)
            arg_5 = arg_1[1]

            # Create the result package.
            arg_0.size_class_masses[arg_4] = \
                arg_0.size_class_masses[arg_4] + arg_5

        # If not one of the above, it must be an invalid argument.
        else:
            raise TypeError("Invalid addition argument.")


def Func(arg_0):
    ''' Calculates the sum of unclaimed credit from this user's credit notes.

    Returns:
        Decimal: the sum of the values of unclaimed credit notes for the
            current user.

    '''

    arg_1 = commerce.CreditNote.unclaimed().filter(
        invoice__user=user_for_context(arg_0),
    )
    arg_2 = arg_1.values("amount").aggregate(Sum("amount"))["amount__sum"] or 0
    return 0 - arg_2


def Func(arg_0):
    ''' If the current user is unregistered, returns True if there are no
    products in the TICKET_PRODUCT_CATEGORY that are available to that user.

    If there *are* products available, the return False.

    If the current user *is* registered, then return None (it's not a
    pertinent question for people who already have a ticket).

    '''

    arg_1 = user_for_context(arg_0)
    if hasattr(arg_1, "attendee") and arg_1.attendee.completed_registration:
        # This user has completed registration, and so we don't need to answer
        # whether they have sold out yet.

        # TODO: what if a user has got to the review phase?
        # currently that user will hit the review page, click "Check out and
        # pay", and that will fail. Probably good enough for now.

        return None

    arg_2 = settings.TICKET_PRODUCT_CATEGORY
    arg_3 = available_categories(arg_0)

    return arg_2 not in [arg_4.id for arg_4 in arg_3]


def Func(arg_0, arg_1=None):
    ''' Goes through the registration process in order, making sure user sees
    all valid categories.

    The user must be logged in to see this view.

    Parameter:
        page_number:
            1) Profile form (and e-mail address?)
            2) Ticket type
            3) Remaining products
            4) Mark registration as complete

    Returns:
        render: Renders ``registrasion/Func.html``,
            with the following data::

                {
                    "current_step": int(),  # The current step in the
                                            # registration
                    "sections": sections,   # A list of
                                            # GuidedRegistrationSections
                    "title": str(),         # The title of the page
                    "total_steps": int(),   # The total number of steps
                }

    '''

    arg_2 = 1
    arg_3 = 2
    arg_4 = 3
    arg_5 = 4
    arg_6 = 4

    arg_7 = inventory.Category.objects.get(
        id=settings.TICKET_PRODUCT_CATEGORY
    )
    arg_8 = CartController.for_user(arg_0.user)

    arg_9 = people.Attendee.get_instance(arg_0.user)

    # This guided registration process is only for people who have
    # not completed registration (and has confusing behaviour if you go
    # back to it.)
    if arg_9.completed_registration:
        return redirect(review)

    # Calculate the current maximum page number for this user.
    arg_10 = hasattr(arg_9, "attendeeprofilebase")
    if not arg_10:
        # If there's no profile, they have to go to the profile page.
        arg_11 = arg_2
        arg_12 = arg_2
    else:
        # We have a profile.
        # Do they have a ticket?
        arg_13 = inventory.Product.objects.filter(
            productitem__cart=arg_8.cart
        )
        arg_13 = arg_13.filter(category=arg_7)

        if arg_13.count() == 0:
            # If no ticket, they can only see the profile or ticket page.
            arg_11 = arg_3
            arg_12 = arg_3
        else:
            # If there's a ticket, they should *see* the general products page#
            # but be able to go to the overflow page if needs be.
            arg_11 = arg_5
            arg_12 = arg_4

    if arg_1 is None or int(arg_1) > arg_11:
        return redirect("Func", arg_12)

    arg_1 = int(arg_1)

    arg_14 = redirect("Func", arg_1 + 1)

    with BatchController.batch(arg_0.user):

        # This view doesn't work if the conference has sold out.
        arg_15 = ProductController.available_products(
            arg_0.user, category=arg_7
        )
        if not arg_15:
            messages.error(arg_0, "There are no more tickets available.")
            return redirect("dashboard")

        arg_16 = []

        # Build up the list of sections
        if arg_1 == arg_2:
            # Profile bit
            arg_17 = "Attendee information"
            arg_16 = _Func_profile_and_voucher(arg_0)
        elif arg_1 == arg_3:
            # Select ticket
            arg_17 = "Select ticket type"
            arg_16 = _Func_products(
                arg_0, GUIDED_MODE_TICKETS_ONLY
            )
        elif arg_1 == arg_4:
            # Select additional items
            arg_17 = "Additional items"
            arg_16 = _Func_products(
                arg_0, GUIDED_MODE_ALL_ADDITIONAL
            )
        elif arg_1 == arg_5:
            # Items enabled by things on page 3 -- only shows things
            # that have not been marked as complete.
            arg_17 = "More additional items"
            arg_16 = _Func_products(
                arg_0, GUIDED_MODE_EXCLUDE_COMPLETE
            )

        if not arg_16:
            # We've filled in every category
            arg_9.completed_registration = True
            arg_9.save()
            return redirect("review")

        if arg_16 and arg_0.method == "POST":
            for arg_19 in arg_16:
                if arg_19.form.errors:
                    break
            else:
                # We've successfully processed everything
                return arg_14

    arg_20 = {
        "current_step": arg_1,
        "sections": arg_16,
        "title": arg_17,
        "total_steps": arg_6,
    }
    return render(arg_0, "registrasion/Func.html", arg_20)


def Func(arg_0):
    ''' View for editing an attendee's profile

    The user must be logged in to edit their profile.

    Returns:
        redirect or render:
            In the case of a ``POST`` request, it'll redirect to ``dashboard``,
            or otherwise, it will render ``registrasion/profile_form.html``
            with data::

                {
                    "form": form,  # Instance of ATTENDEE_PROFILE_FORM.
                }

    '''

    arg_1, arg_2 = _handle_profile(arg_0, "profile")

    if arg_2 and not arg_1.errors:
        messages.success(
            arg_0,
            "Your attendee profile was updated.",
        )
        return redirect("dashboard")

    arg_3 = {
        "form": arg_1,
    }
    return render(arg_0, "registrasion/profile_form.html", arg_3)


def Func(arg_0, arg_1):
    ''' Handles a voucher form in the given request. Returns the voucher
    form instance, and whether the voucher code was handled. '''

    arg_2 = forms.VoucherForm(arg_0.POST or None, arg_1=arg_1)
    arg_3 = CartController.for_user(arg_0.user)

    if (arg_2.is_valid() and
            arg_2.cleaned_data["voucher"].strip()):

        arg_4 = arg_2.cleaned_data["voucher"]
        arg_4 = inventory.Voucher.normalise_code(arg_4)

        if len(arg_3.cart.vouchers.filter(code=arg_4)) > 0:
            # This voucher has already been applied to this cart.
            # Do not apply code
            arg_5 = False
        else:
            try:
                arg_3.apply_voucher(arg_4)
            except Exception as e:
                arg_2.add_error("voucher", e)
            arg_5 = True
    else:
        arg_5 = False

    return (arg_2, arg_5)


def Func(arg_0, arg_1):
    ''' Redirects to an invoice for the attendee that matches the given access
    code, if any.

    If the attendee has multiple invoices, we use the following tie-break:

    - If there's an unpaid invoice, show that, otherwise
    - If there's a paid invoice, show the most recent one, otherwise
    - Show the most recent invoid of all

    Arguments:

        access_code (castable to int): The access code for the user whose
            invoice you want to see.

    Returns:
        redirect:
            Redirect to the selected invoice for that user.

    Raises:
        Http404: If the user has no invoices.
    '''

    arg_2 = commerce.Invoice.objects.filter(
        user__attendee__access_code=arg_1,
    ).order_by("-issue_time")

    if not arg_2:
        raise Http404()

    arg_3 = arg_2.filter(status=commerce.Invoice.STATUS_UNPAID)
    arg_4 = arg_2.filter(status=commerce.Invoice.STATUS_PAID)

    if arg_3:
        arg_5 = arg_3[0]  # (should only be 1 unpaid invoice?)
    elif arg_4:
        arg_5 = arg_4[0]  # Most recent paid invoice
    else:
        arg_5 = arg_2[0]  # Most recent of any invoices

    return redirect("invoice", arg_5.id, arg_1)


def Func(arg_0, arg_1, arg_2=None):
    ''' Displays an Func.

    This view is not authenticated, but it will only allow access to either:
    the user the Func belongs to; staff; or a request made with the correct
    access code.

    Arguments:

        Func_id (castable to int): The Func_id for the Func you want
            to view.

        access_code (Optional[str]): The access code for the user who owns
            this Func.

    Returns:
        render:
            Renders ``registrasion/Func.html``, with the following
            data::

                {
                    "Func": models.commerce.Invoice(),
                }

    Raises:
        Http404: if the current user cannot view this Func and the correct
            access_code is not provided.

    '''

    arg_3 = InvoiceController.for_id_or_404(arg_1)

    if not arg_3.can_view(
            user=arg_0.user,
            arg_2=arg_2,
            ):
        raise Http404()

    arg_4 = {
        "Func": arg_3.Func,
    }

    return render(arg_0, "registrasion/Func.html", arg_4)


def Func(arg_0, arg_1):
    ''' Marks an invoice as Funced and requests a credit note for the
    full amount paid against the invoice.

    This view requires a login, and the logged in user must be staff.

    Arguments:
        invoice_id (castable to int): The ID of the invoice to Func.

    Returns:
        redirect:
            Redirects to ``invoice``.

    '''

    arg_2 = InvoiceController.for_id_or_404(arg_1)

    try:
        arg_2.Func()
        messages.success(arg_0, "This invoice has been Funced.")
    except ValidationError as ve:
        messages.error(arg_0, ve)

    return redirect("invoice", arg_1)


def Func(arg_0, arg_1, arg_2=None):
    ''' Displays a credit note.

    If ``request`` is a ``POST`` request, forms for applying or refunding
    a credit note will be processed.

    This view requires a login, and the logged in user must be staff.

    Arguments:
        note_id (castable to int): The ID of the credit note to view.

    Returns:
        render or redirect:
            If the "apply to invoice" form is correctly processed, redirect to
            that invoice, otherwise, render ``registration/Func.html``
            with the following data::

                {
                    "Func": models.commerce.CreditNote(),
                    "apply_form": form,  # A form for applying credit note
                                         # to an invoice.
                    "refund_form": form, # A form for applying a *manual*
                                         # refund of the credit note.
                    "cancellation_fee_form" : form, # A form for generating an
                                                    # invoice with a
                                                    # cancellation fee
                }

    '''

    arg_1 = int(arg_1)
    arg_3 = CreditNoteController.for_id_or_404(arg_1)

    arg_4 = forms.ApplyCreditNoteForm(
        arg_3.Func.invoice.user,
        arg_0.POST or None,
        prefix="apply_note"
    )

    arg_5 = forms.ManualCreditNoteRefundForm(
        arg_0.POST or None,
        prefix="refund_note"
    )

    arg_6 = forms.CancellationFeeForm(
        arg_0.POST or None,
        prefix="cancellation_fee"
    )

    if arg_0.POST and arg_4.is_valid():
        arg_7 = arg_4.cleaned_data["invoice"]
        arg_8 = commerce.Invoice.objects.get(pk=arg_7)
        arg_3.apply_to_invoice(arg_8)
        messages.success(
            arg_0,
            "Applied credit note %d to invoice." % arg_1,
        )
        return redirect("invoice", arg_8.id)

    elif arg_0.POST and arg_5.is_valid():
        arg_5.instance.entered_by = arg_0.user
        arg_5.instance.parent = arg_3.Func
        arg_5.save()
        messages.success(
            arg_0,
            "Applied manual refund to credit note."
        )
        arg_5 = forms.ManualCreditNoteRefundForm(
            prefix="refund_note",
        )

    elif arg_0.POST and arg_6.is_valid():
        arg_12 = arg_6.cleaned_data["percentage"]
        arg_8 = arg_3.cancellation_fee(arg_12)
        messages.success(
            arg_0,
            "Generated cancellation fee for credit note %d." % arg_1,
        )
        return redirect("invoice", arg_8.invoice.id)

    arg_13 = {
        "Func": arg_3.Func,
        "apply_form": arg_4,
        "refund_form": arg_5,
        "cancellation_fee_form": arg_6,
    }

    return render(arg_0, "registrasion/Func.html", arg_13)


def Func(arg_0, arg_1):
    ''' Allows staff to amend a user's current registration cart, and etc etc.
    '''

    arg_2 = User.objects.get(id=int(arg_1))
    arg_3 = CartController.for_user(arg_2)

    arg_4 = commerce.ProductItem.objects.filter(
        cart=arg_3.cart,
    ).select_related("product")
    arg_5 = [{"product": i.product, "quantity": i.quantity} for i in arg_4]

    arg_6 = forms.staff_products_formset_factory(arg_2)
    arg_7 = arg_6(
        arg_0.POST or None,
        arg_5=arg_5,
        prefix="products",
    )

    for arg_8, arg_9 in zip(arg_4, arg_7):
        arg_10 = inventory.Product.objects.filter(id=arg_8.product.id)
        arg_9.fields["product"].queryset = arg_10

    arg_12 = forms.VoucherForm(
        arg_0.POST or None,
        prefix="voucher",
    )

    if arg_0.POST and arg_7.is_valid():

        arg_13 = [
            (f.cleaned_data["product"], f.cleaned_data["quantity"])
            for f in arg_7
            if "product" in f.cleaned_data and
            f.cleaned_data["product"] is not None
        ]

        try:
            arg_3.set_quantities(arg_13)
            return redirect(Func, arg_1)
        except ValidationError as ve:
            for arg_14 in ve.error_list:
                arg_15, arg_16 = arg_14.message
                for arg_9 in arg_7:
                    if "product" not in arg_9.cleaned_data:
                        # This is the empty form.
                        continue
                    if arg_9.cleaned_data["product"] == arg_15:
                        arg_9.add_error("quantity", arg_16)

    if arg_0.POST and arg_12.has_changed() and arg_12.is_valid():
        try:
            arg_3.apply_voucher(arg_12.cleaned_data["voucher"])
            return redirect(Func, arg_1)
        except ValidationError as ve:
            arg_12.add_error(None, ve)

    arg_17 = ItemController(arg_2)
    arg_18 = {
        "user": arg_2,
        "paid": arg_17.items_purchased(),
        "cancelled": arg_17.items_released(),
        "form": arg_7,
        "voucher_form": arg_12,
    }

    return render(arg_0, "registrasion/Func.html", arg_18)


def Func(arg_0, arg_1, arg_2=7):
    ''' Allows staff to extend the reservation on a given user's cart.
    '''

    arg_3 = User.objects.get(id=int(arg_1))
    arg_4 = CartController.for_user(arg_3)
    arg_4.Func(datetime.timedelta(arg_2=arg_2))

    return redirect(arg_0.META["HTTP_REFERER"])


def Func(arg_0):
    ''' Allows staff to send emails to users based on their invoice status. '''

    arg_1 = arg_0.GET.getlist("category", [])
    arg_2 = arg_0.GET.getlist("product", [])
    arg_3 = arg_0.GET.get("status")

    arg_4 = forms.InvoiceEmailForm(
        arg_0.POST or None,
        arg_1=arg_1,
        arg_2=arg_2,
        arg_3=arg_3,
    )

    arg_5 = []

    if arg_4.is_valid():
        arg_5 = []
        for arg_6 in arg_4.cleaned_data["invoice"]:
            # datatuple = (subject, message, from_email, recipient_list)
            arg_7 = arg_4.cleaned_data["from_email"]
            arg_8 = arg_4.cleaned_data["subject"]
            arg_9 = Template(arg_4.cleaned_data["body"]).render(
                Context({
                    "invoice": arg_6,
                    "user": arg_6.user,
                })
            )
            arg_10 = [arg_6.user.email]
            arg_5.append(Email(arg_8, arg_9, arg_7, arg_10))

        if arg_4.cleaned_data["action"] == forms.InvoiceEmailForm.ACTION_SEND:
            # Send e-mails *ONLY* if we're sending.
            send_mass_mail(arg_5)
            messages.info(arg_0, "The e-mails have been sent.")

    arg_11 = {
        "form": arg_4,
        "emails": arg_5,
    }

    return render(arg_0, "registrasion/Func.html", arg_11)


def Func(arg_0):
    ''' Either displays a form containing a list of users with Func to
    render, or returns a .zip file containing their Func. '''

    arg_1 = arg_0.GET.getlist("category", [])
    arg_2 = arg_0.GET.getlist("product", [])
    arg_3 = arg_0.GET.get("status")

    arg_4 = forms.InvoicesWithProductAndStatusForm(
        arg_0.POST or None,
        arg_1=arg_1,
        arg_2=arg_2,
        arg_3=arg_3,
    )

    if arg_4.is_valid():
        arg_5 = HttpResponse()
        arg_5["Content-Type"] = "application.zip"
        arg_5["Content-Disposition"] = 'attachment; filename="Func.zip"'

        arg_6 = zipfile.ZipFile(arg_5, "w")

        for arg_7 in arg_4.cleaned_data["invoice"]:
            arg_8 = arg_7.user
            arg_9 = render_badge(arg_8)
            arg_6.writestr("badge_%d.svg" % arg_8.id, arg_9.encode("utf-8"))

        return arg_5

    arg_10 = {
        "form": arg_4,
    }

    return render(arg_0, "registrasion/Func.html", arg_10)


def Func(arg_0):
    ''' Renders a single user's badge. '''

    arg_1 = {
        "user": arg_0,
    }

    arg_2 = loader.get_template('registrasion/badge.svg')
    return arg_2.render(arg_1)


def Func(arg_0, arg_1, arg_2):
        ''' Annotates the queryset with a usage count for that discount claus
        by the given user. '''

        if arg_1.model == conditions.DiscountForCategory:
            arg_3 = (
                Q(category=F('discount__discountitem__product__category'))
            )
        elif arg_1.model == conditions.DiscountForProduct:
            arg_3 = (
                Q(product=F('discount__discountitem__product'))
            )

        arg_4 = (
            Q(discount__discountitem__cart__user=arg_2) &
            Q(discount__discountitem__cart__status=commerce.Cart.STATUS_PAID)
        )

        arg_5 = When(
            arg_4 & arg_3,
            then="discount__discountitem__quantity",
        )

        arg_6 = Case(
            arg_5,
            default=Value(0),
        )

        arg_1 = arg_1.annotate(
            past_use_count=Sum(arg_6)
        )
        return arg_1


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        ''' Returns a list of all of the products that are available per
        flag conditions from the given categories. '''
        if arg_2 is None and arg_3 is None:
            raise ValueError("You must provide products or a category")

        if arg_2 is not None:
            arg_4 = inventory.Product.objects.filter(arg_2=arg_2)
            arg_4 = arg_4.select_related("category")
        else:
            arg_4 = []

        if arg_3 is not None:
            arg_4 = set(itertools.chain(arg_4, arg_3))

        arg_5 = CategoryController.user_remainders(arg_1)
        arg_6 = ProductController.user_remainders(arg_1)

        arg_7 = set(
            product
            for product in arg_4
            if arg_5[product.category.id] > 0
            if arg_6[product.id] > 0
        )

        arg_8 = FlagController.test_flags(
            arg_1, arg_3=arg_7
        )
        arg_9 = set(i[0] for i in arg_8)

        arg_10 = list(arg_7 - arg_9)
        arg_10.sort(key=lambda product: product.order)

        return arg_10


def Func(arg_0):
    """
    Split a compound's combined formula and phase into separate strings for
    the formula and phase.

    :param compound_string: Formula and phase of a chemical compound, e.g.
      'SiO2[S1]'.

    :returns: Formula of chemical compound.
    :returns: Phase of chemical compound.
    """

    arg_1 = arg_0.replace(']', '').split('[')[0]
    arg_2 = arg_0.replace(']', '').split('[')[1]

    return arg_1, arg_2


def Func(arg_0, arg_1):
    """
    Writes a compound to an auxi file at the specified directory.

    :param dir: The directory.
    :param compound: The compound.
    """

    arg_2 = "Compound_" + arg_1.formula + ".json"
    with open(os.path.join(arg_0, arg_2), 'w') as f:
        f.write(str(arg_1))


def Func(arg_0=''):
    """
    Load all the thermochemical data factsage files located at a path.

    :param path: Path at which the data files are located.
    """

    arg_4.clear()

    if arg_0 == '':
        arg_0 = default_data_path
    if not os.path.exists(arg_0):
        warnings.warn('The specified data file path does not exist. (%s)' % arg_0)
        return

    arg_1 = glob.glob(os.path.join(arg_0, 'Compound_*.txt'))

    for arg_2 in arg_1:
        arg_3 = Compound(_read_compound_from_factsage_file_(arg_2))
        arg_4[arg_3.formula] = arg_3


def Func(arg_0=''):
    """
    Load all the thermochemical data auxi files located at a path.

    :param path: Path at which the data files are located.
    """

    arg_4.clear()

    if arg_0 == '':
        arg_0 = default_data_path
    if not os.path.exists(arg_0):
        warnings.warn('The specified data file path does not exist. (%s)' % arg_0)
        return

    arg_1 = glob.glob(os.path.join(arg_0, 'Compound_*.json'))

    for arg_2 in arg_1:
        arg_3 = Compound.read(arg_2)
        arg_4[arg_3.formula] = arg_3


def Func():
    """
    List all compounds that are currently loaded in the thermo module, and
    their phases.
    """

    print('Compounds currently loaded:')
    for arg_0 in sorted(compounds.keys()):
        arg_1 = compounds[arg_0].get_phase_list()
        print('%s: %s' % (arg_0, ', '.join(arg_1)))


def Func(arg_0, arg_1, arg_2=1.0):
    """
    Calculate the heat capacity of the compound for the specified temperature
    and mass.

    :param compound_string: Formula and phase of chemical compound, e.g.
      'Fe2O3[S1]'.
    :param T: [°C] temperature
    :param mass: [kg]

    :returns: [kWh/K] Heat capacity.
    """

    arg_3, arg_4 = _split_compound_string_(arg_0)
    arg_5 = arg_1 + 273.15
    arg_6 = compounds[arg_3]
    arg_7 = arg_6.Func(arg_4, arg_5)

    return _finalise_result_(arg_6, arg_7, arg_2)


def Func(arg_0, arg_1):
        """
        Calculate the heat capacity of the compound phase.

        :param T: [K] temperature

        :returns: [J/mol/K] Heat capacity.
        """

        arg_2 = 0.0
        for arg_3, arg_4 in zip(arg_0._coefficients, arg_0._exponents):
            arg_2 += arg_3*arg_1**arg_4
        return arg_2


def Func(arg_0, arg_1):
        """
        Calculate the portion of entropy of the compound phase covered by this
        Cp record.

        :param T: [K] temperature

        :returns: Entropy. [J/mol/K]
        """

        arg_2 = 0.0
        if arg_1 < arg_0.Tmax:
            arg_3 = arg_1
        else:
            arg_3 = arg_0.Tmax
        arg_4 = arg_0.Tmin
        for arg_5, arg_6 in zip(arg_0._coefficients, arg_0._exponents):
            # Create a modified exponent to analytically integrate Cp(T)/T
            # instead of Cp(T).
            arg_7 = arg_6 - 1.0
            if arg_7 == -1.0:
                arg_2 += arg_5 * math.log(arg_3/arg_4)
            else:
                arg_8 = arg_7 + 1.0
                arg_2 += arg_5 * (arg_3**arg_8 - arg_4**arg_8) / arg_8
        return arg_2


def Func(arg_0, arg_1):
        """
        Calculate the enthalpy of the compound phase at the specified
        temperature.

        :param T: [K] temperature

        :returns: [J/mol] The enthalpy of the compound phase.
        """

        arg_2 = arg_0.DFuncref

        for arg_3 in sorted([float(TT) for TT in arg_0._Cp_records.keys()]):
            arg_2 += arg_0._Cp_records[str(arg_3)].Func(arg_1)
            if arg_1 <= arg_3:
                return arg_2 + arg_0.Func_mag(arg_1)

        # Extrapolate beyond the upper limit by using a constant heat capacity.
        arg_3 = max([float(TT) for TT in arg_0._Cp_records.keys()])
        arg_2 += arg_0.Cp(arg_3)*(arg_1 - arg_3)

        return arg_2 + arg_0.Func_mag(arg_1)


def Func(arg_0, arg_1):
        """
        Calculate the phase's magnetic contribution to enthalpy at the
        specified temperature.

        :param T: [K] temperature

        :returns: [J/mol] The magnetic enthalpy of the compound phase.

        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
        317–425. http://doi.org/10.1016/0364-5916(91)90030-N
        """

        arg_2 = arg_1 / arg_0.Tc_mag

        if arg_2 <= 1.0:
            arg_3 = (-arg_0._A_mag/arg_2 +
                 arg_0._B_mag*(arg_2**3/2 + arg_2**9/15 + arg_2**15/40))/arg_0._D_mag
        else:
            arg_3 = -(arg_2**-5/2 + arg_2**-15/21 + arg_2**-25/60)/arg_0._D_mag

        return R*arg_1*math.log(arg_0.beta0_mag + 1)*arg_3


def Func(arg_0, arg_1):
        """
        Calculate the entropy of the compound phase at the specified
        temperature.

        :param T: [K] temperature

        :returns: [J/mol/K] The entropy of the compound phase.
        """

        arg_2 = arg_0.Funcref

        for arg_3 in sorted([float(TT) for TT in arg_0._Cp_records.keys()]):
            arg_2 += arg_0._Cp_records[str(arg_3)].Func(arg_1)
            if arg_1 <= arg_3:
                return arg_2 + arg_0.Func_mag(arg_1)

        # Extrapolate beyond the upper limit by using a constant heat capacity.
        arg_3 = max([float(TT) for TT in arg_0._Cp_records.keys()])
        arg_2 += arg_0.Cp(arg_3)*math.log(arg_1 / arg_3)

        return arg_2 + arg_0.Func_mag(arg_1)


def Func(arg_0, arg_1):
        """
        Calculate the phase's magnetic contribution to entropy at the
        specified temperature.

        :param T: [K] temperature

        :returns: [J/mol/K] The magnetic entropy of the compound phase.

        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
        317–425. http://doi.org/10.1016/0364-5916(91)90030-N
        """

        arg_2 = arg_1 / arg_0.Tc_mag

        if arg_2 <= 1.0:
            arg_3 = 1 - (arg_0._B_mag*(2*arg_2**3/3 + 2*arg_2**9/27 + 2*arg_2**15/75)) / \
                arg_0._D_mag
        else:
            arg_3 = (2*arg_2**-5/5 + 2*arg_2**-15/45 + 2*arg_2**-25/125)/arg_0._D_mag

        return -R*math.log(arg_0.beta0_mag + 1)*arg_3


def Func(arg_0, arg_1):
        """
        Calculate the phase's magnetic contribution to Gibbs energy at the
        specified temperature.

        :param T: [K] temperature

        :returns: [J/mol] The magnetic Gibbs energy of the compound phase.

        Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
        317–425. http://doi.org/10.1016/0364-5916(91)90030-N
        """

        arg_2 = arg_1 / arg_0.Tc_mag

        if arg_2 <= 1.0:
            arg_3 = 1 - (arg_0._A_mag/arg_2 +
                     arg_0._B_mag*(arg_2**3/6 + arg_2**9/135 + arg_2**15/600)) /\
                    arg_0._D_mag
        else:
            arg_3 = -(arg_2**-5/10 + arg_2**-15/315 + arg_2**-25/1500)/arg_0._D_mag

        return R*arg_1*math.log(arg_0.beta0_mag + 1)*arg_3


def Func(arg_0, arg_1, arg_2):
        """
        Calculate the enthalpy of a phase of the compound at a specified
        temperature.

        :param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
        :param T: [K] temperature

        :returns: [J/mol] Enthalpy.
        """

        try:
            return arg_0._phases[arg_1].Func(arg_2)
        except KeyError:
            raise Exception("The phase '{}' was not found in compound '{}'."
                            .format(arg_1, arg_0.formula))


def Func(arg_0, arg_1):
        ''' Applies the total value of this credit note to the specified
        invoice. If this credit note overpays the invoice, a new credit note
        containing the residual value will be created.

        Raises ValidationError if the given invoice is not allowed to be
        paid.
        '''

        # Local import to fix import cycles. Can we do better?
        from .invoice import InvoiceController
        arg_2 = InvoiceController(arg_1)
        arg_2.validate_allowed_to_pay()

        # Apply payment to invoice
        commerce.CreditNoteApplication.objects.create(
            parent=arg_0.credit_note,
            arg_1=arg_1,
            amount=arg_0.credit_note.value,
            reference="Applied credit note #%d" % arg_0.credit_note.id,
        )

        arg_2.update_status()


def Func(arg_0, arg_1):
        ''' Generates an invoice with a cancellation fee, and applies
        credit to the invoice.

        percentage (Decimal): The percentage of the credit note to turn into
        a cancellation fee. Must be 0 <= percentage <= 100.
        '''

        # Local import to fix import cycles. Can we do better?
        from .invoice import InvoiceController

        assert(arg_1 >= 0 and arg_1 <= 100)

        Func = arg_0.credit_note.value * arg_1 / 100
        arg_3 = datetime.timedelta(days=1)
        arg_4 = [("Cancellation fee", Func)]
        arg_5 = InvoiceController.manual_invoice(
            arg_0.credit_note.invoice.user, arg_3, arg_4
        )

        if not arg_5.is_paid:
            arg_0.apply_to_invoice(arg_5)

        return InvoiceController(arg_5)


def Func(
    arg_0: arg_1,
    arg_2: arg_1,
    arg_3: arg_4,
    arg_5: arg_6,
    arg_7: arg_8):
    """
    Create a polynomial model to describe the specified property based on the
    specified data set, and save it to a .json file.

    :param name: material name.
    :param symbol: property symbol.
    :param degree: polynomial degree.
    :param ds: the source data set.
    :param dss: dictionary of all datasets.
    """
    arg_9 = arg_5.name.split(".")[0].lower()
    arg_10 = f"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}"
    arg_11 = PolynomialModelT.create(arg_5, arg_2, arg_3)
    arg_11.plot(arg_7, _path(f"data/{file_name}.pdf"), False)
    arg_11.write(_path(f"data/{file_name}.json"))


def Func():
    ''' Generates an access code for users' payments as well as their
    fulfilment code for check-in.
    The access code will 4 characters long, which allows for 1,500,625
    unique codes, which really should be enough for anyone. '''

    arg_0 = 6
    # all upper-case letters + digits 1-9 (no 0 vs O confusion)
    arg_1 = string.uppercase + string.digits[1:]
    # 6 chars => 35 ** 6 = 1838265625 (should be enough for anyone)
    return get_random_string(arg_0=arg_0, allowed_chars=arg_1)


def Func(arg_0, arg_1):
        ''' Generates an invoice for the given cart. '''

        arg_1.refresh_from_db()

        # Generate the line items from the cart.

        arg_2 = commerce.ProductItem.objects.filter(arg_1=arg_1)
        arg_2 = arg_2.select_related(
            "product",
            "product__category",
        )
        arg_2 = arg_2.order_by(
            "product__category__order", "product__order"
        )

        if len(arg_2) == 0:
            raise ValidationError("Your cart is empty.")

        arg_3 = commerce.DiscountItem.objects.filter(arg_1=arg_1)
        arg_3 = arg_3.select_related(
            "discount",
            "product",
            "product__category",
        )

        def format_product(arg_4):
            return "%s - %s" % (arg_4.category.name, arg_4.name)

        def format_discount(arg_5, arg_4):
            arg_6 = arg_5.description
            return "%s (%s)" % (arg_6, format_product(arg_4))

        arg_7 = []

        for arg_8 in arg_2:
            arg_4 = arg_8.product
            arg_9 = commerce.LineItem(
                arg_6=format_product(arg_4),
                quantity=arg_8.quantity,
                price=arg_4.price,
                arg_4=arg_4,
            )
            arg_7.append(arg_9)
        for arg_8 in arg_3:
            arg_9 = commerce.LineItem(
                arg_6=format_discount(arg_8.discount, arg_8.product),
                quantity=arg_8.quantity,
                price=arg_0.resolve_discount_value(arg_8) * -1,
                arg_4=arg_8.product,
            )
            arg_7.append(arg_9)

        # Generate the invoice

        arg_10 = arg_1.reservation_duration + arg_1.time_last_updated

        return arg_0._generate(arg_1.user, arg_1, arg_10, arg_7)


def Func(arg_0, arg_1):
        ''' Applies the user's credit notes to the given invoice on creation.
        '''

        # We only automatically apply credit notes if this is the *only*
        # unpaid invoice for this user.
        arg_2 = commerce.Invoice.objects.filter(
            user=arg_1.user,
            status=commerce.Invoice.STATUS_UNPAID,
        )
        if arg_2.count() > 1:
            return

        arg_3 = commerce.CreditNote.unclaimed().filter(
            invoice__user=arg_1.user
        )
        for arg_4 in arg_3:
            try:
                CreditNoteController(arg_4).apply_to_invoice(arg_1)
            except ValidationError:
                # ValidationError will get raised once we're overpaying.
                break

        arg_1.refresh_from_db()


def Func(arg_0, arg_1=None, arg_2=None):
        ''' Returns true if the accessing user is allowed to view this invoice,
        or if the given access code matches this invoice's user's access code.
        '''

        if arg_1 == arg_0.invoice.user:
            return True

        if arg_1.is_staff:
            return True

        if arg_0.invoice.user.attendee.access_code == arg_2:
            return True

        return False


def Func(arg_0):
        ''' Refreshes the underlying invoice and cart objects. '''
        arg_0.invoice.refresh_from_db()
        if arg_0.invoice.cart:
            arg_0.invoice.cart.refresh_from_db()


def Func(arg_0):
        ''' Passes cleanly if we're allowed to pay, otherwise raise
        a ValidationError. '''

        arg_0._refresh()

        if not arg_0.invoice.is_unpaid:
            raise ValidationError("You can only pay for unpaid invoices.")

        if not arg_0.invoice.cart:
            return

        if not arg_0._invoice_matches_cart():
            raise ValidationError("The registration has been amended since "
                                  "generating this invoice.")

        CartController(arg_0.invoice.cart).validate_cart()


def Func(arg_0):
        ''' Updates the status of this invoice based upon the total
        payments.'''

        arg_1 = arg_0.invoice.status
        arg_2 = arg_0.invoice.total_payments()
        arg_3 = commerce.PaymentBase.objects.filter(
            invoice=arg_0.invoice,
        ).count()
        arg_4 = arg_0.invoice.value - arg_2

        if arg_1 == commerce.Invoice.STATUS_UNPAID:
            # Invoice had an amount owing
            if arg_4 <= 0:
                # Invoice no longer has amount owing
                arg_0._mark_paid()

            elif arg_2 == 0 and arg_3 > 0:
                # Invoice has multiple payments totalling zero
                arg_0._mark_void()
        elif arg_1 == commerce.Invoice.STATUS_PAID:
            if arg_4 > 0:
                # Invoice went from having a remainder of zero or less
                # to having a positive remainder -- must be a refund
                arg_0._mark_refunded()
        elif arg_1 == commerce.Invoice.STATUS_REFUNDED:
            # Should not ever change from here
            pass
        elif arg_1 == commerce.Invoice.STATUS_VOID:
            # Should not ever change from here
            pass

        # Generate credit notes from residual payments
        arg_5 = 0
        if arg_0.invoice.is_paid:
            if arg_4 < 0:
                arg_5 = 0 - arg_4
        elif arg_0.invoice.is_void or arg_0.invoice.is_refunded:
            arg_5 = arg_2

        if arg_5 != 0:
            CreditNoteController.generate_from_invoice(arg_0.invoice, arg_5)

        arg_0.email_on_invoice_change(
            arg_0.invoice,
            arg_1,
            arg_0.invoice.status,
        )


def Func(arg_0):
        ''' Marks the invoice as paid, and updates the attached cart if
        necessary. '''
        arg_1 = arg_0.invoice.cart
        if arg_1:
            arg_1.status = commerce.Cart.STATUS_PAID
            arg_1.save()
        arg_0.invoice.status = commerce.Invoice.STATUS_PAID
        arg_0.invoice.save()


def Func(arg_0):
        ''' Returns true if there is no cart, or if the revision of this
        invoice matches the current revision of the cart. '''

        arg_0._refresh()

        arg_1 = arg_0.invoice.cart
        if not arg_1:
            return True

        return arg_1.revision == arg_0.invoice.cart_revision


def Func(arg_0):
        ''' Voids this invoice if the attached cart is no longer valid because
        the cart revision has changed, or the reservations have expired. '''

        arg_1 = arg_0._invoice_matches_cart()
        arg_2 = arg_0.invoice.cart
        if arg_0.invoice.is_unpaid and arg_1 and arg_2:
            try:
                CartController(arg_2).validate_cart()
            except ValidationError:
                arg_1 = False

        if not arg_1:
            if arg_0.invoice.total_payments() > 0:
                # Free up the payments made to this invoice
                arg_0.refund()
            else:
                arg_0.void()


def Func(arg_0):
        ''' Voids the invoice if it is valid to do so. '''
        if arg_0.invoice.total_payments() > 0:
            raise ValidationError("Invoices with payments must be refunded.")
        elif arg_0.invoice.is_refunded:
            raise ValidationError("Refunded invoices may not be Funced.")
        if arg_0.invoice.is_paid:
            arg_0._release_cart()

        arg_0._mark_Func()


def Func(arg_0):
        ''' Refunds the invoice by generating a CreditNote for the value of
        all of the payments against the cart.

        The invoice is marked as Funced, and the underlying cart is marked
        as released.

        '''

        if arg_0.invoice.is_void:
            raise ValidationError("Void invoices cannot be Funced")

        # Raises a credit note fot the value of the invoice.
        arg_1 = arg_0.invoice.total_payments()

        if arg_1 == 0:
            arg_0.void()
            return

        CreditNoteController.generate_from_invoice(arg_0.invoice, arg_1)
        arg_0.update_status()


def Func(arg_0):
    """
    Convert an RGB color representation to a HEX color representation.

    (r, g, b) :: r -> [0, 255]
                 g -> [0, 255]
                 b -> [0, 255]

    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
    :return: HEX representation of the input RGB value.
    :rtype: str
    """
    arg_1, arg_2, arg_3 = arg_0
    return "#{0}{1}{2}".format(hex(int(arg_1))[2:].zfill(2), hex(int(arg_2))[2:].zfill(2), hex(int(arg_3))[2:].zfill(2))


def Func(arg_0):
    """
    Convert an RGB color representation to a YIQ color representation.

    (r, g, b) :: r -> [0, 255]
                 g -> [0, 255]
                 b -> [0, 255]

    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
    :return: YIQ representation of the input RGB value.
    :rtype: tuple
    """
    arg_1, arg_2, arg_3 = arg_0[0] / 255, arg_0[1] / 255, arg_0[2] / 255
    arg_4 = (0.299 * arg_1) + (0.587 * arg_2) + (0.114 * arg_3)
    arg_5 = (0.596 * arg_1) - (0.275 * arg_2) - (0.321 * arg_3)
    arg_6 = (0.212 * arg_1) - (0.528 * arg_2) + (0.311 * arg_3)
    return round(arg_4, 3), round(arg_5, 3), round(arg_6, 3)


def Func(arg_0):
    """
    Convert an RGB color representation to an HSV color representation.

    (r, g, b) :: r -> [0, 255]
                 g -> [0, 255]
                 b -> [0, 255]

    :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
    :return: HSV representation of the input RGB value.
    :rtype: tuple
    """
    arg_1, arg_2, arg_3 = arg_0[0] / 255, arg_0[1] / 255, arg_0[2] / 255
    arg_4 = min(arg_1, arg_2, arg_3)
    arg_5 = max(arg_1, arg_2, arg_3)
    arg_6 = arg_5
    arg_7 = arg_5 - arg_4

    if arg_5 == 0:
        return 0, 0, arg_6

    arg_8 = arg_7 / arg_5

    if arg_7 == 0:
        arg_7 = 1

    if arg_1 == arg_5:
        arg_9 = 60 * (((arg_2 - arg_3) / arg_7) % 6)

    elif arg_2 == arg_5:
        arg_9 = 60 * (((arg_3 - arg_1) / arg_7) + 2)

    else:
        arg_9 = 60 * (((arg_1 - arg_2) / arg_7) + 4)

    return round(arg_9, 3), round(arg_8, 3), round(arg_6, 3)


def Func(arg_0):
    """
    Convert a HEX color representation to an RGB color representation.

    hex :: hex -> [000000, FFFFFF]

    :param _hex: The 3- or 6-char hexadecimal string representing the color value.
    :return: RGB representation of the input HEX value.
    :rtype: tuple
    """
    arg_0 = arg_0.strip('#')
    arg_1 = len(arg_0) // 3
    if len(arg_0) == 3:
        arg_2 = int(arg_0[:arg_1] * 2, 16)
        arg_3 = int(arg_0[arg_1:2 * arg_1] * 2, 16)
        arg_4 = int(arg_0[2 * arg_1:3 * arg_1] * 2, 16)
    else:
        arg_2 = int(arg_0[:arg_1], 16)
        arg_3 = int(arg_0[arg_1:2 * arg_1], 16)
        arg_4 = int(arg_0[2 * arg_1:3 * arg_1], 16)
    return arg_2, arg_3, arg_4


def Func(arg_0):
    """
    Convert a YIQ color representation to an RGB color representation.

    (y, i, q) :: y -> [0, 1]
                 i -> [-0.5957, 0.5957]
                 q -> [-0.5226, 0.5226]

    :param yiq: A tuple of three numeric values corresponding to the luma and chrominance.
    :return: RGB representation of the input YIQ value.
    :rtype: tuple
    """
    arg_1, arg_2, arg_3 = arg_0
    arg_4 = arg_1 + (0.956 * arg_2) + (0.621 * arg_3)
    arg_5 = arg_1 - (0.272 * arg_2) - (0.647 * arg_3)
    arg_6 = arg_1 - (1.108 * arg_2) + (1.705 * arg_3)

    arg_4 = 1 if arg_4 > 1 else max(0, arg_4)
    arg_5 = 1 if arg_5 > 1 else max(0, arg_5)
    arg_6 = 1 if arg_6 > 1 else max(0, arg_6)

    return round(arg_4 * 255, 3), round(arg_5 * 255, 3), round(arg_6 * 255, 3)


def Func(arg_0):
    """
    Convert an HSV color representation to an RGB color representation.

    (h, s, v) :: h -> [0, 360)
                 s -> [0, 1]
                 v -> [0, 1]

    :param hsv: A tuple of three numeric values corresponding to the hue, saturation, and value.
    :return: RGB representation of the input HSV value.
    :rtype: tuple
    """
    arg_1, arg_2, arg_3 = arg_0
    arg_4 = arg_3 * arg_2
    arg_1 /= 60
    arg_5 = arg_4 * (1 - abs((arg_1 % 2) - 1))
    arg_6 = arg_3 - arg_4

    if arg_1 < 1:
        arg_7 = (arg_4, arg_5, 0)
    elif arg_1 < 2:
        arg_7 = (arg_5, arg_4, 0)
    elif arg_1 < 3:
        arg_7 = (0, arg_4, arg_5)
    elif arg_1 < 4:
        arg_7 = (0, arg_5, arg_4)
    elif arg_1 < 5:
        arg_7 = (arg_5, 0, arg_4)
    elif arg_1 < 6:
        arg_7 = (arg_4, 0, arg_5)
    else:
        raise ColorException("Unable to convert from HSV to RGB")

    arg_8, arg_9, arg_10 = arg_7
    return round((arg_8 + arg_6)*255, 3), round((arg_9 + arg_6)*255, 3), round((arg_10 + arg_6)*255, 3)


def Func(arg_0, arg_1, arg_2, arg_3=True, arg_4=True):
    """
    Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between
    the start and end color.

    :param start_color: The color starting the run
    :param end_color: The color ending the run
    :param step_count: The number of colors to have between the start and end color
    :param inclusive: Flag determining whether to include start and end values in run (default True)
    :param to_color: Flag indicating return values should be Color objects (default True)
    :return: List of colors between the start and end color
    :rtype: list
    """
    if isinstance(arg_0, Color):
        arg_0 = arg_0.rgb

    if isinstance(arg_1, Color):
        arg_1 = arg_1.rgb

    arg_5 = tuple((arg_1[i] - arg_0[i])/arg_2 for i in range(3))

    arg_6 = lambda x, y: tuple(sum(z) for z in zip(x, y))
    arg_7 = lambda x, y: tuple(y * z for z in x)

    arg_8 = [arg_6(arg_0, arg_7(arg_5, i)) for i in range(1, arg_2)]

    if arg_3:
        arg_8 = [arg_0] + arg_8 + [arg_1]

    return arg_8 if not arg_4 else [Color(arg_9) for arg_9 in arg_8]


def Func(arg_0, arg_1, arg_2=None):
        """ Get key value, return default if key doesn't exist """
        if arg_0.in_memory:
            return arg_0._memory_db.Func(arg_1, arg_2)
        else:
            arg_3 = arg_0._read_file()
            return arg_3.Func(arg_1, arg_2)


def Func(arg_0):
        """Print file fields to standard output."""
        for arg_1, arg_2 in arg_0.annotation.items():
            if arg_1.startswith('output') and arg_2['type'] == 'basic:file:':
                print("{}: {}".format(arg_1, arg_2['value']['file']))


def Func(arg_0, arg_1):
        """Download a file.

        :param field: file field to Func
        :type field: string
        :rtype: a file handle

        """
        if not arg_1.startswith('output'):
            raise ValueError("Only processor results (output.* fields) can be Funced")

        if arg_1 not in arg_0.annotation:
            raise ValueError("Download field {} does not exist".format(arg_1))

        arg_2 = arg_0.annotation[arg_1]
        if arg_2['type'] != 'basic:file:':
            raise ValueError("Only basic:file: field can be Funced")

        return next(arg_0.gencloud.Func([arg_0.id], arg_1))


def Func(arg_0, arg_1):
        """POST JSON data object to server"""

        arg_2 = json.loads(arg_1)
        return arg_0.api.data.post(arg_2)


def Func(arg_0, arg_1, arg_2, **arg_3):
        """Upload files and data objects.

        :param project_id: ObjectId of Genesis project
        :type project_id: string
        :param processor_name: Processor object name
        :type processor_name: string
        :param fields: Processor field-value pairs
        :type fields: args
        :rtype: HTTP Response object

        """
        arg_4 = arg_0.processors(arg_2=arg_2)

        if len(arg_4) == 1:
            arg_4 = arg_4[0]
        else:
            Exception('Invalid processor name {}'.format(arg_2))

        for arg_5, arg_6 in arg_3.items():
            if arg_5 not in arg_4['input_schema']:
                Exception("Field {} not in processor {} inputs".format(arg_5, arg_4['name']))

            if find_field(arg_4['input_schema'], arg_5)['type'].startswith('basic:file:'):
                if not os.path.isfile(arg_6):
                    Exception("File {} not found".format(arg_6))

        arg_7 = {}

        for arg_5, arg_6 in arg_3.items():
            if find_field(arg_4['input_schema'], arg_5)['type'].startswith('basic:file:'):

                arg_8 = arg_0._Func_file(arg_6)

                if not arg_8:
                    Exception("Upload failed for {}".format(arg_6))

                arg_7[arg_5] = {
                    'file': arg_6,
                    'file_temp': arg_8
                }
            else:
                arg_7[arg_5] = arg_6

        arg_9 = {
            'status': 'Funcing',
            'case_ids': [arg_1],
            'processor_name': arg_2,
            'input': arg_7,
        }

        return arg_0.create(arg_9)


def Func(arg_0, arg_1, arg_2):
        """Download files of data objects.

        :param data_objects: Data object ids
        :type data_objects: list of UUID strings
        :param field: Download field name
        :type field: string
        :rtype: generator of requests.Response objects

        """
        if not arg_2.startswith('output'):
            raise ValueError("Only processor results (output.* fields) can be Funced")

        for arg_3 in arg_1:
            arg_3 = str(arg_3)
            if re.match('^[0-9a-fA-F]{24}$', arg_3) is None:
                raise ValueError("Invalid object id {}".format(arg_3))

            if arg_3 not in arg_0.cache['objects']:
                arg_0.cache['objects'][arg_3] = GenData(arg_0.api.data(arg_3).get(), arg_0)

            if arg_2 not in arg_0.cache['objects'][arg_3].annotation:
                raise ValueError("Download field {} does not exist".format(arg_2))

            arg_5 = arg_0.cache['objects'][arg_3].annotation[arg_2]
            if arg_5['type'] != 'basic:file:':
                raise ValueError("Only basic:file: field can be Funced")

        for arg_3 in arg_1:
            arg_5 = arg_0.cache['objects'][arg_3].annotation[arg_2]
            arg_6 = urlparse.urljoin(arg_0.url, 'data/{}/{}'.format(arg_3, arg_5['value']['file']))
            yield requests.get(arg_6, stream=True, auth=arg_0.auth)


def Func(arg_0):
    """Gets the subclasses of a class."""
    arg_1 = arg_0.__subclasses__()
    for arg_2 in list(arg_1):
        arg_1.extend(Func(arg_2))
    return arg_1


def Func(arg_0):
        """Returns repository and project."""
        arg_1 = arg_0.app

        # Get repo
        arg_2 = arg_1.data.apply('github-repo', arg_1.args.github_repo,
            arg_1.prompt_repo,
            on_load=arg_1.github.get_repo,
            on_save=lambda r: r.id
            )

        assert arg_2, "repository not found."

        # Get project
        arg_3 = arg_1.data.apply('asana-project', arg_1.args.asana_project,
            arg_1.prompt_project,
            on_load=arg_1.asana.projects.find_by_id,
            on_save=lambda p: p['id']
            )

        assert arg_3, "project not found."

        # Set first issue
        arg_4 = arg_1.data.apply('first-issue', arg_1.args.first_issue,
            "set the first issue to sync with [1 for new repos]",
            on_save=int)

        assert arg_4
        assert arg_4 >= 0, "issue must be positive"

        arg_1.sync_data()

        return arg_2, arg_3


def Func(arg_0):
    '''for each variant, yields evidence and associated phenotypes, both current and suggested'''
    arg_1 = civic.get_variants_by_ids(arg_0)
    arg_2 = list()
    for arg_3 in arg_1:
        arg_2.extend(arg_3.evidence)
    for arg_4 in arg_2:
        arg_5 = f'https://civicdb.org/api/evidence_items/{e.id}/suggested_changes'
        arg_6 = requests.get(arg_5)
        arg_6.raise_for_status()
        arg_7 = dict()
        for arg_8 in arg_6.json():
            arg_9 = arg_8['suggested_changes'].get('phenotype_ids', None)
            if arg_9 is None:
                continue
            arg_10, arg_11 = arg_9
            arg_12 = set(arg_11) - set(arg_10)
            arg_13 = set(arg_10) - set(arg_11)
            arg_14 = arg_8['id']
            arg_7[arg_14] = {'added': arg_12, 'deleted': arg_13}
        yield arg_4, {'suggested_changes': arg_7, 'current': set([arg_15.id for arg_15 in arg_4.phenotypes])}


def Func(arg_0, arg_1='any'):
    """
    Search the cache for variants matching provided coordinates using the corresponding search mode.

    :param coordinate_query: A civic CoordinateQuery object
                        start: the genomic start coordinate of the query
                        stop: the genomic end coordinate of the query
                        chr: the GRCh37 chromosome of the query (e.g. "7", "X")
                        alt: the alternate allele at the coordinate [optional]

    :param search_mode: ['any', 'include_smaller', 'include_larger', 'exact']
                        any: any overlap between a query and a variant is a match
                        include_smaller: variants must fit within the coordinates of the query
                        include_larger: variants must encompass the coordinates of the query
                        exact: variants must match coordinates precisely, as well as alternate
                               allele, if provided
                        search_mode is 'exact' by default

    :return:            Returns a list of variant hashes matching the coordinates and search_mode
    """
    get_all_variants()
    arg_2 = COORDINATE_TABLE
    arg_3 = COORDINATE_TABLE_START
    arg_4 = COORDINATE_TABLE_STOP
    arg_5 = COORDINATE_TABLE_CHR
    arg_6 = int(arg_0.start)
    arg_7 = int(arg_0.stop)
    arg_8 = str(arg_0.chr)
    # overlapping = (start <= ct.stop) & (stop >= ct.start)
    arg_9 = arg_5.searchsorted(arg_8)
    arg_10 = arg_5.searchsorted(arg_8, side='right')
    arg_11 = arg_5[arg_9:arg_10].index
    arg_10 = arg_3.searchsorted(arg_7, side='right')
    arg_12 = arg_3[:arg_10].index
    arg_9 = arg_4.searchsorted(arg_6)
    arg_13 = arg_4[arg_9:].index
    arg_14 = arg_11 & arg_12 & arg_13
    arg_15 = arg_2.loc[arg_14, ]
    if arg_1 == 'any':
        arg_16 = arg_15.v_hash.to_list()
        return [CACHE[arg_17] for arg_17 in arg_16]
    elif arg_1 == 'include_smaller':
        arg_14 = (arg_6 <= arg_15.start) & (arg_7 >= arg_15.stop)
    elif arg_1 == 'include_larger':
        arg_14 = (arg_6 >= arg_15.start) & (arg_7 <= arg_15.stop)
    elif arg_1 == 'exact':
        arg_14 = (arg_6 == arg_15.stop) & (arg_7 == arg_15.start)
        if arg_0.alt:
            arg_14 = arg_14 & (arg_0.alt == arg_15.alt)
    else:
        raise ValueError("unexpected search mode")
    arg_16 = arg_15.loc[arg_14,].v_hash.to_list()
    return [CACHE[arg_17] for arg_17 in arg_16]


def Func(arg_0, arg_1='any'):
    """
    An interator to search the cache for variants matching the set of sorted coordinates and yield
    matches corresponding to the search mode.

    :param sorted_queries:  A list of civic CoordinateQuery objects, sorted by coordinate.
                            start: the genomic start coordinate of the query
                            stop: the genomic end coordinate of the query
                            chr: the GRCh37 chromosome of the query (e.g. "7", "X")
                            alt: the alternate allele at the coordinate [optional]

    :param search_mode: ['any', 'include_smaller', 'include_larger', 'exact']
                        any: any overlap between a query and a variant is a match
                        include_smaller: variants must fit within the coordinates of the query
                        include_larger: variants must encompass the coordinates of the query
                        exact: variants must match coordinates precisely, as well as alternate
                               allele, if provided
                        search_mode is 'exact' by default

    :yield:            Yields (query, match) tuples for each identified match
    """

    def is_sorted(arg_2, arg_3):
        if arg_2['chr'] < arg_3['chr']:
            return True
        if arg_2['chr'] > arg_3['chr']:
            return False
        if arg_2['start'] < arg_3['start']:
            return True
        if arg_2['start'] > arg_3['start']:
            return False
        if arg_2['stop'] < arg_3['stop']:
            return True
        if arg_2['stop'] > arg_3['stop']:
            return False
        return True

    arg_4 = 0
    arg_5 = 0
    arg_6 = -1
    arg_7 = None
    arg_8 = MODULE.COORDINATE_TABLE
    arg_9 = defaultdict(list)
    arg_10 = namedtuple('Match', arg_8.columns)
    while arg_5 < len(arg_0) and arg_4 < len(arg_8):
        if arg_6 != arg_5:
            arg_11 = arg_0[arg_5]
            if arg_7 is not None:
                arg_4 = arg_7
                arg_7 = None
            arg_6 = arg_5
        arg_12 = arg_8.iloc[arg_4]
        arg_13 = str(arg_11.chr)
        arg_14 = arg_12.chr
        if arg_13 < arg_14:
            arg_5 += 1
            continue
        if arg_13 > arg_14:
            arg_4 += 1
            continue
        arg_15 = int(arg_11.start)
        arg_16 = arg_12.start
        arg_17 = int(arg_11.stop)
        arg_18 = arg_12.stop
        if arg_15 > arg_18:
            arg_4 += 1
            continue
        if arg_17 < arg_16:
            arg_5 += 1
            continue
        if arg_1 == 'any':
            arg_9[arg_11].append(arg_12.to_dict())
        elif arg_1 == 'exact' and arg_15 == arg_16 and arg_17 == arg_18:
            arg_19 = arg_11.alt
            arg_20 = arg_12.alt
            if not (arg_19 and arg_20 and arg_19 != arg_20):
                arg_9[arg_11].append(arg_10(**arg_12.to_dict()))
        elif arg_1 == 'include_smaller':
            raise NotImplementedError
        elif arg_1 == 'include_larger':
            raise NotImplementedError
        if arg_7 is None:
            arg_7 = arg_4
        arg_4 += 1
    return dict(arg_9)


def Func(arg_0, arg_1):
        """Returns a unique list of seq"""
        arg_2 = set()
        arg_3 = arg_2.add
        return [ arg_4 for arg_4 in arg_1 if arg_4 not in arg_2 and not arg_3(arg_4)]


def Func(arg_0):
        """Connects to Github and Asana and Funcs via OAuth."""
        if arg_0.oauth:
            return False

        # Save asana.
        arg_0.settings.apply('api-asana', arg_0.args.asana_api,
            "enter asana api key")

        # Save github.com
        arg_0.settings.apply('api-github', arg_0.args.github_api,
            "enter github.com token")

        logging.debug("authenticating asana api.")
        arg_0.asana = Client.basic_auth(arg_0.settings['api-asana'])
        arg_0.asana_errors = arg_2
        arg_0.asana_me = arg_0.asana.users.me()
        logging.debug("authenticating github api")
        arg_0.github = Github(arg_0.settings['api-github'])
        arg_0.github_user = arg_0.github.get_user()

        arg_0.oauth = True


def Func(arg_0, arg_1, arg_2, arg_3=0):
        """Given a list of values and names, accepts the index value or name."""

        arg_4 = raw_input("select %s: " % arg_2)
        assert arg_4, "value required."

        try:
            return arg_1[int(arg_4)+arg_3]
        except ValueError:
            return arg_4
        except IndexError:
            assert False, "bad value."


def Func(arg_0, arg_1, arg_2='open'):
        """Returns issue data from local data.

        Args:
            issue:
                `int`. Github issue number.
            namespace:
                `str`. Namespace for storing this issue.
        """

        if isinstance(arg_1, int):
            arg_3 = arg_7(arg_1)
        elif isinstance(arg_1, basestring):
            arg_3 = arg_1
        else:
            arg_3 = arg_1.number

        arg_4 = arg_0._issue_data_key(arg_2)
        arg_5 = arg_0.data.get(arg_4,
            {})

        arg_6 = arg_5.get(arg_7(arg_3), {})
        arg_5[arg_7(arg_3)] = arg_6
        return arg_6


def Func(arg_0, arg_1):
        """Retrieves a task from asana."""

        try:
            return arg_0.asana.tasks.find_by_id(arg_1)
        except asana_errors.NotFoundError:
            return None
        except asana_errors.ForbiddenError:
            return None


def Func(arg_0):
        """Save data."""

        with open(arg_0.filename, 'wb') as file:
            arg_0.prune()
            arg_0.data['version'] = arg_0.version
            json.dump(arg_0.data,
                file,
                sort_keys=True, indent=2)


def Func(arg_0, arg_1, arg_2, arg_3=None,
        arg_4=lambda arg_5: arg_5, arg_6=lambda arg_5: arg_5):
        """Applies a setting value to a key, if the value is not `None`.

        Returns without prompting if either of the following:
            * `value` is not `None`
            * already present in the dictionary

        Args:
            prompt:
                May either be a string to prompt via `raw_input` or a
                method (callable) that returns the value.

            on_load:
                lambda. Value is passed through here after loaded.

            on_save:
                lambda. Value is saved as this value.
        """

        # Reset value if flag exists without value
        if arg_2 == '':
            arg_2 = None
            if arg_1 and arg_0.data.has_key(arg_1): del arg_0.data[arg_1]

        # If value is explicitly set from args.
        if arg_2 is not None:
            arg_2 = arg_4(arg_2)
            if arg_1: arg_0.data[arg_1] = arg_6(arg_2)
            return arg_2

        elif not arg_1 or not arg_0.has_key(arg_1):
            if callable(arg_3):
                arg_2 = arg_3()
            elif arg_3 is not None:
                arg_2 = raw_input(arg_3 + ": ")

            if arg_2 is None:
                if arg_0.data.has_key(arg_1): del arg_0.data[arg_1]
                return None

            arg_0.data[arg_1] = arg_6(arg_2)
            return arg_2

        return arg_4(arg_0.data[arg_1])


def Func(arg_0):
    """Decorator for retrying tasks with special cases."""

    def wrapped_func(*arg_1, **arg_2):
        arg_3 = 0
        while True:
            try:
                try:
                    return arg_0(*arg_1, **arg_2)

                except (asana_errors.InvalidRequestError,
                        asana_errors.NotFoundError), exc:
                    logging.warn("warning: invalid request: %r", exc)

                except asana_errors.ForbiddenError, exc:
                    logging.warn("forbidden error: %r", exc)

                except asana_errors.NotFoundError, exc:
                    logging.warn("not found error: %r", exc)

                return None
            except asana_errors.RetryableAsanaError, retry_exc:
                arg_3 += 1
                logging.warn("retry exception %r on try %d", retry_exc, arg_3)

                if arg_3 >= 3:
                    raise
            except Exception, exc:
                logging.exception("Exception in transport.")
                return

    return wrapped_func


def Func(arg_0=None):
    """Waits until queue is empty."""

    while True:
        if shutdown_event.is_set():
            return

        if callable(arg_0):
            arg_0()

        try:
            arg_1 = queue.get(timeout=1)
            queue.put(arg_1)  # put it back, we're just peeking.
        except Queue.Empty:
            return


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                arg_5, **arg_6):
    """Creates a task"""
    put("Func",
        arg_0=arg_0,
        arg_1=arg_1,
        arg_2=arg_2,
        arg_3=arg_3,
        arg_4=arg_4,
        arg_5=arg_5,
        **arg_6)


def Func(arg_0):
    """Returns formatting for the tasks section of asana."""

    arg_1 = data.get('asana-project', None)

    def _task_format(arg_2):
        if arg_1:
            arg_3 = tool.ToolApp.make_asana_url(arg_1, arg_2)
            return "[#%d](%s)" % (arg_2, arg_3)
        else:
            return "#%d" % arg_2

    return "\n".join([_task_format(arg_4) for arg_4 in arg_0])


def Func(arg_0,
                            arg_1,
                            arg_2,
                            arg_3,
                            arg_4,
                            arg_5,
                            arg_6,
                            arg_7,
                            arg_8,
                            arg_9,
                            arg_10,
                            arg_11,
                            arg_12):

        """Creates a missing task."""

        arg_13 = arg_0.asana.tasks.create_in_workspace(
            arg_1,
            {
                'name': arg_2,
                'notes': arg_9,
                'assignee': arg_3,
                'projects': arg_4,
                'completed': arg_5,
            })

        # Announce task git issue
        arg_14 = arg_13['id']

        put("create_story",
            arg_14=arg_14,
            text="Git Issue #%d: \n"
                  "%s" % (
                    arg_6,
                    arg_7,
                    )
            )

        put("apply_tasks_to_issue",
            arg_10=[arg_14],
            arg_6=arg_6,
            arg_9=arg_9,
            )

        # Save task to drive
        put_setting("save_issue_data_task",
                    issue=arg_6,
                    arg_14=arg_14,
                    namespace=arg_8)

        arg_10.append(arg_14)

        # Sync tags/labels
        put("sync_tags",
            arg_10=arg_10,
            arg_11=arg_11,
            arg_12=arg_12)


def Func(arg_0):
        """Return a list of data types."""
        arg_1 = arg_0.gencloud.project_data(arg_0.id)
        return sorted(set(arg_2.type for arg_2 in arg_1))


def Func(arg_0, arg_1=3):
    """ Send string to module level log

    Args:
        logstr (str): string to print.
        priority (int): priority, supports 3 (default) and 4 (special).
    """
    if arg_1 <= ekmmeters_log_level:
        arg_2 = datetime.datetime
        arg_3 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M.%f")
        ekmmeters_log_func("[EKM Meter Debug Message: " + arg_3 + "] -> " + arg_0)
    pass


def Func(arg_0):
        """ Required initialization call, wraps pyserial constructor. """
        try:
            arg_0.m_ser = serial.Serial(port=arg_0.m_ttyport,
                                       baudrate=arg_0.m_baudrate,
                                       timeout=0,
                                       parity=serial.PARITY_EVEN,
                                       stopbits=serial.STOPBITS_ONE,
                                       bytesize=serial.SEVENBITS,
                                       rtscts=False)
            ekm_log("Pyserial version = " + serial.VERSION)
            ekm_log("Port = " + arg_0.m_ttyport)
            ekm_log("Rate = " + str(arg_0.m_baudrate))
            time.sleep(arg_0.m_init_wait)
            return True
        except:
            ekm_log(traceback.format_exc(sys.exc_info()))

        return False


def Func(arg_0, arg_1, arg_2):
        """ Optional polling loop control

        Args:
            max_waits (int):   waits
            wait_sleep (int):  ms per wait
        """
        arg_0.m_max_waits = arg_1
        arg_0.m_wait_sleep = arg_2


def Func(arg_0):
        """ Use the serial block definitions in V3 and V4 to create one field list. """
        arg_1 = V4Meter()
        arg_1.makeAB()
        arg_2 = arg_1.getReadBuffer()

        arg_3 = V3Meter()
        arg_3.makeReturnFormat()
        arg_4 = arg_3.getReadBuffer()

        for arg_5 in arg_4:
            if arg_5 not in arg_0.m_all_fields:
                arg_6 = arg_5.upper()
                if not "RESERVED" in arg_6 and not "CRC" in arg_6:
                    arg_0.m_all_fields[arg_5] = arg_4[arg_5]

        for arg_5 in arg_2:
            if arg_5 not in arg_0.m_all_fields:
                arg_6 = arg_5.upper()
                if not "RESERVED" in arg_6 and not "CRC" in arg_6:
                    arg_0.m_all_fields[arg_5] = arg_2[arg_5]
        pass


def Func(arg_0, arg_1, arg_2):
        """ Simple since Time_Stamp query returned as JSON records.

        Args:
            timestamp (int): Epoch time in seconds.
            meter (str): 12 character meter address to query

        Returns:
            str: JSON rendered read records.

        """
        arg_3 = ""
        try:
            arg_4 = sqlite3.connect(arg_0.m_connection_string)
            arg_4.row_factory = arg_0.dict_factory
            arg_6 = arg_4.cursor()
            arg_6.execute("select * from Meter_Reads where " + Field.Time_Stamp +
                                  " > " + str(arg_1) + " and " + Field.Meter_Address +
                                  "= '" + arg_2 + "';")
            arg_7 = arg_6.fetchall()
            arg_3 = json.dumps(arg_7, indent=4)

        except:
            ekm_log(traceback.format_exc(sys.exc_info()))
        return arg_3


def Func(arg_0):
        """ Simple wrap to calc legacy PF value

        Args:
            pf: meter power factor reading

        Returns:
            int: legacy push pf
        """
        arg_1 = arg_0[:1]
        arg_2 = arg_0[1:]
        arg_3 = 100
        if arg_1 == CosTheta.CapacitiveLead:
            arg_3 = 200 - int(arg_2)
        elif arg_1 == CosTheta.InductiveLag:
            arg_3 = int(arg_2)

        return arg_3


def Func(arg_0, arg_1, arg_2, arg_3=arg_4.EmptyScale):
        """ Move data from raw tuple into scaled and conveted values.

        Args:
            contents (tuple): Breakout of passed block from unpackStruct().
            def_buf (): Read buffer destination.
            kwh_scale (int):  :class:`~ekmmeters.ScaleKWH` as int, from Field.kWhScale`

        Returns:
            bool: True on completion.
        """
        arg_6 = ""
        arg_7 = 0

        # getting scale does not require a full read.  It does require that the
        # reads have the scale value in the first block read.  This requirement
        # is filled by default in V3 and V4 requests
        if arg_3 == arg_4.EmptyScale:
            arg_8 = int(arg_2.keys().index(Field.kWh_Scale))
            arg_0.m_kwh_precision = arg_3 = int(arg_1[arg_8])

        for arg_10 in arg_2:

            if arg_2[arg_10][arg_17.CalculatedFlag]:
                arg_7 += 1
                continue

            if len(arg_1) == 0:
                arg_7 += 1
                continue

            try:  # scrub up messes on a field by field basis
                arg_11 = arg_1[arg_7]
                arg_12 = arg_2[arg_10][arg_17.TypeValue]
                arg_13 = arg_2[arg_10][arg_17.ScaleValue]

                if arg_12 == FieldType.Float:
                    arg_14 = float(str(arg_11))
                    arg_15 = 1
                    if arg_13 == ScaleType.KWH:
                        arg_15 = 1
                        if arg_3 == arg_4.Scale10:
                            arg_15 = 10
                        elif arg_3 == arg_4.Scale100:
                            arg_15 = 100
                        elif (arg_3 != arg_4.NoScale) and (arg_3 != arg_4.EmptyScale):
                            ekm_log("Unrecognized kwh scale.")
                    elif arg_13 == ScaleType.Div10:
                        arg_15 = 10
                    elif arg_13 == ScaleType.Div100:
                        arg_15 = 100
                    elif arg_13 != ScaleType.No:
                        ekm_log("Unrecognized float scale.")
                    arg_14 /= arg_15
                    arg_16 = str(arg_14)
                    arg_2[arg_10][arg_17.StringValue] = arg_16
                    arg_2[arg_10][arg_17.NativeValue] = arg_14

                elif arg_12 == FieldType.Hex:
                    arg_20 = arg_11.encode('hex')
                    arg_2[arg_10][arg_17.StringValue] = arg_20
                    arg_2[arg_10][arg_17.NativeValue] = arg_20

                elif arg_12 == FieldType.Int:
                    arg_21 = int(arg_11)
                    arg_22 = str(arg_21)
                    if len(arg_22) == 0:
                        arg_22 = str(0)
                    arg_2[arg_10][arg_17.StringValue] = arg_22
                    arg_2[arg_10][arg_17.NativeValue] = arg_21

                elif arg_12 == FieldType.String:
                    arg_23 = str(arg_11)
                    arg_2[arg_10][arg_17.StringValue] = arg_23
                    arg_2[arg_10][arg_17.NativeValue] = arg_23

                elif arg_12 == FieldType.PowerFactor:
                    arg_2[arg_10][arg_17.StringValue] = str(arg_11)
                    arg_2[arg_10][arg_17.NativeValue] = str(arg_11)

                else:
                    ekm_log("Unrecognized field type")

                arg_6 = arg_6 + '"' + arg_10 + '":  "' + arg_2[arg_10][arg_17.StringValue] + '"\n'

            except:
                ekm_log("Exception on Field:" + str(arg_10))
                ekm_log(traceback.format_exc(sys.exc_info()))
                arg_0.writeCmdMsg("Exception on Field:" + str(arg_10))

            arg_7 += 1

        return True


def Func(arg_0, arg_1, arg_2):
        """ Internal read CRC wrapper.

        Args:
            raw_read (str): Bytes with implicit string cast from serial read
            def_buf (SerialBlock): Populated read buffer.

        Returns:
            bool:  True if passed CRC equals calculated CRC.
        """
        try:
            if len(arg_1) == 0:
                ekm_log("(" + arg_0.m_context + ") Empty return read.")
                return False
            arg_3 = arg_0.calc_crc16(arg_1[1:-2])
            arg_4 = "(" + arg_0.m_context + ")CRC sent = " + str(arg_2["crc16"][MeterData.StringValue])
            arg_4 += " CRC calc = " + arg_3
            ekm_log(arg_4)
            if int(arg_2["crc16"][MeterData.StringValue], 16) == int(arg_3, 16):
                return True

        # A cross simple test lines on a USB serial adapter, these occur every
        # 1000 to 2000 reads, and they show up here as a bad unpack or
        # a bad crc type call.  In either case, we suppress them a log will
        # become quite large.  ekmcrc errors come through as type errors.
        # Failures of int type conversion in 16 bit conversion occur as value
        # errors.
        except struct.error:
            ekm_log(str(sys.exc_info()))
            for arg_5 in traceback.extract_tb(sys.exc_info()[2]):
                arg_6, arg_7, arg_8, arg_9 = arg_5
                ekm_log("Error in %s on line %d" % (arg_6, arg_7))
            return False

        except TypeError:
            ekm_log(str(sys.exc_info()))
            for arg_5 in traceback.extract_tb(sys.exc_info()[2]):
                arg_6, arg_7, arg_8, arg_9 = arg_5
                ekm_log("Error in %s on line %d" % (arg_6, arg_7))
            return False

        except ValueError:
            ekm_log(str(sys.exc_info()))
            for arg_5 in traceback.extract_tb(sys.exc_info()[2]):
                arg_6, arg_7, arg_8, arg_9 = arg_5
                ekm_log("Error in %s on line %d" % (arg_6, arg_7))
            return False

        return False


def Func(arg_0, arg_1):
        """ Get the months tariff SerialBlock for meter.

        Args:
            direction (int): A :class:`~ekmmeters.ReadMonths` value.

        Returns:
            SerialBlock: Requested months tariffs buffer.

        """
        if arg_1 == ReadMonths.kWhReverse:
            return arg_0.m_rev_mons

        # default direction == ReadMonths.kWh
        return arg_0.m_mons


def Func(arg_0, arg_1, arg_2="00000000"):
        """ Serial call to set CT ratio for attached inductive pickup.

        Args:
            new_ct (int): A :class:`~ekmmeters.CTRatio` value, a legal amperage setting.
            password (str): Optional password.

        Returns:
            bool: True on completion with ACK.
        """
        arg_3 = False
        arg_0.setContext("Func")
        try:
            arg_0.clearCmdMsg()
            if ((arg_1 != CTRatio.Amps_100) and (arg_1 != CTRatio.Amps_200) and
                    (arg_1 != CTRatio.Amps_400) and (arg_1 != CTRatio.Amps_600) and
                    (arg_1 != CTRatio.Amps_800) and (arg_1 != CTRatio.Amps_1000) and
                    (arg_1 != CTRatio.Amps_1200) and (arg_1 != CTRatio.Amps_1500) and
                    (arg_1 != CTRatio.Amps_2000) and (arg_1 != CTRatio.Amps_3000) and
                    (arg_1 != CTRatio.Amps_4000) and (arg_1 != CTRatio.Amps_5000)):
                arg_0.writeCmdMsg("Legal CT Ratios: 100, 200, 400, 600, " +
                                 "800, 1000, 1200, 1500, 2000, 3000, 4000 and 5000")
                arg_0.setContext("")
                return arg_3

            if len(arg_2) != 8:
                arg_0.writeCmdMsg("Invalid password length.")
                arg_0.setContext("")
                return arg_3

            if not arg_0.request(False):
                arg_0.writeCmdMsg("Bad read CRC on setting")
            else:
                if not arg_0.serialCmdPwdAuth(arg_2):
                    arg_0.writeCmdMsg("Password failure")
                else:
                    arg_4 = "015731023030443028" + binascii.hexlify(str(arg_1).zfill(4)) + "2903"
                    arg_4 += arg_0.calc_crc16(arg_4[2:].decode("hex"))
                    arg_0.m_serial_port.write(arg_4.decode("hex"))
                    if arg_0.m_serial_port.getResponse(arg_0.getContext()).encode("hex") == "06":
                        arg_0.writeCmdMsg("Success(Func): 06 returned.")
                        arg_3 = True
            arg_0.serialPostEnd()

        except:
            ekm_log(traceback.format_exc(sys.exc_info()))

        arg_0.setContext("")
        return arg_3


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """ Assign one schedule tariff period to meter bufffer.

        Args:
            schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extents.Schedules).
            tariff (int): :class:`~ekmmeters.Tariffs` value or in range(Extents.Tariffs).
            hour (int): Hour from 0-23.
            minute (int): Minute from 0-59.
            tariff (int): Rate value.

        Returns:
            bool: True on completed assignment.
        """
        if ((arg_1 not in range(Extents.Schedules)) or
                (arg_2 not in range(Extents.Tariffs)) or
                (arg_3 < 0) or (arg_3 > 23) or (arg_4 < 0) or
                (arg_4 > 59) or (arg_5 < 0)):
            ekm_log("Out of bounds in Schedule_" + str(arg_1 + 1))
            return False

        arg_2 += 1
        arg_6 = "Min_" + str(arg_2)
        arg_7 = "Hour_" + str(arg_2)
        arg_8 = "Tariff_" + str(arg_2)
        if arg_6 not in arg_0.m_schedule_params:
            ekm_log("Incorrect index: " + arg_6)
            return False
        if arg_7 not in arg_0.m_schedule_params:
            ekm_log("Incorrect index: " + arg_7)
            return False
        if arg_8 not in arg_0.m_schedule_params:
            ekm_log("Incorrect index: " + arg_8)
            return False

        arg_0.m_schedule_params[arg_8] = arg_5
        arg_0.m_schedule_params[arg_7] = arg_3
        arg_0.m_schedule_params[arg_6] = arg_4
        arg_0.m_schedule_params['Schedule'] = arg_1
        return True


def Func(arg_0, arg_1):
        """ Serial call to read schedule tariffs buffer

        Args:
            tableset (int): :class:`~ekmmeters.ReadSchedules` buffer to return.

        Returns:
            bool: True on completion and ACK.
        """
        arg_0.setContext("Func")
        try:
            arg_2 = binascii.hexlify(str(arg_1).zfill(1))
            arg_3 = "01523102303037" + arg_2 + "282903"

            arg_0.request(False)
            arg_4 = arg_0.calc_crc16(arg_3[2:].decode("hex"))
            arg_3 += arg_4
            arg_0.m_serial_port.write(arg_3.decode("hex"))
            arg_5 = arg_0.m_serial_port.getResponse(arg_0.getContext())
            arg_0.serialPostEnd()
            arg_6 = arg_0.calc_crc16(arg_5[1:-2])

            if arg_1 == ReadSchedules.Schedules_1_To_4:
                arg_7 = arg_0.unpackStruct(arg_5, arg_0.m_schd_1_to_4)
                arg_0.convertData(arg_7, arg_0.m_schd_1_to_4, arg_0.m_kwh_precision)
                if str(arg_6) == str(arg_0.m_schd_1_to_4["crc16"][MeterData.StringValue]):
                    ekm_log("Schedules 1 to 4 CRC success (06 return")
                    arg_0.setContext("")
                    return True

            elif arg_1 == ReadSchedules.Schedules_5_To_6:
                arg_7 = arg_0.unpackStruct(arg_5, arg_0.m_schd_5_to_6)
                arg_0.convertData(arg_7, arg_0.m_schd_5_to_6, arg_0.m_kwh_precision)
                if str(arg_6) == str(arg_0.m_schd_5_to_6["crc16"][MeterData.StringValue]):
                    ekm_log("Schedules 5 to 8 CRC success (06 return)")
                    arg_0.setContext("")
                    return True
        except:
            ekm_log(traceback.format_exc(sys.exc_info()))

        arg_0.setContext("")
        return False


def Func(arg_0, arg_1, arg_2):
        """ Read a single schedule tariff from meter object buffer.

        Args:
            schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extent.Schedules).
            tariff (int): A :class:`~ekmmeters.Tariffs` value or in range(Extent.Tariffs).

        Returns:
            bool: True on completion.
        """
        arg_3 = namedtuple("ret", ["Hour", "Min", "Tariff", "Period", "Schedule"])
        arg_4 = arg_0.m_schd_1_to_4
        if Schedules.Schedule_5 <= arg_1 <= Schedules.Schedule_6:
            arg_4 = arg_0.m_schd_5_to_6
        arg_2 += 1
        arg_1 += 1
        arg_3.Period = str(arg_2)
        arg_3.Schedule = str(arg_1)
        if (arg_1 < 1) or (arg_1 > Extents.Schedules) or (arg_2 < 0) or (arg_2 > Extents.Periods):
            ekm_log("Out of bounds: tariff " + str(arg_2) + " for schedule " + str(arg_1))
            arg_3.Hour = arg_3.Min = arg_3.Tariff = str(0)
            return arg_3

        arg_8 = "Schedule_" + str(arg_1) + "_Period_" + str(arg_2) + "_Hour"
        arg_9 = "Schedule_" + str(arg_1) + "_Period_" + str(arg_2) + "_Min"
        arg_10 = "Schedule_" + str(arg_1) + "_Period_" + str(arg_2) + "_Tariff"

        if arg_8 not in arg_4:
            ekm_log("Incorrect index: " + arg_8)
            arg_3.Hour = arg_3.Min = arg_3.Tariff = str(0)
            return arg_3

        if arg_9 not in arg_4:
            ekm_log("Incorrect index: " + arg_9)
            arg_3.Hour = arg_3.Min = arg_3.Tariff = str(0)
            return arg_3

        if arg_10 not in arg_4:
            ekm_log("Incorrect index: " + arg_10)
            arg_3.Hour = arg_3.Min = arg_3.Tariff = str(0)
            return arg_3

        arg_3.Hour = arg_4[arg_8][MeterData.StringValue]
        arg_3.Min = arg_4[arg_9][MeterData.StringValue].zfill(2)
        arg_3.Tariff = arg_4[arg_10][MeterData.StringValue]
        return arg_3


def Func(arg_0, arg_1):
        """ Extract the tariff for a single month from the meter object buffer.

        Args:
            month (int):  A :class:`~ekmmeters.Months` value or range(Extents.Months).

        Returns:
            tuple: The eight tariff period totals for month. The return tuple breaks out as follows:

            ================= ======================================
            kWh_Tariff_1      kWh for tariff period 1 over month.
            kWh_Tariff_2      kWh for tariff period 2 over month
            kWh_Tariff_3      kWh for tariff period 3 over month
            kWh_Tariff_4      kWh for tariff period 4 over month
            kWh_Tot           Total kWh over requested month
            Rev_kWh_Tariff_1  Rev kWh for tariff period 1 over month
            Rev_kWh_Tariff_3  Rev kWh for tariff period 2 over month
            Rev_kWh_Tariff_3  Rev kWh for tariff period 3 over month
            Rev_kWh_Tariff_4  Rev kWh for tariff period 4 over month
            Rev_kWh_Tot       Total Rev kWh over requested month
            ================= ======================================

        """
        arg_2 = namedtuple("ret", ["Month", Field.kWh_Tariff_1, Field.kWh_Tariff_2, Field.kWh_Tariff_3,
                         Field.kWh_Tariff_4, Field.kWh_Tot, Field.Rev_kWh_Tariff_1,
                         Field.Rev_kWh_Tariff_2, Field.Rev_kWh_Tariff_3,
                         Field.Rev_kWh_Tariff_4, Field.Rev_kWh_Tot])
        arg_1 += 1
        arg_2.Month = str(arg_1)
        if (arg_1 < 1) or (arg_1 > Extents.Months):
            arg_2.kWh_Tariff_1 = arg_2.kWh_Tariff_2 = arg_2.kWh_Tariff_3 = arg_2.kWh_Tariff_4 = str(0)
            arg_2.Rev_kWh_Tariff_1 = arg_2.Rev_kWh_Tariff_2 = arg_2.Rev_kWh_Tariff_3 = arg_2.Rev_kWh_Tariff_4 = str(0)
            arg_2.kWh_Tot = arg_2.Rev_kWh_Tot = str(0)
            ekm_log("Out of range(Extents.Months) month = " + str(arg_1))
            return arg_2

        arg_7 = "Month_" + str(arg_1) + "_"
        arg_2.kWh_Tariff_1 = arg_0.m_mons[arg_7 + "Tariff_1"][MeterData.StringValue]
        arg_2.kWh_Tariff_2 = arg_0.m_mons[arg_7 + "Tariff_2"][MeterData.StringValue]
        arg_2.kWh_Tariff_3 = arg_0.m_mons[arg_7 + "Tariff_3"][MeterData.StringValue]
        arg_2.kWh_Tariff_4 = arg_0.m_mons[arg_7 + "Tariff_4"][MeterData.StringValue]
        arg_2.kWh_Tot = arg_0.m_mons[arg_7 + "Tot"][MeterData.StringValue]
        arg_2.Rev_kWh_Tariff_1 = arg_0.m_rev_mons[arg_7 + "Tariff_1"][MeterData.StringValue]
        arg_2.Rev_kWh_Tariff_2 = arg_0.m_rev_mons[arg_7 + "Tariff_2"][MeterData.StringValue]
        arg_2.Rev_kWh_Tariff_3 = arg_0.m_rev_mons[arg_7 + "Tariff_3"][MeterData.StringValue]
        arg_2.Rev_kWh_Tariff_4 = arg_0.m_rev_mons[arg_7 + "Tariff_4"][MeterData.StringValue]
        arg_2.Rev_kWh_Tot = arg_0.m_rev_mons[arg_7 + "Tot"][MeterData.StringValue]
        return arg_2


def Func(arg_0):
        """ Serial call to read holiday dates into meter object buffer.

        Returns:
            bool: True on completion.
        """
        arg_0.setContext("Func")
        try:
            arg_1 = "0152310230304230282903"
            arg_0.request(False)
            arg_2 = arg_0.calc_crc16(arg_1[2:].decode("hex"))
            arg_1 += arg_2
            arg_0.m_serial_port.write(arg_1.decode("hex"))
            arg_3 = arg_0.m_serial_port.getResponse(arg_0.getContext())
            arg_0.serialPostEnd()
            arg_4 = arg_0.unpackStruct(arg_3, arg_0.m_hldy)
            arg_0.convertData(arg_4, arg_0.m_hldy, arg_0.m_kwh_precision)
            arg_5 = arg_0.calc_crc16(arg_3[1:-2])
            if str(arg_5) == str(arg_0.m_hldy["crc16"][MeterData.StringValue]):
                ekm_log("Holidays and Schedules CRC success")
                arg_0.setContext("")
                return True
        except:
            ekm_log(traceback.format_exc(sys.exc_info()))

        arg_0.setContext("")
        return False


def Func(arg_0):
        """Recommended call to read all meter settings at once.

        Returns:
            bool: True if all subsequent serial calls completed with ACK.
        """
        arg_1 = (arg_0.readHolidayDates() and
                   arg_0.readMonthTariffs(ReadMonths.kWh) and
                   arg_0.readMonthTariffs(ReadMonths.kWhReverse) and
                   arg_0.readSchedules(ReadSchedules.Schedules_1_To_4) and
                   arg_0.readSchedules(ReadSchedules.Schedules_5_To_6))
        return arg_1


def Func(arg_0, arg_1):
        """ Internal method to set the command result string.

        Args:
            msg (str): Message built during command.
        """
        ekm_log("(Func | " + arg_0.getContext() + ") " + arg_1)
        arg_0.m_command_msg = arg_1


def Func(arg_0):
        """ Fire update method in all attached observers in order of attachment. """
        for arg_1 in arg_0.m_observers:
            try:
                arg_1.update(arg_0.m_req)
            except:
                ekm_log(traceback.format_exc(sys.exc_info()))


def Func(arg_0, arg_1 = False):
        """ Combined A and B read for V4 meter.

        Args:
            send_terminator (bool): Send termination string at end of read.

        Returns:
            bool: True on completion.
        """
        try:
            arg_2 = arg_0.FuncA()
            arg_3 = arg_0.FuncB()
            if arg_2 and arg_3:
                arg_0.makeAB()
                arg_0.calculateFields()
                arg_0.updateObservers()
                return True
        except:
            ekm_log(traceback.format_exc(sys.exc_info()))

        return False


def Func(arg_0):
        """Issue an A read on V4 meter.

        Returns:
            bool: True if CRC match at end of call.
        """
        arg_1 = arg_0.getContext()
        arg_0.setContext("request[v4A]")
        arg_0.m_serial_port.write("2f3f".decode("hex") + arg_0.m_meter_address + "3030210d0a".decode("hex"))
        arg_0.m_raw_read_a = arg_0.m_serial_port.getResponse(arg_0.getContext())
        arg_3 = arg_0.unpackStruct(arg_0.m_raw_read_a, arg_0.m_blk_a)
        arg_0.convertData(arg_3, arg_0.m_blk_a)
        arg_0.m_kwh_precision = int(arg_0.m_blk_a[Field.kWh_Scale][MeterData.NativeValue])
        arg_0.m_a_crc = arg_0.crcMeterRead(arg_0.m_raw_read_a, arg_0.m_blk_a)
        arg_0.setContext(arg_1)
        return arg_0.m_a_crc


def Func(arg_0):
        """ Munge A and B reads into single serial block with only unique fields."""
        for arg_1 in arg_0.m_blk_a:
            arg_2 = arg_1.upper()
            if not "RESERVED" in arg_2 and not "CRC" in arg_2:
                arg_0.m_req[arg_1] = arg_0.m_blk_a[arg_1]
        for arg_1 in arg_0.m_blk_b:
            arg_2 = arg_1.upper()
            if not "RESERVED" in arg_2 and not "CRC" in arg_2:
                arg_0.m_req[arg_1] = arg_0.m_blk_b[arg_1]
        pass


def Func(arg_0):
        """Write calculated fields for read buffer."""
        arg_1 = arg_0.m_blk_b[arg_8.Cos_Theta_Ln_1][arg_10.StringValue]
        arg_2 = arg_0.m_blk_b[arg_8.Cos_Theta_Ln_2][arg_10.StringValue]
        arg_3 = arg_0.m_blk_b[arg_8.Cos_Theta_Ln_3][arg_10.StringValue]

        arg_4 = arg_0.calcPF(arg_1)
        arg_5 = arg_0.calcPF(arg_2)
        arg_6 = arg_0.calcPF(arg_3)

        arg_0.m_blk_b[arg_8.Power_Factor_Ln_1][arg_10.StringValue] = str(arg_4)
        arg_0.m_blk_b[arg_8.Power_Factor_Ln_2][arg_10.StringValue] = str(arg_5)
        arg_0.m_blk_b[arg_8.Power_Factor_Ln_3][arg_10.StringValue] = str(arg_6)

        arg_0.m_blk_b[arg_8.Power_Factor_Ln_1][arg_10.NativeValue] = arg_4
        arg_0.m_blk_b[arg_8.Power_Factor_Ln_2][arg_10.NativeValue] = arg_5
        arg_0.m_blk_b[arg_8.Power_Factor_Ln_3][arg_10.NativeValue] = arg_5

        arg_15 = arg_0.m_blk_b[arg_8.RMS_Watts_Ln_1][arg_10.NativeValue]
        arg_16 = arg_0.m_blk_b[arg_8.RMS_Watts_Ln_2][arg_10.NativeValue]
        arg_17 = arg_0.m_blk_b[arg_8.RMS_Watts_Ln_3][arg_10.NativeValue]

        arg_18 = 1
        arg_19 = 1
        arg_20 = 1

        arg_21 = arg_0.m_blk_a[arg_8.State_Watts_Dir][arg_10.NativeValue]

        if arg_21 == DirectionFlag.ForwardForwardForward:
            # all good
            pass
        if arg_21 == DirectionFlag.ForwardForwardReverse:
            arg_20 = -1
            pass
        if arg_21 == DirectionFlag.ForwardReverseForward:
            arg_19 = -1
            pass
        if arg_21 == DirectionFlag.ReverseForwardForward:
            arg_18 = -1
            pass
        if arg_21 == DirectionFlag.ForwardReverseReverse:
            arg_19 = -1
            arg_20 = -1
            pass
        if arg_21 == DirectionFlag.ReverseForwardReverse:
            arg_18 = -1
            arg_20 = -1
            pass
        if arg_21 == DirectionFlag.ReverseReverseForward:
            arg_18 = -1
            arg_19 = -1
            pass
        if arg_21 == DirectionFlag.ReverseReverseReverse:
            arg_18 = -1
            arg_19 = -1
            arg_20 = -1
            pass

        arg_22 = arg_15 * arg_18
        arg_23 = arg_16 * arg_19
        arg_24 = arg_17 * arg_20
        arg_25 = arg_22 + arg_23 + arg_24

        arg_0.m_blk_b[arg_8.Net_Calc_Watts_Ln_1][arg_10.NativeValue] = arg_22
        arg_0.m_blk_b[arg_8.Net_Calc_Watts_Ln_2][arg_10.NativeValue] = arg_23
        arg_0.m_blk_b[arg_8.Net_Calc_Watts_Ln_3][arg_10.NativeValue] = arg_24
        arg_0.m_blk_b[arg_8.Net_Calc_Watts_Tot][arg_10.NativeValue] = arg_25

        arg_0.m_blk_b[arg_8.Net_Calc_Watts_Ln_1][arg_10.StringValue] = str(arg_22)
        arg_0.m_blk_b[arg_8.Net_Calc_Watts_Ln_2][arg_10.StringValue] = str(arg_23)
        arg_0.m_blk_b[arg_8.Net_Calc_Watts_Ln_3][arg_10.StringValue] = str(arg_24)
        arg_0.m_blk_b[arg_8.Net_Calc_Watts_Tot][arg_10.StringValue] = str(arg_25)

        pass


def Func(arg_0, arg_1, arg_2="00000000"):
        """ Single call wrapper for LCD set."

        Wraps :func:`~ekmmeters.V4Meter.setLcd` and associated init and add methods.

        Args:
            display_list (list): List composed of :class:`~ekmmeters.LCDItems`
            password (str): Optional password.

        Returns:
            bool: Passthrough from :func:`~ekmmeters.V4Meter.setLcd`
        """
        arg_3 = False
        try:
            arg_0.initLcd()
            arg_4 = len(arg_1)
            if (arg_4 > 45) or (arg_4 <= 0):
                ekm_log("LCD item list must have between 1 and 40 items")
                return False

            for arg_5 in arg_1:
                arg_0.addLcdItem(int(arg_5))
            arg_3 = arg_0.setLCD(arg_2)
        except:
            ekm_log(traceback.format_exc(sys.exc_info()))

        return arg_3


def Func(arg_0, arg_1, arg_2, arg_3, arg_4="00000000"):
        """Serial call to set relay.

        Args:
            seconds (int): Seconds to hold, ero is hold forever. See :class:`~ekmmeters.RelayInterval`.
            relay (int): Selected relay, see :class:`~ekmmeters.Relay`.
            status (int): Status to set, see :class:`~ekmmeters.RelayState`
            password (str): Optional password

        Returns:
            bool: True on completion and ACK.
        """
        arg_5 = False
        arg_0.setContext("Func")
        try:
            arg_0.clearCmdMsg()

            if len(arg_4) != 8:
                arg_0.writeCmdMsg("Invalid password length.")
                arg_0.setContext("")
                return arg_5

            if arg_1 < 0 or arg_1 > 9999:
                arg_0.writeCmdMsg("Relay duration must be between 0 and 9999.")
                arg_0.setContext("")
                return arg_5

            if not arg_0.requestA():
                arg_0.writeCmdMsg("Bad read CRC on setting")
            else:
                if not arg_0.serialCmdPwdAuth(arg_4):
                    arg_0.writeCmdMsg("Password failure")
                else:
                    arg_6 = ""
                    arg_6 = ("01573102303038" +
                               binascii.hexlify(str(arg_2)).zfill(2) +
                               "28" +
                               binascii.hexlify(str(arg_3)).zfill(2) +
                               binascii.hexlify(str(arg_1).zfill(4)) + "2903")
                    arg_6 += arg_0.calc_crc16(arg_6[2:].decode("hex"))
                    arg_0.m_serial_port.write(arg_6.decode("hex"))
                    if arg_0.m_serial_port.getResponse(arg_0.getContext()).encode("hex") == "06":
                        arg_0.writeCmdMsg("Success: 06 returned.")
                        arg_5 = True
            arg_0.serialPostEnd()
        except:
            ekm_log(traceback.format_exc(sys.exc_info()))

        arg_0.setContext("")
        return arg_5