text:
push!( LOAD_PATH, "../" )
import InformationInequalities  # Import the module to  have access to functions

"""
plotEntropyTree(S,...)
```julia-repl
julia>plotEntropyTree("H(X,Y)+1.2 H(X)+7H(X1,X2,X3)")

julia>plotEntropyTree("H(X,Y)+1H(X1,X2)+3H(X1,X2,X3)",curves=:false,nodecolor=:gold,edgecolor=:gray,nodeshape=:rect,nodesize=0.15)
```
"""
function plotEntropyTree(S;kwargs...)
p=plot(Meta.parse(S);kwargs...)
return p
end

"""
plotIE(S,...)
```julia-repl
julia>PlotIE("H(X,Y)+7H(X1,X2,X3)")

julia>plotIE("I(X;Y)+2I(X;Y|Z)",curves=:false)
```
"""
function plotIE(S;kwargs...)
Z= LinearInformationExpressionToCanonical(S)
p=plot(Meta.parse(Z);kwargs...)
return p
end

"""
PlotInformationExpression(S,...)
```julia-repl
julia>PlotInformationExpression("H(X,Y)+7H(X1,X2,X3)")

julia>PlotInformationExpression("I(X;Y)+2I(X;Y|Z)",curves=:false)
```
"""
function plotInformationExpression(S;kwargs...)
Z= LinearInformationExpressionToCanonical(S)
p=plot(Meta.parse(Z);kwargs...)
return p
end


text:
struct CPU <: AbstractDevice
end

struct GPU <: AbstractDevice
    id::Int
end

"""
Check if the argument is of type CuArray. Doesn't require CuArrays.jl to be loaded
"""
is_cuarray(x) = startswith(string(typeof(x)), "CuArray")

# function has_cuda_inputs(tape::Tape)
#     res = false
#     for op in tape
#         if op isa Input && op.val isa CuArray
#             res = true
#             break
#         end
#     end
#     return res
# end

# currently GPU's ID is just a placeholder
guess_device(args) = any(is_cuarray, args) ? GPU(1) : CPU()

# also see cuda.jl
to_device(device::CPU, x) = x

# also see cuda.jl
device_op(device::CPU, op) = op

deviceof(x::TAny) = x.device
deviceof(x) = is_cuarray(x) ? GPU(1) : CPU()

ext: jl


text:
function theme_light()
    Theme(
        textcolor = :gray50,
        Axis = (
            backgroundcolor = :transparent,
            xgridcolor = (:black, 0.07),
            ygridcolor = (:black, 0.07),
            leftspinevisible = false,
            rightspinevisible = false,
            bottomspinevisible = false,
            topspinevisible = false,
            xminorticksvisible = false,
            yminorticksvisible = false,
            xticksvisible = false,
            yticksvisible = false,
            xlabelpadding = 3,
            ylabelpadding = 3
        ),
        Legend = (
            framevisible = false,
            padding = (0, 0, 0, 0),
        ),
        Axis3 = (
            xgridcolor = (:black, 0.07),
            ygridcolor = (:black, 0.07),
            zgridcolor = (:black, 0.07),
            xspinesvisible = false,
            yspinesvisible = false,
            zspinesvisible = false,
            xticksvisible = false,
            yticksvisible = false,
            zticksvisible = false,
        ),
        Colorbar = (
            ticksvisible = false,
            spinewidth = 0,
            ticklabelpad = 5,
        )
    )
end


text:
function utility_revenue_change(bill::Dict, DS::Tariff, transmission::Float64 = 12.07)
        utility_change = Dict{Any,Any}()

		if !("grid_energy_savings" in keys(bill["savings"]))
			grid_energy_savings = bill["savings"]["savings_energy_cost_peak"]  + bill["savings"]["savings_energy_cost_valley"] + bill["savings"]["savings_energy_cost_night"]
		    demand_charges = bill["savings"]["savings_demand_charge_peak"]  + bill["savings"]["savings_demand_charge_valley"] + bill["savings"]["savings_demand_charge_night"]
		else
			grid_energy_savings = bill["savings"]["grid_energy_savings"]
			demand_charges = bill["savings"]["demand_charges"]
		end

		utility_change["consumer_savings"] = user_savings = -1*( grid_energy_savings + demand_charges + bill["savings"]["street_light"])
        utility_change["withdrawal_charges"] = withdrawn_charges = bill["withdrawn_energy_cost"]
        #Energy Change
        utility_change["energy_night"] = energy_night = (transmission + SD.e_cost[3][2])*(bill["Balance"]["utility_balance"]["consumer_energy_night"] - bill["Balance"]["utility_balance"]["grid_energy_night"])
        utility_change["energy_valley"] = energy_valley = (transmission + SD.e_cost[2][2])*(bill["Balance"]["utility_balance"]["consumer_energy_valley"] - bill["Balance"]["utility_balance"]["grid_energy_valley"])
        utility_change["energy_peak"] = energy_peak = (transmission + SD.e_cost[1][2])*(bill["Balance"]["utility_balance"]["consumer_energy_peak"] - bill["Balance"]["utility_balance"]["grid_energy_peak"])
        #Demand Change
        utility_change["demand_night"] = demand_night = (SD.p_cost[3][2])*(bill["Balance"]["utility_balance"]["consumer_demand_night"] - bill["Balance"]["utility_balance"]["grid_demand_night"])
        utility_change["demand_valley"] = demand_valley = (SD.p_cost[2][2])*(bill["Balance"]["utility_balance"]["consumer_demand_valley"] - bill["Balance"]["utility_balance"]["grid_demand_valley"])
        utility_change["demand_peak"] = demand_peak = (SD.p_cost[1][2])*(bill["Balance"]["utility_balance"]["consumer_demand_peak"] - bill["Balance"]["utility_balance"]["grid_demand_peak"])
        #Totals
        utility_change["losses"] = losses = (user_savings + withdrawn_charges + energy_night + energy_valley + energy_peak + demand_night + demand_valley + demand_peak)
        bill["utility_change"] = utility_change
end

function PV_losses(consumer_input::Consumer, system::PVSystem, SD::Tariff; tariff_increase=true)

    consumer = deepcopy(consumer_input)

	utility_tariff = deepcopy(SD)

	total_losses = Array{Float64,2}(undef,12,consumer.decision_timeframe)

    for y in 1:consumer.decision_timeframe

        ebalance = annual_energy_balance(consumer, system, print_output=false);

        for m in 1:12

            bill = monthly_bill(ebalance[m], consumer, SD = utility_tariff, print_output=false)

            total_losses[m,y] = bill["utility_change"]["losses"]

        end

        tariff_increase ? increase_tariff!(consumer) : true
		tariff_increase ? increase_tariff!(utility_tariff) : true

    end

    return total_losses

end

function utility_revenue(consumer_input::Consumer, system::PVSystem, SD::Tariff; tariff_increase=true)

    consumer = deepcopy(consumer_input)

	utility_tariff = deepcopy(SD)

	total_revenue = Array{Float64,2}(undef,12,consumer.decision_timeframe)

    for y in 1:consumer.decision_timeframe

        ebalance = annual_energy_balance(consumer, system, print_output=false);

        for m in 1:12

            bill = monthly_bill(ebalance[m], consumer, SD = utility_tariff, print_output=false)

            total_revenue[m,y] = bill["counterfactual_cost"]

        end

        tariff_increase ? increase_tariff!(consumer) : true
		tariff_increase ? increase_tariff!(utility_tariff) : true

    end

    return total_revenue

end

max_stars_repo_name: arnavgautam/PVCR

max_issues_repo_name: arnavgautam/PVCR

max_forks_repo_name: arnavgautam/PVCR


text:
module HusimiFunctions

using Base.Threads
using StaticArrays

export SVector

include("utils.jl")
include("husimi.jl")
include("graphene.jl")

export Graphene

end


text:
begin
    tab(n::Int) = begin
            " " ^ n
        end
    #= none:3 =# Base.@kwdef struct Color
            literal::Symbol = :light_blue
            type::Symbol = :light_green
            string::Symbol = :yellow
            comment::Symbol = :light_black
            kw::Symbol = :light_magenta
            fn::Symbol = :light_blue
        end
    #= none:12 =# Base.@kwdef mutable struct PrintState
            line_indent::Int = 0
            content_indent::Int = line_indent
            color::Symbol = :normal
        end
    #= none:18 =# Core.@doc "    sprint_expr(ex; context=nothing)\n\nPrint given expression to `String`, see also [`print_expr`](@ref).\n" function sprint_expr(ex; context = nothing)
            buf = IOBuffer()
            if context === nothing
                print_expr(buf, ex)
            else
                print_expr(IOContext(buf, context), ex)
            end
            return String(take!(buf))
        end
    #= none:33 =# Core.@doc "    print_expr([io::IO], ex)\n\nPrint a given expression. `ex` can be a `Expr` or a syntax type `JLExpr`.\n" print_expr(ex) = begin
                print_expr(stdout, ex)
            end
    print_expr(io::IO, ex) = begin
            print_expr(io, ex, PrintState())
        end
    print_expr(io::IO, ex, p::PrintState) = begin
            print_expr(io, ex, p, Color())
        end
    #= none:42 =# @deprecate print_ast(ex) print_expr(ex)
    #= none:43 =# @deprecate print_ast(io, ex) print_expr(io, ex)
    const uni_ops = Set{Symbol}([:+, :-, :!, :¬, :~, :<:, :>:, :√, :∛, :∜])
    const expr_infix_wide = Set{Symbol}([:(=), :+=, :-=, :*=, :/=, :\=, :^=, :&=, :|=, :÷=, :%=, :>>>=, :>>=, :<<=, :.=, :.+=, :.-=, :.*=, :./=, :.\=, :.^=, :.&=, :.|=, :.÷=, :.%=, :.>>>=, :.>>=, :.<<=, :&&, :||, :<:, :$=, :⊻=, :>:, :-->])
    Base.show(io::IO, def::JLExpr) = begin
            print_expr(io, def)
        end
    function print_expr(io::IO, ex::JLExpr, ps::PrintState, theme::Color)
        print_expr(io, codegen_ast(ex), ps, theme)
    end
    function print_expr(io::IO, ex, ps::PrintState, theme::Color)
        var"##cache#517" = nothing
        var"##516" = ex
        if var"##516" isa Expr
            if begin
                        if var"##cache#517" === nothing
                            var"##cache#517" = Some(((var"##516").head, (var"##516").args))
                        end
                        var"##518" = (var"##cache#517").value
                        var"##518" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##518"[1] == :block && (begin
                                var"##519" = var"##518"[2]
                                var"##519" isa AbstractArray
                            end && (length(var"##519") === 2 && (begin
                                        var"##520" = var"##519"[1]
                                        var"##520" isa LineNumberNode
                                    end && begin
                                        var"##521" = var"##519"[2]
                                        true
                                    end))))
                stmt = var"##521"
                line = var"##520"
                var"##return#514" = begin
                        print_expr(io, stmt, ps, theme)
                        print(io, tab(2))
                        print_expr(io, line, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##522" = (var"##cache#517").value
                        var"##522" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##522"[1] == :block && (begin
                                var"##523" = var"##522"[2]
                                var"##523" isa AbstractArray
                            end && (length(var"##523") === 3 && (begin
                                        var"##524" = var"##523"[1]
                                        var"##525" = var"##523"[2]
                                        var"##525" isa LineNumberNode
                                    end && begin
                                        var"##526" = var"##523"[3]
                                        true
                                    end))))
                line = var"##525"
                stmt2 = var"##526"
                stmt1 = var"##524"
                var"##return#514" = begin
                        printstyled(io, "("; color = ps.color)
                        print_expr(io, stmt1, ps, theme)
                        printstyled(io, "; "; color = ps.color)
                        print_expr(io, stmt2)
                        printstyled(io, ")"; color = ps.color)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##527" = (var"##cache#517").value
                        var"##527" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##527"[1] == :block && (begin
                                var"##528" = var"##527"[2]
                                var"##528" isa AbstractArray
                            end && ((ndims(var"##528") === 1 && length(var"##528") >= 0) && begin
                                    var"##529" = (SubArray)(var"##528", (1:length(var"##528"),))
                                    true
                                end)))
                stmts = var"##529"
                var"##return#514" = begin
                        print_kw(io, "begin", ps, theme)
                        println(io, ps)
                        print_stmts_list(io, stmts, ps, theme)
                        print_end(io, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##530" = (var"##cache#517").value
                        var"##530" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##530"[1] == :let && (begin
                                var"##531" = var"##530"[2]
                                var"##531" isa AbstractArray
                            end && (length(var"##531") === 2 && begin
                                    var"##532" = var"##531"[1]
                                    var"##533" = var"##531"[2]
                                    true
                                end)))
                vars = var"##532"
                body = var"##533"
                var"##return#514" = begin
                        print_kw(io, "let", ps, theme)
                        if !(isempty(vars.args))
                            print(io, tab(1))
                            print_collection(io, vars.args, ps, theme)
                        end
                        println(io, ps)
                        print_stmts(io, body, ps, theme)
                        print_end(io, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##534" = (var"##cache#517").value
                        var"##534" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##534"[1] == :if && (begin
                                var"##535" = var"##534"[2]
                                var"##535" isa AbstractArray
                            end && ((ndims(var"##535") === 1 && length(var"##535") >= 2) && begin
                                    var"##536" = var"##535"[1]
                                    var"##537" = var"##535"[2]
                                    var"##538" = (SubArray)(var"##535", (3:length(var"##535"),))
                                    true
                                end)))
                cond = var"##536"
                body = var"##537"
                otherwise = var"##538"
                var"##return#514" = begin
                        printstyled(io, ex.head, tab(1); color = theme.kw)
                        print_expr(io, cond, ps, theme)
                        println(io, ps)
                        print_stmts(io, body, ps, theme)
                        if isempty(otherwise)
                            print_end(io, ps, theme)
                        else
                            otherwise = otherwise[1]
                            if Meta.isexpr(otherwise, :elseif)
                                print_expr(io, otherwise, ps, theme)
                            else
                                print_kw(io, "else", ps, theme)
                                println(io, ps)
                                print_stmts(io, otherwise, ps, theme)
                                print_end(io, ps, theme)
                            end
                        end
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##539" = (var"##cache#517").value
                        var"##539" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##539"[1] == :elseif && (begin
                                var"##540" = var"##539"[2]
                                var"##540" isa AbstractArray
                            end && ((ndims(var"##540") === 1 && length(var"##540") >= 2) && begin
                                    var"##541" = var"##540"[1]
                                    var"##542" = var"##540"[2]
                                    var"##543" = (SubArray)(var"##540", (3:length(var"##540"),))
                                    true
                                end)))
                cond = var"##541"
                body = var"##542"
                otherwise = var"##543"
                var"##return#514" = begin
                        printstyled(io, ex.head, tab(1); color = theme.kw)
                        print_expr(io, cond, ps, theme)
                        println(io, ps)
                        print_stmts(io, body, ps, theme)
                        if isempty(otherwise)
                            print_end(io, ps, theme)
                        else
                            otherwise = otherwise[1]
                            if Meta.isexpr(otherwise, :elseif)
                                print_expr(io, otherwise, ps, theme)
                            else
                                print_kw(io, "else", ps, theme)
                                println(io, ps)
                                print_stmts(io, otherwise, ps, theme)
                                print_end(io, ps, theme)
                            end
                        end
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##544" = (var"##cache#517").value
                        var"##544" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##544"[1] == :for && (begin
                                var"##545" = var"##544"[2]
                                var"##545" isa AbstractArray
                            end && (length(var"##545") === 2 && begin
                                    var"##546" = var"##545"[1]
                                    var"##547" = var"##545"[2]
                                    true
                                end)))
                body = var"##547"
                head = var"##546"
                var"##return#514" = begin
                        within_line(io, ps) do
                            print_kw(io, "for ", ps, theme)
                            if Meta.isexpr(head, :block)
                                print_collection(io, head.args, ps, theme)
                            else
                                print_expr(io, head, ps, theme)
                            end
                        end
                        println(io, ps)
                        print_stmts(io, body, ps, theme)
                        print_end(io, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##548" = (var"##cache#517").value
                        var"##548" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##548"[1] == :function && (begin
                                var"##549" = var"##548"[2]
                                var"##549" isa AbstractArray
                            end && (length(var"##549") === 2 && begin
                                    var"##550" = var"##549"[1]
                                    var"##551" = var"##549"[2]
                                    true
                                end)))
                call = var"##550"
                body = var"##551"
                var"##return#514" = begin
                        within_line(io, ps) do
                            print_kw(io, "function ", ps, theme)
                            print_expr(io, call, ps, theme)
                        end
                        println(io, ps)
                        print_stmts(io, body, ps, theme)
                        print_end(io, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##552" = (var"##cache#517").value
                        var"##552" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##552"[1] == :macrocall && (begin
                                var"##553" = var"##552"[2]
                                var"##553" isa AbstractArray
                            end && (length(var"##553") === 4 && (begin
                                        var"##554" = var"##553"[1]
                                        var"##554" == GlobalRef(Core, Symbol("@doc"))
                                    end && begin
                                        var"##555" = var"##553"[2]
                                        var"##556" = var"##553"[3]
                                        var"##557" = var"##553"[4]
                                        true
                                    end))))
                line = var"##555"
                code = var"##557"
                doc = var"##556"
                var"##return#514" = begin
                        print_expr(io, line, ps, theme)
                        println(io, ps)
                        print(io, tab(ps.line_indent))
                        printstyled(io, "\"\"\""; color = theme.string)
                        println(io, ps)
                        lines = split(doc, '\n')
                        for (i, line) = enumerate(lines)
                            print(io, tab(ps.line_indent))
                            printstyled(io, line; color = theme.string)
                            if i != length(lines)
                                println(io, ps)
                            end
                        end
                        print(io, tab(ps.line_indent))
                        printstyled(io, "\"\"\""; color = theme.string)
                        println(io, ps)
                        print_expr(io, code, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##558" = (var"##cache#517").value
                        var"##558" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##558"[1] == :macrocall && (begin
                                var"##559" = var"##558"[2]
                                var"##559" isa AbstractArray
                            end && ((ndims(var"##559") === 1 && length(var"##559") >= 2) && begin
                                    var"##560" = var"##559"[1]
                                    var"##561" = var"##559"[2]
                                    var"##562" = (SubArray)(var"##559", (3:length(var"##559"),))
                                    true
                                end)))
                line = var"##561"
                name = var"##560"
                xs = var"##562"
                var"##return#514" = begin
                        print_expr(io, line, ps, theme)
                        println(io, ps)
                        within_line(io, ps) do
                            with_color(theme.fn, ps) do
                                print_expr(io, name, ps, theme)
                            end
                            print(io, tab(1))
                            print_collection(io, xs, ps, theme; delim = tab(1))
                        end
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##563" = (var"##cache#517").value
                        var"##563" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##563"[1] == :struct && (begin
                                var"##564" = var"##563"[2]
                                var"##564" isa AbstractArray
                            end && (length(var"##564") === 3 && begin
                                    var"##565" = var"##564"[1]
                                    var"##566" = var"##564"[2]
                                    var"##567" = var"##564"[3]
                                    true
                                end)))
                ismutable = var"##565"
                body = var"##567"
                head = var"##566"
                var"##return#514" = begin
                        within_line(io, ps) do
                            if ismutable
                                printstyled(io, "mutable "; color = theme.kw)
                            end
                            printstyled(io, "struct "; color = theme.kw)
                            print_expr(io, head, ps, theme)
                        end
                        println(io, ps)
                        print_stmts(io, body, ps, theme)
                        print_end(io, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##568" = (var"##cache#517").value
                        var"##568" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##568"[1] == :try && (begin
                                var"##569" = var"##568"[2]
                                var"##569" isa AbstractArray
                            end && (length(var"##569") === 3 && begin
                                    var"##570" = var"##569"[1]
                                    var"##571" = var"##569"[2]
                                    var"##572" = var"##569"[3]
                                    true
                                end)))
                catch_body = var"##572"
                try_body = var"##570"
                catch_var = var"##571"
                var"##return#514" = begin
                        print_try(io, try_body, ps, theme)
                        print_catch(io, catch_var, catch_body, ps, theme)
                        print_end(io, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##573" = (var"##cache#517").value
                        var"##573" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##573"[1] == :try && (begin
                                var"##574" = var"##573"[2]
                                var"##574" isa AbstractArray
                            end && (length(var"##574") === 4 && (begin
                                        var"##575" = var"##574"[1]
                                        var"##574"[2] === false
                                    end && (var"##574"[3] === false && begin
                                            var"##576" = var"##574"[4]
                                            true
                                        end)))))
                try_body = var"##575"
                finally_body = var"##576"
                var"##return#514" = begin
                        print_try(io, try_body, ps, theme)
                        print_finally(io, finally_body, ps, theme)
                        print_end(io, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
            if begin
                        var"##577" = (var"##cache#517").value
                        var"##577" isa Tuple{Symbol, var2} where var2<:AbstractArray
                    end && (var"##577"[1] == :try && (begin
                                var"##578" = var"##577"[2]
                                var"##578" isa AbstractArray
                            end && (length(var"##578") === 4 && begin
                                    var"##579" = var"##578"[1]
                                    var"##580" = var"##578"[2]
                                    var"##581" = var"##578"[3]
                                    var"##582" = var"##578"[4]
                                    true
                                end)))
                catch_body = var"##581"
                try_body = var"##579"
                finally_body = var"##582"
                catch_var = var"##580"
                var"##return#514" = begin
                        print_try(io, try_body, ps, theme)
                        print_catch(io, catch_var, catch_body, ps, theme)
                        print_finally(io, finally_body, ps, theme)
                        print_end(io, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#515#583")))
            end
        end
        var"##return#514" = begin
                print_within_line(io, ex, ps, theme)
            end
        $(Expr(:symbolicgoto, Symbol("####final#515#583")))
        (error)("matching non-exhaustive, at #= none:58 =#")
        $(Expr(:symboliclabel, Symbol("####final#515#583")))
        var"##return#514"
    end
    function print_kw(io::IO, x, ps, theme::Color)
        print(io, tab(ps.line_indent))
        printstyled(io, x; color = theme.kw)
    end
    print_end(io::IO, ps, theme) = begin
            print_kw(io, "end", ps, theme)
        end
    function Base.println(io::IO, ps::PrintState)
        ps.line_indent = ps.content_indent
        println(io)
    end
    function print_stmts(io, body, ps::PrintState, theme::Color)
        if body isa Expr && body.head === :block
            print_stmts_list(io, body.args, ps, theme)
        else
            within_indent(ps) do
                print_expr(io, body, ps, theme)
                println(io, ps)
            end
        end
    end
    function print_try(io, try_body, ps, theme)
        print_kw(io, "try", ps, theme)
        println(io, ps)
        print_stmts(io, try_body, ps, theme)
    end
    function print_catch(io, catch_var, catch_body, ps, theme)
        print_kw(io, "catch ", ps, theme)
        print_expr(io, catch_var, ps, theme)
        println(io, ps)
        print_stmts(io, catch_body, ps, theme)
    end
    function print_finally(io, finally_body, ps, theme)
        print_kw(io, "finally", ps, theme)
        println(io, ps)
        print_stmts(io, finally_body, ps, theme)
    end
    function print_stmts_list(io, stmts, ps::PrintState, theme::Color)
        within_indent(ps) do
            for stmt = stmts
                print_expr(io, stmt, ps, theme)
                println(io, ps)
            end
        end
        return
    end
    function print_collection(io, xs, ps::PrintState, theme = Color(); delim = ", ")
        for i = 1:length(xs)
            print_expr(io, xs[i], ps, theme)
            if i !== length(xs)
                print(io, delim)
            end
        end
    end
    function with_color(f, name::Symbol, ps::PrintState)
        color = ps.color
        if color === :normal
            ps.color = name
        end
        ret = f()
        ps.color = color
        return ret
    end
    function within_line(f, io, ps)
        indent = ps.line_indent
        print(io, tab(indent))
        ps.line_indent = 0
        ret = f()
        ps.line_indent = indent
        return ret
    end
    function within_indent(f, ps)
        ps.line_indent += 4
        ps.content_indent = ps.line_indent
        ret = f()
        ps.line_indent -= 4
        ps.content_indent = ps.line_indent
        return ret
    end
    function print_within_line(io::IO, ex, ps::PrintState, theme::Color = Color())
        within_line(io, ps) do
            var"##cache#587" = nothing
            var"##586" = ex
            if var"##586" isa GlobalRef
                var"##return#584" = begin
                        printstyled(io, ex.mod, "."; color = ps.color)
                        print_expr(io, ex.name, ps, theme)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            end
            if var"##586" isa Symbol
                var"##return#584" = begin
                        printstyled(io, ex; color = ps.color)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            end
            if var"##586" isa Expr
                if begin
                            if var"##cache#587" === nothing
                                var"##cache#587" = Some(((var"##586").head, (var"##586").args))
                            end
                            var"##588" = (var"##cache#587").value
                            var"##588" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##588"[1] == :tuple && (begin
                                    var"##589" = var"##588"[2]
                                    var"##589" isa AbstractArray
                                end && ((ndims(var"##589") === 1 && length(var"##589") >= 1) && (begin
                                            var"##cache#591" = nothing
                                            var"##590" = var"##589"[1]
                                            var"##590" isa Expr
                                        end && (begin
                                                if var"##cache#591" === nothing
                                                    var"##cache#591" = Some(((var"##590").head, (var"##590").args))
                                                end
                                                var"##592" = (var"##cache#591").value
                                                var"##592" isa Tuple{Symbol, var2} where var2<:AbstractArray
                                            end && (var"##592"[1] == :parameters && (begin
                                                        var"##593" = var"##592"[2]
                                                        var"##593" isa AbstractArray
                                                    end && ((ndims(var"##593") === 1 && length(var"##593") >= 0) && begin
                                                            var"##594" = (SubArray)(var"##593", (1:length(var"##593"),))
                                                            var"##595" = (SubArray)(var"##589", (2:length(var"##589"),))
                                                            true
                                                        end))))))))
                    args = var"##595"
                    kwargs = var"##594"
                    var"##return#584" = begin
                            printstyled(io, "("; color = ps.color)
                            print_collection(io, args, ps, theme)
                            if !(isempty(kwargs))
                                printstyled(io, "; "; color = ps.color)
                                print_collection(io, kwargs, ps)
                            end
                            printstyled(io, ")"; color = ps.color)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##596" = (var"##cache#587").value
                            var"##596" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##596"[1] == :tuple && (begin
                                    var"##597" = var"##596"[2]
                                    var"##597" isa AbstractArray
                                end && ((ndims(var"##597") === 1 && length(var"##597") >= 0) && begin
                                        var"##598" = (SubArray)(var"##597", (1:length(var"##597"),))
                                        true
                                    end)))
                    xs = var"##598"
                    var"##return#584" = begin
                            printstyled(io, "("; color = ps.color)
                            print_collection(io, xs, ps)
                            printstyled(io, ")"; color = ps.color)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##599" = (var"##cache#587").value
                            var"##599" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##599"[1] == :(::) && (begin
                                    var"##600" = var"##599"[2]
                                    var"##600" isa AbstractArray
                                end && (length(var"##600") === 1 && begin
                                        var"##601" = var"##600"[1]
                                        true
                                    end)))
                    type = var"##601"
                    var"##return#584" = begin
                            printstyled(io, "::"; color = ps.color)
                            with_color(theme.type, ps) do
                                print_expr(io, type, ps, theme)
                            end
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##602" = (var"##cache#587").value
                            var"##602" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##602"[1] == :(::) && (begin
                                    var"##603" = var"##602"[2]
                                    var"##603" isa AbstractArray
                                end && (length(var"##603") === 2 && begin
                                        var"##604" = var"##603"[1]
                                        var"##605" = var"##603"[2]
                                        true
                                    end)))
                    type = var"##605"
                    name = var"##604"
                    var"##return#584" = begin
                            print_expr(io, name, ps, theme)
                            printstyled(io, "::"; color = ps.color)
                            with_color(theme.type, ps) do
                                print_expr(io, type, ps, theme)
                            end
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##606" = (var"##cache#587").value
                            var"##606" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##606"[1] == :<: && (begin
                                    var"##607" = var"##606"[2]
                                    var"##607" isa AbstractArray
                                end && (length(var"##607") === 2 && begin
                                        var"##608" = var"##607"[1]
                                        var"##609" = var"##607"[2]
                                        true
                                    end)))
                    type = var"##609"
                    name = var"##608"
                    var"##return#584" = begin
                            print_expr(io, name, ps, theme)
                            printstyled(io, " <: "; color = ps.color)
                            with_color(theme.type, ps) do
                                print_expr(io, type, ps, theme)
                            end
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##610" = (var"##cache#587").value
                            var"##610" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##610"[1] == :kw && (begin
                                    var"##611" = var"##610"[2]
                                    var"##611" isa AbstractArray
                                end && (length(var"##611") === 2 && begin
                                        var"##612" = var"##611"[1]
                                        var"##613" = var"##611"[2]
                                        true
                                    end)))
                    value = var"##613"
                    name = var"##612"
                    var"##return#584" = begin
                            print_expr(io, name, ps, theme)
                            printstyled(io, tab(1), "=", tab(1); color = ps.color)
                            print_expr(io, value, ps, theme)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##614" = (var"##cache#587").value
                            var"##614" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##614"[1] == :(=) && (begin
                                    var"##615" = var"##614"[2]
                                    var"##615" isa AbstractArray
                                end && (length(var"##615") === 2 && begin
                                        var"##616" = var"##615"[1]
                                        var"##617" = var"##615"[2]
                                        true
                                    end)))
                    value = var"##617"
                    name = var"##616"
                    var"##return#584" = begin
                            print_expr(io, name, ps, theme)
                            printstyled(io, tab(1), "=", tab(1); color = ps.color)
                            print_expr(io, value, ps, theme)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##618" = (var"##cache#587").value
                            var"##618" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##618"[1] == :... && (begin
                                    var"##619" = var"##618"[2]
                                    var"##619" isa AbstractArray
                                end && (length(var"##619") === 1 && begin
                                        var"##620" = var"##619"[1]
                                        true
                                    end)))
                    name = var"##620"
                    var"##return#584" = begin
                            print_expr(io, name, ps, theme)
                            print(io, "...")
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##621" = (var"##cache#587").value
                            var"##621" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##621"[1] == :& && (begin
                                    var"##622" = var"##621"[2]
                                    var"##622" isa AbstractArray
                                end && (length(var"##622") === 1 && begin
                                        var"##623" = var"##622"[1]
                                        true
                                    end)))
                    name = var"##623"
                    var"##return#584" = begin
                            printstyled(io, "&"; color = theme.kw)
                            print_expr(io, name, ps, theme)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##624" = (var"##cache#587").value
                            var"##624" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##624"[1] == :$ && (begin
                                    var"##625" = var"##624"[2]
                                    var"##625" isa AbstractArray
                                end && (length(var"##625") === 1 && begin
                                        var"##626" = var"##625"[1]
                                        true
                                    end)))
                    name = var"##626"
                    var"##return#584" = begin
                            printstyled(io, "\$"; color = theme.kw)
                            print(io, "(")
                            print_expr(io, name, ps, theme)
                            print(io, ")")
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##627" = (var"##cache#587").value
                            var"##627" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##627"[1] == :curly && (begin
                                    var"##628" = var"##627"[2]
                                    var"##628" isa AbstractArray
                                end && ((ndims(var"##628") === 1 && length(var"##628") >= 1) && begin
                                        var"##629" = var"##628"[1]
                                        var"##630" = (SubArray)(var"##628", (2:length(var"##628"),))
                                        true
                                    end)))
                    vars = var"##630"
                    name = var"##629"
                    var"##return#584" = begin
                            print_expr(io, name, ps, theme)
                            print(io, "{")
                            with_color(theme.type, ps) do
                                print_collection(io, vars, ps, theme)
                            end
                            print(io, "}")
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##631" = (var"##cache#587").value
                            var"##631" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##631"[1] == :ref && (begin
                                    var"##632" = var"##631"[2]
                                    var"##632" isa AbstractArray
                                end && ((ndims(var"##632") === 1 && length(var"##632") >= 1) && begin
                                        var"##633" = var"##632"[1]
                                        var"##634" = (SubArray)(var"##632", (2:length(var"##632"),))
                                        true
                                    end)))
                    name = var"##633"
                    xs = var"##634"
                    var"##return#584" = begin
                            print_expr(io, name, ps, theme)
                            print(io, "[")
                            print_collection(io, xs, ps, theme)
                            print(io, "]")
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##635" = (var"##cache#587").value
                            var"##635" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##635"[1] == :where && (begin
                                    var"##636" = var"##635"[2]
                                    var"##636" isa AbstractArray
                                end && ((ndims(var"##636") === 1 && length(var"##636") >= 1) && begin
                                        var"##637" = var"##636"[1]
                                        var"##638" = (SubArray)(var"##636", (2:length(var"##636"),))
                                        true
                                    end)))
                    body = var"##637"
                    whereparams = var"##638"
                    var"##return#584" = begin
                            print_expr(io, body, ps, theme)
                            printstyled(io, tab(1), "where", tab(1); color = theme.kw)
                            print(io, "{")
                            print_collection(io, whereparams, ps, theme)
                            print(io, "}")
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##639" = (var"##cache#587").value
                            var"##639" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##639"[1] == :call && (begin
                                    var"##640" = var"##639"[2]
                                    var"##640" isa AbstractArray
                                end && ((ndims(var"##640") === 1 && length(var"##640") >= 2) && (begin
                                            var"##641" = var"##640"[1]
                                            var"##cache#643" = nothing
                                            var"##642" = var"##640"[2]
                                            var"##642" isa Expr
                                        end && (begin
                                                if var"##cache#643" === nothing
                                                    var"##cache#643" = Some(((var"##642").head, (var"##642").args))
                                                end
                                                var"##644" = (var"##cache#643").value
                                                var"##644" isa Tuple{Symbol, var2} where var2<:AbstractArray
                                            end && (var"##644"[1] == :parameters && (begin
                                                        var"##645" = var"##644"[2]
                                                        var"##645" isa AbstractArray
                                                    end && ((ndims(var"##645") === 1 && length(var"##645") >= 0) && begin
                                                            var"##646" = (SubArray)(var"##645", (1:length(var"##645"),))
                                                            var"##647" = (SubArray)(var"##640", (3:length(var"##640"),))
                                                            true
                                                        end))))))))
                    name = var"##641"
                    args = var"##647"
                    kwargs = var"##646"
                    var"##return#584" = begin
                            print_expr(io, name, ps, theme)
                            printstyled(io, "("; color = ps.color)
                            print_collection(io, args, ps)
                            if !(isempty(kwargs))
                                printstyled(io, "; "; color = ps.color)
                                print_collection(io, kwargs, ps)
                            end
                            printstyled(io, ")"; color = ps.color)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##648" = (var"##cache#587").value
                            var"##648" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##648"[1] == :call && (begin
                                    var"##649" = var"##648"[2]
                                    var"##649" isa AbstractArray
                                end && ((ndims(var"##649") === 1 && length(var"##649") >= 1) && (var"##649"[1] == :(:) && begin
                                            var"##650" = (SubArray)(var"##649", (2:length(var"##649"),))
                                            true
                                        end))))
                    xs = var"##650"
                    var"##return#584" = begin
                            print_collection(io, xs, ps, theme; delim = ":")
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##651" = (var"##cache#587").value
                            var"##651" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##651"[1] == :call && (begin
                                    var"##652" = var"##651"[2]
                                    var"##652" isa AbstractArray
                                end && (length(var"##652") === 2 && (begin
                                            var"##653" = var"##652"[1]
                                            var"##653" isa Symbol
                                        end && begin
                                            var"##654" = var"##652"[2]
                                            true
                                        end))))
                    name = var"##653"
                    x = var"##654"
                    var"##return#584" = begin
                            if name in uni_ops
                                print_expr(io, name, ps, theme)
                                print_expr(io, x, ps, theme)
                            else
                                print_call_expr(io, name, [x], ps, theme)
                            end
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##655" = (var"##cache#587").value
                            var"##655" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##655"[1] == :call && (begin
                                    var"##656" = var"##655"[2]
                                    var"##656" isa AbstractArray
                                end && (length(var"##656") === 3 && begin
                                        var"##657" = var"##656"[1]
                                        var"##658" = var"##656"[2]
                                        var"##659" = var"##656"[3]
                                        true
                                    end)))
                    rhs = var"##659"
                    lhs = var"##658"
                    name = var"##657"
                    var"##return#584" = begin
                            func_prec = Base.operator_precedence(name_only(name))
                            if func_prec > 0
                                print_expr(io, lhs, ps, theme)
                                print(io, tab(1))
                                print_expr(io, name, ps, theme)
                                print(io, tab(1))
                                print_expr(io, rhs, ps, theme)
                            else
                                print_call_expr(io, name, [lhs, rhs], ps, theme)
                            end
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##660" = (var"##cache#587").value
                            var"##660" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##660"[1] == :call && (begin
                                    var"##661" = var"##660"[2]
                                    var"##661" isa AbstractArray
                                end && ((ndims(var"##661") === 1 && length(var"##661") >= 1) && begin
                                        var"##662" = var"##661"[1]
                                        var"##663" = (SubArray)(var"##661", (2:length(var"##661"),))
                                        true
                                    end)))
                    name = var"##662"
                    args = var"##663"
                    var"##return#584" = begin
                            print_call_expr(io, name, args, ps, theme)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##664" = (var"##cache#587").value
                            var"##664" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##664"[1] == :-> && (begin
                                    var"##665" = var"##664"[2]
                                    var"##665" isa AbstractArray
                                end && (length(var"##665") === 2 && begin
                                        var"##666" = var"##665"[1]
                                        var"##667" = var"##665"[2]
                                        true
                                    end)))
                    call = var"##666"
                    body = var"##667"
                    var"##return#584" = begin
                            print_expr(io, call, ps, theme)
                            printstyled(io, tab(1), "->", tab(1); color = theme.kw)
                            print_expr(io, body, ps, theme)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##668" = (var"##cache#587").value
                            var"##668" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##668"[1] == :return && (begin
                                    var"##669" = var"##668"[2]
                                    var"##669" isa AbstractArray
                                end && (length(var"##669") === 1 && begin
                                        var"##670" = var"##669"[1]
                                        true
                                    end)))
                    x = var"##670"
                    var"##return#584" = begin
                            printstyled(io, "return", tab(1); color = theme.kw)
                            let
                                var"##cache#683" = nothing
                                var"##return#680" = nothing
                                var"##682" = x
                                if var"##682" isa Expr && (begin
                                                if var"##cache#683" === nothing
                                                    var"##cache#683" = Some(((var"##682").head, (var"##682").args))
                                                end
                                                var"##684" = (var"##cache#683").value
                                                var"##684" isa Tuple{Symbol, var2} where var2<:AbstractArray
                                            end && (var"##684"[1] == :tuple && (begin
                                                        var"##685" = var"##684"[2]
                                                        var"##685" isa AbstractArray
                                                    end && ((ndims(var"##685") === 1 && length(var"##685") >= 0) && begin
                                                            var"##686" = (SubArray)(var"##685", (1:length(var"##685"),))
                                                            true
                                                        end))))
                                    var"##return#680" = let xs = var"##686"
                                            print_collection(io, xs, ps)
                                        end
                                    $(Expr(:symbolicgoto, Symbol("####final#681#687")))
                                end
                                var"##return#680" = let
                                        print_expr(io, x, ps, theme)
                                    end
                                $(Expr(:symbolicgoto, Symbol("####final#681#687")))
                                (error)("matching non-exhaustive, at #= none:388 =#")
                                $(Expr(:symboliclabel, Symbol("####final#681#687")))
                                var"##return#680"
                            end
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##671" = (var"##cache#587").value
                            var"##671" isa Tuple{Symbol, var2} where var2<:AbstractArray
                        end && (var"##671"[1] == :string && (begin
                                    var"##672" = var"##671"[2]
                                    var"##672" isa AbstractArray
                                end && ((ndims(var"##672") === 1 && length(var"##672") >= 0) && begin
                                        var"##673" = (SubArray)(var"##672", (1:length(var"##672"),))
                                        true
                                    end)))
                    xs = var"##673"
                    var"##return#584" = begin
                            printstyled(io, "\""; color = theme.string)
                            for x = xs
                                if x isa String
                                    printstyled(io, x; color = theme.string)
                                else
                                    printstyled(io, "\$"; color = theme.literal)
                                    with_color(theme.literal, ps) do
                                        print_expr(io, x, ps, theme)
                                    end
                                end
                            end
                            printstyled(io, "\""; color = theme.string)
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
                if begin
                            var"##674" = (var"##cache#587").value
                            var"##674" isa Tuple{var1, var2} where {var2<:AbstractArray, var1}
                        end && (begin
                                var"##675" = var"##674"[1]
                                var"##676" = var"##674"[2]
                                var"##676" isa AbstractArray
                            end && (length(var"##676") === 2 && begin
                                    var"##677" = var"##676"[1]
                                    var"##678" = var"##676"[2]
                                    true
                                end))
                    rhs = var"##678"
                    lhs = var"##677"
                    head = var"##675"
                    var"##return#584" = begin
                            if head in expr_infix_wide
                                print_expr(io, lhs, ps, theme)
                                printstyled(io, tab(1), head, tab(1); color = theme.kw)
                                print_expr(io, rhs, ps, theme)
                            else
                                Base.show_unquoted_quote_expr(IOContext(io, :unquote_fallback => true), ex, ps.line_indent, -1, 0)
                            end
                        end
                    $(Expr(:symbolicgoto, Symbol("####final#585#679")))
                end
            end
            if var"##586" isa Number
                var"##return#584" = begin
                        printstyled(io, ex; color = theme.literal)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            end
            if var"##586" isa Nothing
                var"##return#584" = begin
                        printstyled(io, "nothing"; color = :blue)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            end
            if var"##586" isa QuoteNode
                var"##return#584" = begin
                        if Base.isidentifier(ex.value)
                            print(io, ":", ex.value)
                        else
                            print(io, ":(", ex.value, ")")
                        end
                    end
                $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            end
            if var"##586" isa LineNumberNode
                var"##return#584" = begin
                        printstyled(io, ex; color = theme.comment)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            end
            if var"##586" isa String
                var"##return#584" = begin
                        printstyled(io, "\"", ex, "\""; color = theme.string)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            end
            if var"##586" isa Base.ExprNode
                var"##return#584" = begin
                        Base.show_unquoted_quote_expr(IOContext(io, :unquote_fallback => true), ex, ps.line_indent, -1, 0)
                    end
                $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            end
            var"##return#584" = begin
                    print(io, ex)
                end
            $(Expr(:symbolicgoto, Symbol("####final#585#679")))
            (error)("matching non-exhaustive, at #= none:269 =#")
            $(Expr(:symboliclabel, Symbol("####final#585#679")))
            var"##return#584"
        end
        return
    end
    function print_call_expr(io::IO, name, args, ps, theme)
        print_expr(io, name, ps, theme)
        printstyled(io, "("; color = ps.color)
        print_collection(io, args, ps, theme)
        printstyled(io, ")"; color = ps.color)
    end
end


text:
using ProximalOperators
using LinearAlgebra

# Nonsmooth + regularization

mu, lam = 2.0, 3.0

f = NormL1(mu)
g = Regularize(f, lam)
h = ElasticNet(mu, lam)

x = randn(10)

gx = call_test(g, x)
hx = call_test(h, x)

@test abs(gx - hx)/(1+abs(gx)) <= 1e-12

yg, gy = prox_test(g, x, 0.5)
yh, hy = prox_test(h, x, 0.5)

@test abs(gy - hy)/(1+abs(gy)) <= 1e-12
@test norm(yg - yh, Inf)/(1+norm(yg, Inf)) <= 1e-12

# Smooth + regularization (test also gradient)

m, n = 10, 20
lam = 1.5

A = randn(m, n)
b = randn(m)

f = LeastSquares(A, b)
g = Regularize(f, lam)

x = randn(n)
res = A*x-b

gx = call_test(g, x)

@test abs(0.5*norm(res)^2 + (0.5*lam)*norm(x)^2 - gx)/(1+abs(gx)) <= 1e-12

prox_test(g, x, 0.7)
grad_gx, gx1 = gradient_test(g, x)

@test abs(gx - gx1)/(1+abs(gx)) <= 1e-12
@test norm(grad_gx - A'*(A*x - b) - lam*x, Inf)/(1+norm(grad_gx, Inf)) <= 1e-12


text:
#=
    ref:
    Choosing a Twice More Accurate Dot Product Implementation by Stef Graillat
    Ogita, Rump, Oishi (SISC 05)
=#

""" dot(x,y) as if computed at twice working precision """
function csdDot{T<:AbstractFloat}(x::Vector{T}, y::Vector{T})
   wrk=csd=p=q=r=zero(T)
   n = length(x)
   if ((n == 0)|(n != length(y)))
      throw(ErrorException("vectors must be of the same nonzero length"))
   end
   wrk,csd = eftMul(x[1], y[1])
   for i in 2:n
       p,q = eftMul(x[i], y[i])
       wrk,r = eftAdd(wrk, p)
       csd += q+r
   end
   wrk+csd
end


text:
# Definiciones para distribuciones dispersas de variaciones intermensuales
# utilizadas en el cómputo de la medida de inflación subyacente MAI (muestra
# ampliada implícitamente)

# Constante de normalización para ponderaciones
const WN = 1

# Función de posición en grilla discreta vspace. Esta función requiere que la
# grilla sea definida de forma simétrica, ya que la posición del cero está fija
function vposition(v, vspace)
	v0 = (length(vspace) + 1) ÷ 2
	eps = step(vspace)
	pos = v0 + round(Int, v / eps)
    pos
end

# Tipo abstracto para representar las distribuciones empíricas, dispersas o
# acumuladas de variaciones intermensuales, equiponderadas y ponderadas
abstract type TransversalDistr{T <: AbstractFloat} end

# Distribución de observaciones
struct ObservationsDistr{T, R} <: TransversalDistr{T}
    distr::SparseVector{T, Int}
    vspace::StepRangeLen{T, R, R}
end

function ObservationsDistr(v::AbstractVector{T}, vspace) where T
    # Obtener posiciones de variaciones en vspace
    vpos = vposition.(v, Ref(vspace))
    # Obtener las ponderaciones
    l = length(v)
    w = WN * one(T) / l
    # Obtener distribución dispersa
    distr = sparsevec(vpos, w, length(vspace))
    ObservationsDistr(distr, vspace)
end

# Distribución de ponderaciones
struct WeightsDistr{T, R} <: TransversalDistr{T}
    distr::SparseVector{T, Int}
    vspace::StepRangeLen{T, R, R}
end

function WeightsDistr(v::AbstractVector{T}, w::AbstractVector{T}, vspace) where T
    # Obtener posiciones de variaciones en vspace
    vpos = vposition.(v, Ref(vspace))
    # Obtener las ponderaciones
    w = WN * w / sum(w)
    # Obtener distribución dispersa
    distr = sparsevec(vpos, w, length(vspace))
    WeightsDistr(distr, vspace)
end

# Distribución transversal acumulada
struct AccumulatedDistr{T, R} <: TransversalDistr{T}
    distr::SparseVector{T, Int}
    vspace::StepRangeLen{T, R, R}
end

# Función para mostrar
function Base.show(io::IO, tdistr::TransversalDistr)
    println(io, "Sparse ", typeof(tdistr))
    println(io, "|─> Distribution : ", summary(tdistr.distr))
    println(io, "|─> Support      : ", tdistr.vspace, " ─ Step: ", step(tdistr.vspace))
    println(io, "|─> Elements     : ", nnz(tdistr.distr))

    # Imprimir la distribución, con índices y posiciones en la grilla
    n = length(tdistr.distr)
    pad = ndigits(n)
    limit = get(io, :limit, false)::Bool
    half_screen_rows = limit ? div(displaysize(io)[1] - 10, 2) : typemax(Int)
    nzind = tdistr.distr.nzind
    nzval = tdistr.distr.nzval

    for k = eachindex(nzind)
        if k < half_screen_rows || k > length(nzind) - half_screen_rows
            print(io, "    ", '[', rpad(nzind[k], pad), "]  => ", lpad(tdistr.vspace[nzind[k]], 7), "  =>  ", round(nzval[k], digits=5))
            k != length(nzind) && println(io)
        elseif k == half_screen_rows
            println(io, "   ", " "^pad, "   \u22ee")
        end
    end
end

## Extendiendo métodos para distribuciones transversales

# Método para sumar dos distribuciones f o g.
# ¡Supone que a y b tienen el mismo vspace!
function Base.:+(a::TransversalDistr, b::TransversalDistr)
    # Combinar los vectores de distribución y normalizar
    sparsedistr = (a.distr + b.distr) / 2
    # Obtener el tipo concreto para la distribución
    TypeDistr = typeof(a)
    TypeDistr(sparsedistr, a.vspace)
end

# Obtener el promedio simple o ponderado según la distribución
function Statistics.mean(tdistr::TransversalDistr)
    tdistr.vspace' * tdistr.distr / WN
end

# Suma de los valores en la distribución
Base.sum(tdistr::TransversalDistr) = sum(tdistr.distr)

# Obtener valor distribución en una variación intermensual
function (tdistr::TransversalDistr)(v::Real)
    # Obtener la posición en la grilla de variaciones intermensuales y devolver
    # el valor almacenado en esa posición en el vector disperso
    vpos = vposition(v, tdistr.vspace)
    tdistr.distr[vpos]
end

## Extendiendo métodos para distribuciones acumuladas

# Obtener distribución acumulada de distribución dispersa
function Base.cumsum(tdistr::TransversalDistr)
    AccumulatedDistr(
        sparsevec(tdistr.distr.nzind, cumsum(tdistr.distr.nzval), tdistr.distr.n),
        tdistr.vspace)
end

function Base.cumsum!(tdistr::TransversalDistr)
    v_values = tdistr.distr.nzval
    cumsum!(v_values, v_values)
    AccumulatedDistr(
        sparsevec(tdistr.distr.nzind, v_values, tdistr.distr.n),
        tdistr.vspace)
end

# Obtener valor de distribución acumulada en una variación intermensual
function (tdistr::AccumulatedDistr{T})(v::Real) where T
    # Obtener posición en la grilla
    vpos = vposition(v, tdistr.vspace)

    # Obtener índice de última variacióni intermensual guardada que sea mayor o
    # igual a la buscada
    l = findlast(vpos .>= tdistr.distr.nzind)
    l === nothing && return zero(T)
    m = tdistr.distr.nzval[l]
    m
end

# Algoritmo de percentil próximo para distribuciones
function Statistics.quantile(cdistr::AccumulatedDistr{T}, p::Real) where T
    # Obtener el vector disperso subyacente y sus índices
    sparse_cdistr = cdistr.distr.nzval
    cdistr_inds = cdistr.distr.nzind
    ε = step(cdistr.vspace)

    # Aplicar el algoritmo de percentil próximo para obtener índice de variación
    # intermensual correspondiente al cuantil p
    i_p = cdistr_inds[1]
    mindist = one(T)
    @inbounds for i in 1:length(sparse_cdistr)
        dist = abs(sparse_cdistr[i] - p)
        if dist < mindist
            mindist = dist
            i_p = i
        end
    end

    # Obtener la variación intermensual asociada
    q_p = cdistr.vspace[cdistr_inds[i_p]]

    # Si la variación es la última, no reajustar
    if i_p == length(cdistr_inds)
        return q_p
    # Si el índice es de la variación cero, devolver esta variación intermensual
    elseif q_p == T(-0.01)
        return zero(T)
    # Si la variación del cuantil p es menor que p, obtener la máxima de las
    # variaciones intermensuales que verifica ser la más próxima al cuantil
    # buscado
    elseif cdistr(q_p) < p
        q_p = cdistr.vspace[cdistr_inds[i_p + 1]] - ε
    end

    q_p::T
end

# Definición para cómputo de varios percentiles a la vez
Statistics.quantile(cdistr::AccumulatedDistr{T}, p::AbstractVector) where T =
    quantile.(Ref(cdistr), p)::Vector{T}

# Función de cómputo de percentiles in-place
function Statistics.quantile!(q, cdistr::AccumulatedDistr, p)
    for i in eachindex(p)
        q[i] = quantile(cdistr, p[i])
    end
end

## Métodos para generar distribuciones a partir de VarCPIBase y CountryStructure

function ObservationsDistr(base::VarCPIBase{T}, vspace) where T
    # Obtener años completos en la base
    full_years = periods(base) ÷ 12

    v = view(base.v[1:12*full_years, :], :)

    # Obtener posiciones de variaciones en vspace
    vpos = vposition.(v, Ref(vspace))
    # Obtener las ponderaciones
    l = length(v)
    w = WN * one(T) / l

    # # Obtener distribución dispersa
    distr = sparsevec(vpos, w, length(vspace))
    ObservationsDistr(distr, vspace)
end

function WeightsDistr(base::VarCPIBase{T}, vspace) where T
    # Obtener años completos en la base
    full_years = periods(base) ÷ 12

    v = view(base.v[1:12*full_years, :], :)
    weights = repeat(base.w', 12*full_years)

    # Obtener posiciones de variaciones en vspace
    vpos = vposition.(v, Ref(vspace))
    # Obtener las ponderaciones
    w = WN * (@view weights[:]) / sum(weights)

    # # Obtener distribución dispersa
    distr = sparsevec(vpos, w, length(vspace))
    WeightsDistr(distr, vspace)
end

## RecipesBase

@recipe function plot(tdistr::TransversalDistr)

    # Etiqueta
    if tdistr isa ObservationsDistr
        lbl = "Distribución de observaciones f"
    elseif tdistr isa WeightsDistr
        lbl = "Distribución de pesos g"
    else
        lbl = "Distribución acumulada"
    end
    label --> lbl
    legend --> :topleft

    # Tipo de gráfica
    # ptype = tdistr isa AccumulatedDistr ? :line : :bar
    # seriestype --> ptype

    # Límites
    xlims --> (-10, 20)

    tdistr.vspace, tdistr.(tdistr.vspace)
end


text: # This is the file to contain an agent description using the assumption from agent zero


text:
include("preamble.jl")

@test begin
    PyBase.pytest(inprocess = true)
    true
end


text:
# https://github.com/ma-laforge/InspectDR.jl

#=TODO:
    Tweak scale factor for width & other sizes

Not supported by InspectDR:
    :foreground_color_grid
    :foreground_color_border
    :polar,

Add in functionality to Plots.jl:
    :aspect_ratio,
=#

@require Revise begin
    Revise.track(Plots, joinpath(Pkg.dir("Plots"), "src", "backends", "inspectdr.jl"))
end

# ---------------------------------------------------------------------------
#TODO: remove features
const _inspectdr_attr = merge_with_base_supported([
    :annotations,
    :background_color_legend, :background_color_inside, :background_color_outside,
    # :foreground_color_grid,
    :foreground_color_legend, :foreground_color_title,
    :foreground_color_axis, :foreground_color_border, :foreground_color_guide, :foreground_color_text,
    :label,
    :linecolor, :linestyle, :linewidth, :linealpha,
    :markershape, :markercolor, :markersize, :markeralpha,
    :markerstrokewidth, :markerstrokecolor, :markerstrokealpha,
    :markerstrokestyle, #Causes warning not to have it... what is this?
    :fillcolor, :fillalpha, #:fillrange,
#    :bins, :bar_width, :bar_edges, :bar_position,
    :title, :title_location,
    :window_title,
    :guide, :lims, :scale, #:ticks, :flip, :rotation,
    :titlefontfamily, :titlefontsize, :titlefontcolor,
    :legendfontfamily, :legendfontsize, :legendfontcolor,
    :tickfontfamily, :tickfontsize, :tickfontcolor,
    :guidefontfamily, :guidefontsize, :guidefontcolor,
    :grid, :legend, #:colorbar,
#    :marker_z,
#    :line_z,
#    :levels,
 #   :ribbon, :quiver, :arrow,
#    :orientation,
    :overwrite_figure,
    :polar,
#    :normalize, :weights,
#    :contours, :aspect_ratio,
    :match_dimensions,
#    :clims,
#    :inset_subplots,
    :dpi,
#    :colorbar_title,
  ])
const _inspectdr_style = [:auto, :solid, :dash, :dot, :dashdot]
const _inspectdr_seriestype = [
        :path, :scatter, :shape #, :steppre, :steppost
    ]
#see: _allMarkers, _shape_keys
const _inspectdr_marker = Symbol[
    :none, :auto,
    :circle, :rect, :diamond,
    :cross, :xcross,
    :utriangle, :dtriangle, :rtriangle, :ltriangle,
    :pentagon, :hexagon, :heptagon, :octagon,
    :star4, :star5, :star6, :star7, :star8,
    :vline, :hline, :+, :x,
]

const _inspectdr_scale = [:identity, :ln, :log2, :log10]

is_marker_supported(::InspectDRBackend, shape::Shape) = true

_inspectdr_to_pixels(bb::BoundingBox) =
    InspectDR.BoundingBox(to_pixels(left(bb)), to_pixels(right(bb)), to_pixels(top(bb)), to_pixels(bottom(bb)))

#Do we avoid Map to avoid possible pre-comile issues?
function _inspectdr_mapglyph(s::Symbol)
    s == :rect && return :square
    return s
end

function _inspectdr_mapglyph(s::Shape)
    x, y = coords(s)
    return InspectDR.GlyphPolyline(x, y)
end

# py_marker(markers::AVec) = map(py_marker, markers)
function _inspectdr_mapglyph(markers::AVec)
    warn("Vectors of markers are currently unsupported in InspectDR.")
    _inspectdr_mapglyph(markers[1])
end

_inspectdr_mapglyphsize(v::Real) = v
function _inspectdr_mapglyphsize(v::Vector)
    warn("Vectors of marker sizes are currently unsupported in InspectDR.")
    _inspectdr_mapglyphsize(v[1])
end

_inspectdr_mapcolor(v::Colorant) = v
function _inspectdr_mapcolor(g::PlotUtils.ColorGradient)
    warn("Color gradients are currently unsupported in InspectDR.")
    #Pick middle color:
    _inspectdr_mapcolor(g.colors[div(1+end,2)])
end
function _inspectdr_mapcolor(v::AVec)
    warn("Vectors of colors are currently unsupported in InspectDR.")
    #Pick middle color:
    _inspectdr_mapcolor(v[div(1+end,2)])
end

#Hack: suggested point size does not seem adequate relative to plot size, for some reason.
_inspectdr_mapptsize(v) = 1.5*v

function _inspectdr_add_annotations(plot, x, y, val)
    #What kind of annotation is this?
end

#plot::InspectDR.Plot2D
function _inspectdr_add_annotations(plot, x, y, val::PlotText)
    vmap = Dict{Symbol, Symbol}(:top=>:t, :bottom=>:b) #:vcenter
    hmap = Dict{Symbol, Symbol}(:left=>:l, :right=>:r) #:hcenter
    align = Symbol(get(vmap, val.font.valign, :c), get(hmap, val.font.halign, :c))
    fnt = InspectDR.Font(val.font.family, val.font.pointsize,
        color =_inspectdr_mapcolor(val.font.color)
    )
    ann = InspectDR.atext(val.str, x=x, y=y,
        font=fnt, angle=val.font.rotation, align=align
    )
    InspectDR.add(plot, ann)
    return
end

# ---------------------------------------------------------------------------

function _inspectdr_getscale(s::Symbol, yaxis::Bool)
#TODO: Support :asinh, :sqrt
    kwargs = yaxis ? (:tgtmajor=>8, :tgtminor=>2) : () #More grid lines on y-axis
    if :log2 == s
        return InspectDR.AxisScale(:log2; kwargs...)
    elseif :log10 == s
        return InspectDR.AxisScale(:log10; kwargs...)
    elseif :ln == s
        return InspectDR.AxisScale(:ln; kwargs...)
    else #identity
        return InspectDR.AxisScale(:lin; kwargs...)
    end
end

# ---------------------------------------------------------------------------

function add_backend_string(::InspectDRBackend)
    """
    if !Plots.is_installed("InspectDR")
        Pkg.add("InspectDR")
    end
    """
end

function _initialize_backend(::InspectDRBackend; kw...)
    @eval begin
        import InspectDR
        export InspectDR

        #Glyph used when plotting "Shape"s:
        const INSPECTDR_GLYPH_SHAPE = InspectDR.GlyphPolyline(
            2*InspectDR.GLYPH_SQUARE.x, InspectDR.GLYPH_SQUARE.y
        )

        mutable struct InspecDRPlotRef
            mplot::Union{Void, InspectDR.Multiplot}
            gui::Union{Void, InspectDR.GtkPlot}
        end

        _inspectdr_getmplot(::Any) = nothing
        _inspectdr_getmplot(r::InspecDRPlotRef) = r.mplot

        _inspectdr_getgui(::Any) = nothing
        _inspectdr_getgui(gplot::InspectDR.GtkPlot) = (gplot.destroyed ? nothing : gplot)
        _inspectdr_getgui(r::InspecDRPlotRef) = _inspectdr_getgui(r.gui)
    end
end

# ---------------------------------------------------------------------------

# Create the window/figure for this backend.
function _create_backend_figure(plt::Plot{InspectDRBackend})
    mplot = _inspectdr_getmplot(plt.o)
    gplot = _inspectdr_getgui(plt.o)

    #:overwrite_figure: want to reuse current figure
    if plt[:overwrite_figure] && mplot != nothing
        mplot.subplots = [] #Reset
        if gplot != nothing #Ensure still references current plot
            gplot.src = mplot
        end
    else #want new one:
        mplot = InspectDR.Multiplot()
        gplot = nothing #Will be created later
    end

    #break link with old subplots
    for sp in plt.subplots
        sp.o = nothing
    end

    return InspecDRPlotRef(mplot, gplot)
end

# ---------------------------------------------------------------------------

# # this is called early in the pipeline, use it to make the plot current or something
# function _prepare_plot_object(plt::Plot{InspectDRBackend})
# end

# ---------------------------------------------------------------------------

# Set up the subplot within the backend object.
function _initialize_subplot(plt::Plot{InspectDRBackend}, sp::Subplot{InspectDRBackend})
    plot = sp.o
    #Don't do anything without a "subplot" object:  Will process later.
    if nothing == plot; return; end
    plot.data = []
    plot.userannot = [] #Clear old markers/text annotation/polyline "annotation"
    return plot
end

# ---------------------------------------------------------------------------

# Add one series to the underlying backend object.
# Called once per series
# NOTE: Seems to be called when user calls plot()... even if backend
#       plot, sp.o has not yet been constructed...
function _series_added(plt::Plot{InspectDRBackend}, series::Series)
    st = series[:seriestype]
    sp = series[:subplot]
    plot = sp.o

    #Don't do anything without a "subplot" object:  Will process later.
    if nothing == plot; return; end

    _vectorize(v) = isa(v, Vector) ? v : collect(v) #InspectDR only supports vectors
    x = _vectorize(series[:x]); y = _vectorize(series[:y])

    #No support for polar grid... but can still perform polar transformation:
    if ispolar(sp)
        Θ = x; r = y
        x = r.*cos.(Θ); y = r.*sin.(Θ)
    end

    # doesn't handle mismatched x/y - wrap data (pyplot behaviour):
    nx = length(x); ny = length(y)
    if nx < ny
        series[:x] = Float64[x[mod1(i,nx)] for i=1:ny]
    elseif ny > nx
        series[:y] = Float64[y[mod1(i,ny)] for i=1:nx]
    end

#= TODO: Eventually support
    series[:fillcolor] #I think this is fill under line
    zorder = series[:series_plotindex]

For st in :shape:
    zorder = series[:series_plotindex],
=#

    if st in (:shape,)
        nmax = 0
        for (i,rng) in enumerate(iter_segments(x, y))
            nmax = i
            if length(rng) > 1
                linewidth = series[:linewidth]
                linecolor = _inspectdr_mapcolor(_cycle(series[:linecolor], i))
                fillcolor = _inspectdr_mapcolor(_cycle(series[:fillcolor], i))
                line = InspectDR.line(
                    style=:solid, width=linewidth, color=linecolor
                )
                apline = InspectDR.PolylineAnnotation(
                    x[rng], y[rng], line=line, fillcolor=fillcolor
                )
                InspectDR.add(plot, apline)
            end
        end

        i = (nmax >= 2 ? div(nmax, 2) : nmax) #Must pick one set of colors for legend
        if i > 1 #Add dummy waveform for legend entry:
            linewidth = series[:linewidth]
            linecolor = _inspectdr_mapcolor(_cycle(series[:linecolor], i))
            fillcolor = _inspectdr_mapcolor(_cycle(series[:fillcolor], i))
            wfrm = InspectDR.add(plot, Float64[], Float64[], id=series[:label])
            wfrm.line = InspectDR.line(
                style=:none, width=linewidth, #linewidth affects glyph
            )
            wfrm.glyph = InspectDR.glyph(
                shape = INSPECTDR_GLYPH_SHAPE, size = 8,
                color = linecolor, fillcolor = fillcolor
            )
        end
   elseif st in (:path, :scatter) #, :steppre, :steppost)
        #NOTE: In Plots.jl, :scatter plots have 0-linewidths (I think).
        linewidth = series[:linewidth]
        #More efficient & allows some support for markerstrokewidth:
        _style = (0==linewidth ? :none : series[:linestyle])
        wfrm = InspectDR.add(plot, x, y, id=series[:label])
        wfrm.line = InspectDR.line(
            style = _style,
            width = series[:linewidth],
            color = series[:linecolor],
        )
        #InspectDR does not control markerstrokewidth independently.
        if :none == _style
            #Use this property only if no line is displayed:
            wfrm.line.width = series[:markerstrokewidth]
        end
        wfrm.glyph = InspectDR.glyph(
            shape = _inspectdr_mapglyph(series[:markershape]),
            size = _inspectdr_mapglyphsize(series[:markersize]),
            color = _inspectdr_mapcolor(series[:markerstrokecolor]),
            fillcolor = _inspectdr_mapcolor(series[:markercolor]),
        )
    end

    # this is all we need to add the series_annotations text
    anns = series[:series_annotations]
    for (xi,yi,str,fnt) in EachAnn(anns, x, y)
        _inspectdr_add_annotations(plot, xi, yi, PlotText(str, fnt))
    end
    return
end

# ---------------------------------------------------------------------------

# When series data is added/changed, this callback can do dynamic updates to the backend object.
# note: if the backend rebuilds the plot from scratch on display, then you might not do anything here.
function _series_updated(plt::Plot{InspectDRBackend}, series::Series)
    #Nothing to do
end

# ---------------------------------------------------------------------------

function _inspectdr_setupsubplot(sp::Subplot{InspectDRBackend})
    const plot = sp.o
    const strip = plot.strips[1] #Only 1 strip supported with Plots.jl

    xaxis = sp[:xaxis]; yaxis = sp[:yaxis]
    xgrid_show = xaxis[:grid]
    ygrid_show = yaxis[:grid]

    strip.grid = InspectDR.GridRect(
    	vmajor=xgrid_show, # vminor=xgrid_show,
    	hmajor=ygrid_show, # hminor=ygrid_show,
    )

        plot.xscale = _inspectdr_getscale(xaxis[:scale], false)
        strip.yscale = _inspectdr_getscale(yaxis[:scale], true)
        xmin, xmax  = axis_limits(xaxis)
        ymin, ymax  = axis_limits(yaxis)
        if ispolar(sp)
            #Plots.jl appears to give (xmin,xmax) ≜ (Θmin,Θmax) & (ymin,ymax) ≜ (rmin,rmax)
            rmax = NaNMath.max(abs(ymin), abs(ymax))
            xmin, xmax = -rmax, rmax
            ymin, ymax = -rmax, rmax
        end
        plot.xext = InspectDR.PExtents1D() #reset
        strip.yext = InspectDR.PExtents1D() #reset
        plot.xext_full = InspectDR.PExtents1D(xmin, xmax)
        strip.yext_full = InspectDR.PExtents1D(ymin, ymax)
    a = plot.annotation
        a.title = sp[:title]
        a.xlabel = xaxis[:guide]; a.ylabels = [yaxis[:guide]]

    l = plot.layout
        l[:frame_canvas].fillcolor = _inspectdr_mapcolor(sp[:background_color_subplot])
        l[:frame_data].fillcolor = _inspectdr_mapcolor(sp[:background_color_inside])
        l[:frame_data].line.color = _inspectdr_mapcolor(xaxis[:foreground_color_axis])
        l[:font_title] = InspectDR.Font(sp[:titlefontfamily],
            _inspectdr_mapptsize(sp[:titlefontsize]),
            color = _inspectdr_mapcolor(sp[:titlefontcolor])
        )
        #Cannot independently control fonts of axes with InspectDR:
        l[:font_axislabel] = InspectDR.Font(xaxis[:guidefontfamily],
            _inspectdr_mapptsize(xaxis[:guidefontsize]),
            color = _inspectdr_mapcolor(xaxis[:guidefontcolor])
        )
        l[:font_ticklabel] = InspectDR.Font(xaxis[:tickfontfamily],
            _inspectdr_mapptsize(xaxis[:tickfontsize]),
            color = _inspectdr_mapcolor(xaxis[:tickfontcolor])
        )
        l[:enable_legend] = (sp[:legend] != :none)
        #l[:halloc_legend] = 150 #TODO: compute???
        l[:font_legend] = InspectDR.Font(sp[:legendfontfamily],
            _inspectdr_mapptsize(sp[:legendfontsize]),
            color = _inspectdr_mapcolor(sp[:legendfontcolor])
        )
        l[:frame_legend].fillcolor = _inspectdr_mapcolor(sp[:background_color_legend])
end

# called just before updating layout bounding boxes... in case you need to prep
# for the calcs
function _before_layout_calcs(plt::Plot{InspectDRBackend})
    const mplot = _inspectdr_getmplot(plt.o)
    if nothing == mplot; return; end

    mplot.title = plt[:plot_title]
    if "" == mplot.title
        #Don't use window_title... probably not what you want.
        #mplot.title = plt[:window_title]
    end
    mplot.layout[:frame].fillcolor = _inspectdr_mapcolor(plt[:background_color_outside])

    resize!(mplot.subplots, length(plt.subplots))
    nsubplots = length(plt.subplots)
    for (i, sp) in enumerate(plt.subplots)
        if !isassigned(mplot.subplots, i)
            mplot.subplots[i] = InspectDR.Plot2D()
        end
        sp.o = mplot.subplots[i]
        plot = sp.o
        _initialize_subplot(plt, sp)
        _inspectdr_setupsubplot(sp)

        # add the annotations
        for ann in sp[:annotations]
            _inspectdr_add_annotations(plot, ann...)
        end
    end

    #Do not yet support absolute plot positionning.
    #Just try to make things look more-or less ok:
    if nsubplots <= 1
        mplot.layout[:ncolumns] = 1
    elseif nsubplots <= 4
        mplot.layout[:ncolumns] = 2
    elseif nsubplots <= 6
        mplot.layout[:ncolumns] = 3
    elseif nsubplots <= 12
        mplot.layout[:ncolumns] = 4
    else
        mplot.layout[:ncolumns] = 5
    end

    for series in plt.series_list
        _series_added(plt, series)
    end
    return
end

# ----------------------------------------------------------------

# Set the (left, top, right, bottom) minimum padding around the plot area
# to fit ticks, tick labels, guides, colorbars, etc.
function _update_min_padding!(sp::Subplot{InspectDRBackend})
    plot = sp.o
    if !isa(plot, InspectDR.Plot2D); return sp.minpad; end
    #Computing plotbounds with 0-BoundingBox returns required padding:
    bb = InspectDR.plotbounds(plot.layout.values, InspectDR.BoundingBox(0,0,0,0))
    #NOTE: plotbounds always pads for titles, legends, etc. even if not in use.
    #TODO: possibly zero-out items not in use??

    # add in the user-specified margin to InspectDR padding:
    leftpad   = abs(bb.xmin)*px + sp[:left_margin]
    toppad    = abs(bb.ymin)*px + sp[:top_margin]
    rightpad  = abs(bb.xmax)*px + sp[:right_margin]
    bottompad = abs(bb.ymax)*px + sp[:bottom_margin]
    sp.minpad = (leftpad, toppad, rightpad, bottompad)
end

# ----------------------------------------------------------------

# Override this to update plot items (title, xlabel, etc), and add annotations (d[:annotations])
function _update_plot_object(plt::Plot{InspectDRBackend})
    mplot = _inspectdr_getmplot(plt.o)
    if nothing == mplot; return; end

    for (i, sp) in enumerate(plt.subplots)
        graphbb = _inspectdr_to_pixels(plotarea(sp))
        plot = mplot.subplots[i]
        plot.plotbb = InspectDR.plotbounds(plot.layout.values, graphbb)
    end

    gplot = _inspectdr_getgui(plt.o)
    if nothing == gplot; return; end

    gplot.src = mplot #Ensure still references current plot
    InspectDR.refresh(gplot)
    return
end

# ----------------------------------------------------------------

const _inspectdr_mimeformats_dpi = Dict(
    "image/png"               => "png"
)
const _inspectdr_mimeformats_nodpi = Dict(
    "image/svg+xml"           => "svg",
    "application/eps"         => "eps",
    "image/eps"               => "eps",
#    "application/postscript"  => "ps", #TODO: support once Cairo supports PSSurface
    "application/pdf"         => "pdf"
)
_inspectdr_show(io::IO, mime::MIME, ::Void, w, h) =
    throw(ErrorException("Cannot show(::IO, ...) plot - not yet generated"))
function _inspectdr_show(io::IO, mime::MIME, mplot, w, h)
    InspectDR._show(io, mime, mplot, Float64(w), Float64(h))
end

for (mime, fmt) in _inspectdr_mimeformats_dpi
    @eval function _show(io::IO, mime::MIME{Symbol($mime)}, plt::Plot{InspectDRBackend})
        dpi = plt[:dpi]#TODO: support
        _inspectdr_show(io, mime, _inspectdr_getmplot(plt.o), plt[:size]...)
    end
end
for (mime, fmt) in _inspectdr_mimeformats_nodpi
    @eval function _show(io::IO, mime::MIME{Symbol($mime)}, plt::Plot{InspectDRBackend})
        _inspectdr_show(io, mime, _inspectdr_getmplot(plt.o), plt[:size]...)
    end
end
_show(io::IO, mime::MIME"text/plain", plt::Plot{InspectDRBackend}) = nothing #Don't show

# ----------------------------------------------------------------

# Display/show the plot (open a GUI window, or browser page, for example).
function _display(plt::Plot{InspectDRBackend})
    mplot = _inspectdr_getmplot(plt.o)
    if nothing == mplot; return; end
    gplot = _inspectdr_getgui(plt.o)

    if nothing == gplot
        gplot = display(InspectDR.GtkDisplay(), mplot)
    else
        #redundant... Plots.jl will call _update_plot_object:
        #InspectDR.refresh(gplot)
    end
    plt.o = InspecDRPlotRef(mplot, gplot)
    return gplot
end


text:
function MarkNChess(r, n)
    counter = 0
    Moves = Array{Int,1}(undef, 1000)
    Moves, counter = movetothecorner(r, West, Moves)
    markntypechess(r, n)
    movements!(r, Sud)
    movements!(r, West)
    returnfromthecorner(r, Ost, Moves, counter)
end

function markntypechess(r, n)
    side = Ost
    x_coordinate = 0
    y_coordinate = 0
    while !isborder(r, Nord)
        x_coordinate = movelineandmarkntypechess(r, x_coordinate, y_coordinate, n, side)
        move!(r, Nord)
        y_coordinate += 1
        side = inverse(side)
    end
    x_coordinate = movelineandmarkntypechess(r, x_coordinate, y_coordinate, n, side)
end

function changexcoordinate(x_coordinate, side)
    if side == Ost
        x_coordinate += 1
    end
    if side == West
        x_coordinate -= 1
    end
    return x_coordinate
end

function putrightmarker(r, x_coordinate, y_coordinate, n)
    if (floor(x_coordinate / n) + floor(y_coordinate / n)) % 2 == 0
        putmarker!(r)
    end
end

function movelineandmarkntypechess(r, x_coordinate, y_coordinate, n, side)
    putrightmarker(r, x_coordinate, y_coordinate, n)
    while !isborder(r, side)
        move!(r, side)
        x_coordinate = changexcoordinate(x_coordinate, side)
        putrightmarker(r, x_coordinate, y_coordinate, n)
    end
    return x_coordinate
end

function movements!(r, side)
    while !isborder(r, side)
        move!(r, side)
    end
end


text:
# Inspired by "Fizz Buzz in Tensorflow" blog by Joel Grus
# http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/
using Flux: Chain, Dense, params, crossentropy, onehotbatch,
            ADAM, train!, softmax

using Random
using Test

# Data preparation
function fizzbuzz(x::Int)
    is_divisible_by_three = x % 3 == 0
    is_divisible_by_five = x % 5 == 0

    if is_divisible_by_three & is_divisible_by_five
        return "fizzbuzz"
    elseif is_divisible_by_three
        return "fizz"
    elseif is_divisible_by_five
        return "buzz"
    else
        return "else"
    end
end

const LABELS = ["fizz", "buzz", "fizzbuzz", "else"];

raw_x = 100:10000; #Made training dataset larger and exclusive of test set
raw_y = fizzbuzz.(raw_x);

# Feature engineering
features(x) = float.([x%3 , x%5 , x%15 ])
features(x::AbstractArray) = hcat(features.(x)...)

X = features(raw_x);
y = onehotbatch(raw_y, LABELS);

# Model
m = Chain(Dense(3, 100), Dense(100, 4), softmax)
loss(x, y) = crossentropy(m(X), y)
opt = ADAM()

# Helpers
deepbuzz(x) = (a = argmax(m(features(x))); a = LABELS[a])

function monitor(e)
    print("epoch $(lpad(e, 4)): loss = $(round(loss(X,y).data; digits=4)) | ")
    @show deepbuzz.([3, 5, 15, 98])
end

# Training
for e in 0:1000
    #Randomizing training data to avoid sequential bias
    Random.shuffle!(float.(raw_x))
    raw_y = fizzbuzz.(raw_x)
    X = features(raw_x);
    y = onehotbatch(raw_y, LABELS);
    train!(loss, params(m), [(X, y)], opt)
    if e % 50 == 0; monitor(e) end
end
#Test Cases added
@test fizzbuzz.([3, 5, 15, 98]) == deepbuzz.([3,5,15,98])
@test fizzbuzz.([10,9,60, 99]) == deepbuzz.([10,9,60,99])
@test fizzbuzz.([35, 42, 99, 3]) == deepbuzz.([35,42,99,3])
@test fizzbuzz.([55,64,72,18]) == deepbuzz.([55,64,72,18])

max_stars_repo_name: thebhatman/model-zoo

max_issues_repo_name: thebhatman/model-zoo

max_forks_repo_name: thebhatman/model-zoo


text:
module InsuranceTariffs
import BitemporalPostgres
import SearchLight: DbId
import Base: @kwdef
export Tariff, TariffRevision
using BitemporalPostgres

"""
Tariff

  a component of a bitemporal entity

"""
@kwdef mutable struct Tariff <: BitemporalPostgres.Component
  id::DbId = DbId()
  ref_history :: DbId = InfinityKey
  ref_version :: DbId = InfinityKey
end

"""
Tariff_Revision

  a revision of a Tariff component of a bitemporal entity

"""
@kwdef mutable struct TariffRevision <: BitemporalPostgres.ComponentRevision
  id::DbId = DbId()
  ref_component :: DbId = InfinityKey
  ref_validfrom::DbId = InfinityKey
  ref_invalidfrom::DbId = InfinityKey
  description::String = ""
end

end # module

max_stars_repo_name: michaelfliegner/BitempWebApp

max_issues_repo_name: michaelfliegner/BitempWebApp