text:
## CombinationFunction - Función de combinación lineal de medidas de inflación

# Tipo para representar combinaciones lineales de conjuntos de medidas
"""
    CombinationFunction{N, W} <: EnsembleInflationFunction <: InflationFunction

    CombinationFunction(ensemble, weights [, name, tag])
    CombinationFunction(inflfn1, inflfn2 [, ...], weights [, name, tag])

Función de inflación para computar un promedio ponderado de un conjunto de `N`
de medidas de inflación con tipo del vector de ponderaciones `W`.
"""
struct CombinationFunction{N, W} <: EnsembleInflationFunction
    ensemble::EnsembleFunction{N}
    weights::W
    name::Union{Nothing, String}
    tag::Union{Nothing, String}

    function CombinationFunction(ensemble::EnsembleFunction{N}, weights::W, name=nothing, tag=nothing) where {N, W}
        num_measures(ensemble) == length(weights) || throw(ArgumentError("número de ponderadores debe coincidir con número de medidas"))
        new{N, W}(ensemble, weights, name, tag)
    end
end

"""
    InflationCombination <: EnsembleInflationFunction <: InflationFunction

Alias para [`CombinationFunction`](@ref).
"""
const InflationCombination = CombinationFunction

# Utilidades para construir una CombinationFunction
function CombinationFunction(args...)
    if args[end-1] isa String && last(args) isa String
        return CombinationFunction(EnsembleFunction(args[1:end-3]), args[end-2], args[end-1], args[end])
    elseif !(args[end-1] isa String) && last(args) isa String
        return CombinationFunction(EnsembleFunction(args[1:end-2]), args[end-1], args[end])
    end
    CombinationFunction(EnsembleFunction(args[1:end-1]), args[end])
end

# Número de medidas
function num_measures(combfn::CombinationFunction; get_components = false)
    get_components && return num_measures(combfn.ensemble)
    1
end

# Ponderaciones
"""
    weights(combfn::CombinationFunction)
Devuelve el vector de ponderaciones de una [`CombinationFunction`](@ref).
"""
weights(combfn::CombinationFunction) = getfield(combfn, :weights)

# Nombres de medidas
function measure_name(combfn::CombinationFunction;
    return_array=false,
    show_weights=false)
    return_array && return measure_name(combfn.ensemble)
    isnothing(combfn.name) || return combfn.name

    n = length(combfn.ensemble.functions)
    wstr = show_weights ? "\n"*string(round.(combfn.weights, digits=2)) : ""
    "Promedio ponderado de $n metodologías" * wstr
end

# Etiqueta para una CombinationFunction
function measure_tag(combfn::CombinationFunction)
    isnothing(combfn.tag) || return combfn.tag
    "COMBFN"
end

# Aplicación sobre (::CountryStructure, ::CPIVarInterm) ajusta los índices y
# variaciones intermensuales para estar acordes con el promedio de las variaciones
# interanuales
function (combfn::CombinationFunction)(cs::CountryStructure, ::CPIVarInterm)
    cpi_index = combfn(cs, CPIIndex())
    varinterm!(cpi_index, cpi_index) # cpi_index -> v_interm
    cpi_index
end

function (combfn::CombinationFunction)(cs::CountryStructure, ::CPIIndex)
    # Obtener variaciones interanuales
    v_yoy = combfn(cs)
    # Obtener variaciones intermensuales promedio para las primeras 11 observaciones
    v_interm = mapreduce(inflfn -> inflfn(cs, CPIVarInterm()), hcat, combfn.ensemble.functions)::Matrix{eltype(cs)}
    v_mean_interm = v_interm * combfn.weights

    T = periods(cs)
    cpi_index = zeros(eltype(cs), T+1)
    cpi_index[1] = 100
    # Completar las primeras 11 variaciones intermensuales
    cpi_index[2:12] .= capitalize(v_mean_interm[1:11])
    # Capitalizar utilizando las variaciones interanuales
    for t = 13:T+1
        cpi_index[t] = (v_yoy[t-12]/100 + 1) * cpi_index[t-12]
    end
    cpi_index[2:end]
end

# Aplicación sobre CountryStructure: devuelve la combinación lineal en
# variaciones interanuales
function (combfn::CombinationFunction)(cst::CountryStructure)
    # Get ensemble and compute trajectories
    tray_infl = combfn.ensemble(cst)
    # Return weighted sum
    tray_infl * combfn.weights
end

## Métodos de ayuda

"""
    components(inflfn::CombinationFunction)

Devuelve un `DataFrame` con las componentes de la función de combinación lineal
y las ponderaciones asociadas.
"""
function components(inflfn::CombinationFunction)
    components = DataFrame(
        measure = measure_name(inflfn, return_array=true),
        weights = inflfn.weights
    )
    components
end


text:
using DataFrames, CSV
using TimeSeries, Dates

function pct_change(input::AbstractVector{<:Number})
    [i == 1 ? missing : (input[i]-input[i-1])/input[i-1] for i in eachindex(input)]
end

# This is the path to the Stocks directory in your extracted folder for the data
cd("/Path/to/data/price-volume-data-for-all-us-stocks-etfs/Stocks")

master_data = DataFrame(date = Date(2020, 5, 8), symbol = "NEWSTAT", price = 69.69)
for i in 1:730
    master_data[string(i) * "_pc"] = 0.00001
end

global index = 0
for (root, dirs, files) in walkdir(".")
    for file in files
        symbol_index = findfirst(".", file)[1]
        symbol = uppercase(SubString(file, 1, (symbol_index - 1)))
        println(symbol)

        data = convert(Matrix, CSV.read(joinpath(root, file)))

        data = data[:, 1:end .!= 2]
        data = data[:, 1:end .!= 2]
        data = data[:, 1:end .!= 2]
        data = data[:, 1:end .!= 3]
        data = data[:, 1:end .!= 3]

        data = convert(DataFrame, data)
        colnames = ["date", "price"]
        names!(data, Symbol.(colnames))
        symbols = [symbol]
        for i in 2:size(data, 1)
            append!(symbols, [symbol])
        end
        data["symbol"] = symbols
        permutecols!(data, [:date, :symbol, :price])

        data.date = Date.(data.date)

        for i in 1:730
            data_add = [0.00001]
            counter = 1
            for row in eachrow(data)
                if counter == 1
                    counter += 1
                    continue
                end

                pc = 0.00001
                if (counter - i) >= 1
                    oldPrice = data[(counter - i), 3]
                    pc = (row.price - oldPrice) / oldPrice
                end
                append!(data_add, [pc])

                counter += 1
            end
            data[string(i) * "_pc"] = data_add
        end

        append!(master_data, data)

        global index += 1
        if index % 500 == 0
            println("*** Writing data ***")
            # This path should be where you want the output files to go
            CSV.write("/Path to output files/master_data_" * string(Int(floor(index / 200))) * ".csv", master_data, writeheader=true)

            global master_data = DataFrame(date = Date(2020, 5, 8), symbol = "NEWSTAT", price = 69.69)
            for i in 1:730
                master_data[string(i) * "_pc"] = 0.00001
            end
        end
    end
end

ext: jl


text:
using AdversarialDriving
using AutomotiveSimulator, AutomotiveVisualization
using POMDPs, POMDPPolicies, POMDPSimulators

blindspot = Blindspot(π/12 - 0.05, π/13)
sut_agent = BlinkerVehicleAgent(get_ped_vehicle(id=1, s=5., v=15.), TIDM(ped_TIDM_template, noisy_observations = true, blindspot = blindspot))
adv_ped = NoisyPedestrianAgent(get_pedestrian(id=2, s=10.8, v=0.), AdversarialPedestrian(idm=IntelligentDriverModel(v_des = 0)))
mdp = AdversarialDrivingMDP(sut_agent, [adv_ped], ped_roadway, 0.1)

# Make the renderable object to visualize the blindspot
rb = (s) -> RenderableBlindspot(posg(get_by_id(s, sutid(mdp))), sut(mdp).model.blindspot, 30, colorant"black")

# Render a single frame
s = rand(initialstate(mdp))
c = render([mdp.roadway,
                crosswalk,
                rb(s),
                FancyCar(car = s[2], color = colorant"blue"),
                FancyPedestrian(ped = s[1])],
                surface=AutomotiveVisualization.CairoPDFSurface(IOBuffer(), DEFAULT_CANVAS_WIDTH, DEFAULT_CANVAS_HEIGHT))
write("blindspot.pdf", c)

# Example blindspot behavior
hist = POMDPSimulators.simulate(HistoryRecorder(max_steps = 25), mdp, FunctionPolicy((s) -> Disturbance[PedestrianControl()]))

# Write to gif
scenes_to_gif([s.s for s in hist], mdp.roadway, "blindspot.gif", others = [crosswalk], others_fn = [rb])

max_stars_repo_name: ancorso/MAST

max_issues_repo_name: ancorso/MAST


text:
"""
    candlestick(dt, open, close, low, high)

Creates an `EChart` for visualizing financial prices of a security.

## Methods
```julia
candlestick(dt::AbstractVector{String},
            open::AbstractVector{<:Union{Missing, Real}},
            close::AbstractVector{<:Union{Missing, Real}},
            low::AbstractVector{<:Union{Missing, Real}},
            high::AbstractVector{<:Union{Missing, Real}})

candlestick(dt::AbstractVector{<:Dates.TimeType},
            open::AbstractVector{<:Union{Missing, Real}},
            close::AbstractVector{<:Union{Missing, Real}},
            low::AbstractVector{<:Union{Missing, Real}},
            high::AbstractVector{<:Union{Missing, Real}})
```

## Arguments
* `legend::Bool` : display legend?
* `scale::Bool = false` : show full Y-axis or truncated
* `kwargs` : varargs to set any field of resulting `EChart` struct

## Notes

Candlestick plots are financial plots showing the relationship between the open, close, low and high prices for a security on a given day. For a more thorough description of the uses and subtleties of candlestick plots, see: [http://www.datavizcatalogue.com/methods/candlestick_chart.html](http://www.datavizcatalogue.com/methods/candlestick_chart.html)

## Examples
```julia
dt = ["2016/08/26", "2016/08/29", "2016/08/30", "2016/08/31", "2016/09/01", "2016/09/02",
"2016/09/06", "2016/09/07", "2016/09/08", "2016/09/09", "2016/09/12", "2016/09/13",
"2016/09/14", "2016/09/15", "2016/09/16", "2016/09/19", "2016/09/20", "2016/09/21",
"2016/09/22", "2016/09/23", "2016/09/26"]

close_ = [12.38, 12.47, 12.55, 12.60, 12.44, 12.50, 12.67, 12.70, 12.73, 12.38, 12.70, 12.38, 12.14, 12.11, 12.11, 12.11, 12.00, 12.09, 12.18, 12.17, 12.01]

open_ = [12.47, 12.38, 12.46, 12.48, 12.66, 12.53, 12.49, 12.62, 12.50, 12.61, 12.32, 12.53, 12.18, 12.14, 12.05, 12.12, 12.09, 12.08, 12.17, 12.12, 12.12]

high_ = [12.55, 12.50, 12.56, 12.61, 12.72, 12.57, 12.67, 12.75, 12.75, 12.6850, 12.77, 12.68, 12.31, 12.18, 12.13, 12.33, 12.19, 12.11, 12.29, 12.22, 12.12]

low_ = [12.34, 12.38, 12.43, 12.48, 12.35, 12.46, 12.43, 12.62, 12.50, 12.38, 12.28, 12.33,12.11, 12.06, 12.01, 12.0586, 11.96, 12.01, 12.16, 12.12, 12.00]

c = candlestick(dt, open_, close_, low_, high_)
```
"""
function candlestick(dt::AbstractVector{String},
                     open::AbstractVector{<:Union{Missing, Real}},
                     close::AbstractVector{<:Union{Missing, Real}},
                     low::AbstractVector{<:Union{Missing, Real}},
                     high::AbstractVector{<:Union{Missing, Real}};
                     legend::Bool = false,
                     scale::Bool = true,
                     kwargs...)

    #Put in array of array format
    fmtdata = []
    for (o,c,l,h) in zip(open, close, low, high)
        push!(fmtdata, [o,c,l,h])
    end

    ec = newplot(kwargs, ec_charttype = "candlestick")
    ec.xAxis = [Axis(_type = "category", data = dt, scale = true, boundaryGap = true)]
    ec.yAxis = [Axis(scale = scale)]
    ec.series = [CandleStickSeries(name = "Series 1", data = fmtdata)]

    #Add legend if requested
    legend ? legend!(ec) : nothing

    return ec

end

candlestick(dt::AbstractVector{<:Dates.TimeType},
                     open::AbstractVector{<:Union{Missing, Real}},
                     close::AbstractVector{<:Union{Missing, Real}},
                     low::AbstractVector{<:Union{Missing, Real}},
                     high::AbstractVector{<:Union{Missing, Real}};
                     legend::Bool = false,
                     scale::Bool = true,
                     kwargs...) = candlestick(string.(dt), open, close, low, high; legend = legend, scale = scale, kwargs...)


text:
module DB2

using DataFrames, StatsBase

export personGenerator, calculatePremiums

premiums_df = DataFrame(State = String[],
                          Catastrophic = Int64[],
                          Bronze = Int64[],
                          Silver = Int64[],
                          Gold = Int64[],
                          Platinum = Int64[],
                          Suburban_penalty = Float32[],
                          Rural_Penalty = Float32[],
                          Tobacco_penalty = Float32[],
                          Population = Int64[])

push!(premiums_df, ["Alabama",193,217,269,314,371,1,1,1.5,4871547])
push!(premiums_df, ["Alaska",364,475,583,689,689,1,1,1.5,739818])
push!(premiums_df, ["Arizona",169,229,279,319,334,1,1.7,1.5,6927347])
push!(premiums_df, ["Arkansas",191,255,326,375,375,1.1,1,1.5,2989573])
push!(premiums_df, ["California",223,249,300,358,407,1.4,1.3,1,39497345])
push!(premiums_df, ["Colorado",222,262,323,366,405,0.9,1.3,1.5,5557560])
push!(premiums_df, ["Connecticut",217,290,372,411,490,1.2,1,1.5,3587010])
push!(premiums_df, ["Delaware",219,252,324,370,439,1,1,1.5,955900])
push!(premiums_df, ["District of Columbia",175,228,294,361,440,1,1,1,684620])
push!(premiums_df, ["Florida",249,303,369,419,487,1.2,1.1,1.5,20636975])
push!(premiums_df, ["Georgia",208,247,307,365,443,1,1.1,1.5,10332588])
push!(premiums_df, ["Hawaii",155,171,206,252,318,1,1,1.5,1442949])
push!(premiums_df, ["Idaho",210,238,289,342,406,1.1,1.2,1.5,1675054])
push!(premiums_df, ["Illinois" ,210,238,289,342,406,1.1,1.2,1.5,12837801])
push!(premiums_df, ["Indiana",232,286,352,425,647,0.9,0.8,1.5,6641480])
push!(premiums_df, ["Iowa",240,246,310,364,524,0.8,1.2,1.5,3138317])
push!(premiums_df, ["Kansas",158,205,245,286,341,1,1,1.5,2920775])
push!(premiums_df, ["Kentucky",181,220,277,326,345,1.2,1.2,1.5,4437567])
push!(premiums_df, ["Louisiana",209,274,359,411,454,1,1.1,1.5,4692458])
push!(premiums_df, ["Maine",205,272,342,425,425,1.2,1.1,1.5,1328400])
push!(premiums_df, ["Maryland",174,207,269,317,385,1,1,1.5,6037456])
push!(premiums_df, ["Massachusetts",254,288,345,440,526,1,1,1,6833720])
push!(premiums_df, ["Michigan",197,252,305,371,412,1,1.1,1.5,9928846])
push!(premiums_df, ["Minnesota",142,195,232,284,312,1.1,1.5,1.5,5522063])
push!(premiums_df, ["Mississippi",238,243,315,353,384,1.1,1,1.5,2991223])
push!(premiums_df, ["Missouri",216,245,306,358,330,0.9,1.1,1.5,6103517])
push!(premiums_df, ["Montana",185,226,273,331,384,1,1,1.5,1042646])
push!(premiums_df, ["Nebraska",206,261,319,375,514,1,1,1.5,1909400])
push!(premiums_df, ["Nevada",220,247,284,321,364,1.3,1.8,1.5,2943409])
push!(premiums_df, ["New Hampshire",194,254,329,400,665,1,1,1.5,1333220])
push!(premiums_df, ["New Jersey",272,327,360,454,554,1,1,1,8977182])
push!(premiums_df, ["New Mexico",185,205,253,302,384,1.2,1.4,1.5,2084651])
push!(premiums_df, ["New York",267,333,368,471,540,1,1,1,19842724])
push!(premiums_df, ["North Carolina" ,206,270,343,396,447,1,1,1.5,10145217])
push!(premiums_df, ["North Dakota",189,263,318,365,365,1.1,1.1,1.5,773814])
push!(premiums_df, ["Ohio",196,258,321,373,540,1.1,1.1,1.5,11629848])
push!(premiums_df, ["Oklahoma",173,220,287,359,504,1,1,1.5,3943066])
push!(premiums_df, ["Oregon",201,212,262,310,366,1.1,1.1,1.5,4086752])
push!(premiums_df, ["Pennsylvania",194,261,313,354,454,0.9,0.8,1.5,12811239])
push!(premiums_df, ["Rhode Island",199,228,284,340,340,1,1,1,1057689])
push!(premiums_df, ["South Carolina",207,268,308,365,684,1,1,1.5,4963132])
push!(premiums_df, ["South Dakota",203,243,289,368,421,1.1,1,1.5,863634])
push!(premiums_df, ["Tennessee",171,200,258,344,438,0.9,1,1.5,6652819])
push!(premiums_df, ["Texas",248,269,328,388,493,0.8,0.9,1.5,27959150])
push!(premiums_df, ["Utah",197,207,256,299,272,1.1,1.1,1.5,3047340])
push!(premiums_df, ["Vermont",223,383,455,546,635,1,1,1,625317])
push!(premiums_df, ["Virginia",193,246,307,375,517,1,1,1.5,8437888])
push!(premiums_df, ["Washington",229,242,305,364,420,1.1,1,1.5,7277536])
push!(premiums_df, ["West Virginia",217,241,289,350,350,1.1,1.1,1.5,1839505])
push!(premiums_df, ["Wisconsin",228,308,373,447,564,0.9,0.8,1.5,5783242])
push!(premiums_df, ["Wyoming" ,336,394,456,537,580,1,1.1,1.5,587910])

function personGenerator(n::Int64)
    output_df = DataFrame(First_name = String[],
                          Last_name = String[],
                          Age = Float32[],
                          Gender = String[],
                          Income = Float32[],
                          State = String[],
                          Urban_rural = String[],
                          Tobacco_use = String[],
                          Family_individual = String[],
                          Plan_level = String[],
                          Existing_plan = String[],
                          Last_paid = Date[])
    for i = 1:n
        first = randstring()
        last = randstring()
        age = 50+randn()*15
        while (age < 20) | (age > 85)
            age = 50+randn()*15
        end
        gender = sample(["M", "F"], WeightVec([49.2, 50.8]))
        income = max(age*1000+randn()*10000,0)
        state = sample(premiums_df[:State], WeightVec(premiums_df[:Population]))
        urbanRural = sample(["Urban", "Suburban", "Rural"], WeightVec([26, 53, 21]))
        tobaccoChance = 19
        if (age < 25) | (age > 65)
            if gender == "M"
                tobaccoChance = 14
            else
                tobaccoChance = 11
            end
        else
            if gender == "F"
                tobaccoChance = 16
            end
        end
        tobacco = sample(["Yes", "No"], WeightVec([tobaccoChance, 100-tobaccoChance]))
        familyChance = max(0, min(100, income/1000))
        family = sample(["Family", "Individual"], WeightVec([familyChance, 100-familyChance]))
        plan = sample(["Bronze", "Silver", "Gold", "Platinum", "Catastrophic"])
        existingPlan = sample(["Yes", "No"])
        lastPaid = NA
        if existingPlan == "Yes"
            lastPaid = Date(rand(2014:2016),rand(1:12),rand(1:28))
        end

        push!(output_df,
              [first, last, age, gender, income, state,
              urbanRural, tobacco, family, plan, existingPlan, lastPaid])
    end

    return output_df
end

function calculatePremiums(input_df)

    function premiumCalculation(age, state, urbanRural, tobacco, family, plan)
        #Get my state info
        stateID = find(x->x==state,premiums_df[:State])
        if length(stateID)==1
            stateID = stateID[1]
        else
            stateID = 0
        end

        # Pulls the premium from your state and plan type
        basePremium = 0
        if stateID > 0
            if plan == "Bronze"
                basePremium = premiums_df[stateID, 3][1]
            elseif plan == "Silver"
                basePremium = premiums_df[stateID, 4][1]
            elseif plan == "Gold"
                basePremium = premiums_df[stateID, 5][1]
            elseif plan == "Platinum"
                basePremium = premiums_df[stateID, 6][1]
            elseif plan =="Catastrophic"
                basePremium = premiums_df[stateID, 2][1]
            end
        end

        # Adjusts premium for rural/suburban location
        premium = 0
        if urbanRural == "Suburban"
            premium = basePremium*premiums_df[stateID, 7][1]
        elseif urbanRural == "Rural"
            premium = basePremium*premiums_df[stateID, 8][1]
        elseif urbanRural == "Urban"
            premium = basePremium
        end

        # Adjusts premium for smokers
        if tobacco
             premium = premium*premiums_df[stateID, 9][1]
        end

        # Doubles premium if it's for a family
        if family
             premium = premium*2
        end

        # Adjusts premium for age
        ageMultiplier = 1
        newage = min(64, max(19, age))
        if age > 40
            ageMultiplier = 1 + 0.00285*(age-40)^2
        else
            ageMultiplier = 1 - .025*(40-age)
        end
        premium = premium*ageMultiplier

        #Finally, round
        premium = round(premium,2)
        return premium
    end

    numRecords = size(input_df,1)
    premiumOutput = zeros(numRecords)
    for i = 1:numRecords
        age = input_df[i,:Age]
        state = input_df[i,:State]
        urbanRural = input_df[i,:Urban_rural]
        tobacco = false
        if input_df[i,:Tobacco_use]=="Yes" tobacco = true end
        family = false
        if input_df[i,:Family_individual]=="Family" family = true end
        plan = input_df[i,:Plan_level]
        premiumOutput[i] = premiumCalculation(age, state, urbanRural, tobacco, family, plan)
    end

    return premiumOutput
end

#Importing claim history
# claimHeader = ["Date"  "Proivder" "Claim type" "Pre-authorization" "Dollar amount"]
# claim1 = [Date(2016,2,1) "MIT Medical" "Adult well visit" false 100]
# claim2 = [Date(2016,4,1) "Harvard Vanguard" "Urgent care" false 100]
# claim3 = [Date(2016,9,1) "Great Hill Dental" "Annual dental visit" false 200]
# claims = [claim1; claim2; claim3]

###### Starting claim acceptance model
# accept = true

# If claim type not covered by plan level, reject
# Need to compile a document that lists possible claims and what is covered by what level

# Reject if not pre-authorized for CT, MRI

# Reject if out-of-network provider

# Reject if more claims in the last 3 months than previous 12

# Reject if more cost in last 3 months than previous 12

# Reject if two claims in a red zone category

# Reject if two months or more late on premium payments

end # module


text:
"""
	isapprox(a::AbstractPoint2D, b::AbstractPoint2D) -> Bool

Test if the two points `a` and `b` are approximately equal in the `l1`-norm.
"""
function Base.isapprox(a::VoronoiDelaunay.AbstractPoint2D, b::VoronoiDelaunay.AbstractPoint2D)
	isapprox(getx(a), getx(b)) && isapprox(gety(a), gety(b))
end

"""
	contains(pts::AbstractPoints2D, p::AbstractPoint2D) -> Bool

Test if the point `p` is in the vector of points `pts`.
"""
function contains(pts::Vector{<:VoronoiDelaunay.AbstractPoint2D}, p::VoronoiDelaunay.AbstractPoint2D)
	for element in pts
		if isapprox(p, element)
			return true
		end
	end
	return false
end

"""
	dist_squared(p, q) -> Real

The `l2` distance squared between the points `p` and `q`.
"""
function dist_squared(p::VoronoiDelaunay.AbstractPoint2D, q::VoronoiDelaunay.AbstractPoint2D)
	(getx(p)-getx(q))^2 + (gety(p)-gety(q))^2
end

"""
	quadrant(p::AbstractPoint2D)

Get the quadrant number of `p`.

The quadrants are numbered in the usual way, starting with 1 in the upper
right and consecutively with positive orientation:

* 1 is the upper right
* 2 is the upper left
* 3 is the lower left
* 4 is the lower right
"""
function quadrant(p::VoronoiDelaunay.AbstractPoint2D)
	isleft = getx(p) < MIDDLEx
	islow = gety(p) < MIDDLEy

	if !islow && !isleft
		Q = 1
	elseif !islow && isleft
		Q = 2
	elseif islow && isleft
		Q = 3
	elseif islow && !isleft
		Q = 4
	end

	return Q
end

"""
	fit2boundingbox(x::Vector, y::Vector; ...) -> Points2D, Float, Float

Scale `x` and `y` to be in the GeometricalPredicates window [1,2]x[1,2].
Return a vector of `Point2D`'s and the scaling factors applied in each
dimension.

As an optional argument the bounding box of `x` and `y` can be changed
from the unit square.
"""
function fit2boundingbox(x::AbstractVector{Float64}, y::AbstractVector{Float64}, rw::Vector{Float64}=[0.0;1.0;0.0;1.0])
	(N = length(x)) == length(y) || throw(DimensionMismatch())

	RW_LEFT = rw[1]
	RW_LOWER = rw[3]
	minimum(x) >= RW_LEFT && maximum(x) <= rw[2] && minimum(y) >= RW_LOWER && maximum(y) <= rw[4] || throw(DomainError(x))

	SCALEX = rw[2] - RW_LEFT
	SCALEY = rw[4] - RW_LOWER

	pts = [IndexablePoint2D( LEFT + (x[n]-RW_LEFT)/SCALEX, LOWER + (y[n]-RW_LOWER)/SCALEY, n) for n = 1:N]

	return pts, SCALEX, SCALEY
end


text:
###########################################################
### Manifold Gradient
###########################################################
struct ManifoldIdentity <: ManifoldUpdate
end

struct ManifoldIdentityState
end

initial_state(::ManifoldIdentity, x, reg) = ManifoldIdentityState()

Base.summary(o::ManifoldIdentity) = "ManIdentity"

str_updatelog(::ManifoldIdentity, ::ManifoldIdentityState) = ""

function update_iterate!(state::PartlySmoothOptimizerState, pb, ::ManifoldIdentity)

    return
end


text:
@testset "wat2wasm" begin
    exception = try
        wat"invalid wasm code"
    catch e
        e
    end

    exception_msg = string(exception)
    @test occursin("invalid wasm code", exception_msg)
end

@testset "Basic export" begin
    wasm_code = wat"""
        (module
            (type $sum_t (func (param i32 i32) (result i32)))
            (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32)
            local.get $x
            local.get $y
            i32.add)
            (export "sum" (func $sum_f)))
    """

    engine = WasmEngine()
    store = WasmStore(engine)
    wasm_module = WasmModule(store, wasm_code)
    instance = WasmInstance(store, wasm_module)
    wasm_exports = exports(instance)
    sum_function = wasm_exports.sum

    result, = sum_function(Int32(2), Int32(2))
    result = Base.convert(Int32, result)

    @test result == Int32(4)
end


text:
using Dates
using Distributions

@testset "Black Scholes" begin
    #start_time = now()
    #end_time = now()
    run_with_job("Black Scholes with Banyan") do job
        # size = 256_000_000  ##512000000  # 256000000
        size = 128_000_000
        # NOTE: 64M works but 128M doesn't (and also doesn't batch the I/O)
        price = BanyanArrays.fill(4.0, size)
        strike = BanyanArrays.fill(4.0, size)
        t = BanyanArrays.fill(4.0, size)
        rate = BanyanArrays.fill(4.0, size)
        vol = BanyanArrays.fill(4.0, size)

        d1 = map(
            (p, s, t, r, v) ->
                ((log(p / s) + (r + v ^ 2 * 0.5) * t) / (v * sqrt(t))),
            price,
            strike,
            t,
            rate,
            vol,
        )

        d2 = map((d1, v, t) -> (d1 - (v * sqrt(t))), d1, vol, t)

        call = map(
            (d1, d2, p, s, t, r) ->
                ((cdf(Normal(), d1) * p) - (cdf(Normal(), d2) * s * exp(-r * t))),
            d1,
            d2,
            price,
            strike,
            t,
            rate,
        )

        call_sum = sum(call)
        call = nothing
        res = collect(call_sum)
	    # println(res)
        @show res
        #res = collect(res)
        #end = now()
        #@test typeof(res) == Base.Vector{Float64}
        #@test all(v->v==3.999999985812889, res)
    end
    #end_time = now()
    #println(end_time - start_time)
end

@testset "Black Scholes" begin
    run_without_job("Black Scholes without Banyan") do job
        size = 128  #256000000
        price = Base.fill(4.0, size)
        strike = Base.fill(4.0, size)
        t = Base.fill(4.0, size)
        rate = Base.fill(4.0, size)
        vol = Base.fill(4.0, size)

        d1 = Base.map(
                (p, s, t, r, v)->(
                        (log(p / s) + (r + v ^ 2 * 0.5) * t) / (v * sqrt(t))
                ),
                price,
                strike,
                t,
                rate,
                vol
        )

        d2 = Base.map(
                (d1, v, t)->(
                        d1 - (v * sqrt(t))
                ),
                d1,
                vol,
                t
        )

        call = Base.map(
                  (d1, d2, p, s, t, r)->(
                        (cdf(Normal(), d1) * p) - (cdf(Normal(), d2) * s * exp(-r * t))
                  ),
                  d1,
                  d2,
                  price,
                  strike,
                  t,
                  rate
        )

        call_sum = Base.sum(call)
        res = Base.collect(call_sum)
        println(res)
        # @test typeof(res) == Base.Vector{Float64}
        # @test all(v->v==3.999999985812889, res)
    end
end

@testset "Black Scholes" begin
    run_without_job("Black Scholes without Banyan vectorized") do job
        size = 128  #256000000
        price = Base.fill(4.0, size)
        strike = Base.fill(4.0, size)
        t = Base.fill(4.0, size)
        rate = Base.fill(4.0, size)
        vol = Base.fill(4.0, size)

        d1 = (log.(price ./ strike) .+ (rate .+ vol .^ 2 .* 0.5) .* t) ./ (vol .* sqrt.(t))

        d2 = d1 .- (vol .* sqrt.(t))

        call = (cdf.(Normal(), d1) .* price) - (cdf.(Normal(), d2) .* strike .* exp.(-rate .* t))

        call_sum = Base.sum(call)
        res = Base.collect(call_sum)
        println(res)

    end
end

max_stars_repo_name: banyan-team/banyan-julia

max_issues_repo_name: banyan-team/banyan-julia

max_forks_repo_name: banyan-team/banyan-julia


text:
#
# Autogenerated by Thrift Compiler (0.11.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
# COV_EXCL_START

struct _enum__Type
  BOOLEAN::Int32
  INT32::Int32
  INT64::Int32
  INT96::Int32
  FLOAT::Int32
  DOUBLE::Int32
  BYTE_ARRAY::Int32
  FIXED_LEN_BYTE_ARRAY::Int32
end
const _Type = _enum__Type(Int32(0), Int32(1), Int32(2), Int32(3), Int32(4), Int32(5), Int32(6), Int32(7))

struct _enum_ConvertedType
  UTF8::Int32
  MAP::Int32
  MAP_KEY_VALUE::Int32
  LIST::Int32
  ENUM::Int32
  DECIMAL::Int32
  DATE::Int32
  TIME_MILLIS::Int32
  TIME_MICROS::Int32
  TIMESTAMP_MILLIS::Int32
  TIMESTAMP_MICROS::Int32
  UINT_8::Int32
  UINT_16::Int32
  UINT_32::Int32
  UINT_64::Int32
  INT_8::Int32
  INT_16::Int32
  INT_32::Int32
  INT_64::Int32
  JSON::Int32
  BSON::Int32
  INTERVAL::Int32
end
const ConvertedType = _enum_ConvertedType(Int32(0), Int32(1), Int32(2), Int32(3), Int32(4), Int32(5), Int32(6), Int32(7), Int32(8), Int32(9), Int32(10), Int32(11), Int32(12), Int32(13), Int32(14), Int32(15), Int32(16), Int32(17), Int32(18), Int32(19), Int32(20), Int32(21))

struct _enum_FieldRepetitionType
  REQUIRED::Int32
  OPTIONAL::Int32
  REPEATED::Int32
end
const FieldRepetitionType = _enum_FieldRepetitionType(Int32(0), Int32(1), Int32(2))

struct _enum_Encoding
  PLAIN::Int32
  PLAIN_DICTIONARY::Int32
  RLE::Int32
  BIT_PACKED::Int32
  DELTA_BINARY_PACKED::Int32
  DELTA_LENGTH_BYTE_ARRAY::Int32
  DELTA_BYTE_ARRAY::Int32
  RLE_DICTIONARY::Int32
  BYTE_STREAM_SPLIT::Int32
end
const Encoding = _enum_Encoding(Int32(0), Int32(2), Int32(3), Int32(4), Int32(5), Int32(6), Int32(7), Int32(8), Int32(9))

struct _enum_CompressionCodec
  UNCOMPRESSED::Int32
  SNAPPY::Int32
  GZIP::Int32
  LZO::Int32
  BROTLI::Int32
  LZ4::Int32
  ZSTD::Int32
end
const CompressionCodec = _enum_CompressionCodec(Int32(0), Int32(1), Int32(2), Int32(3), Int32(4), Int32(5), Int32(6))

struct _enum_PageType
  DATA_PAGE::Int32
  INDEX_PAGE::Int32
  DICTIONARY_PAGE::Int32
  DATA_PAGE_V2::Int32
end
const PageType = _enum_PageType(Int32(0), Int32(1), Int32(2), Int32(3))

struct _enum_BoundaryOrder
  UNORDERED::Int32
  ASCENDING::Int32
  DESCENDING::Int32
end
const BoundaryOrder = _enum_BoundaryOrder(Int32(0), Int32(1), Int32(2))

mutable struct Statistics <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function Statistics(; kwargs...)
    obj = new(__meta__Statistics, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct Statistics

const __meta__Statistics = meta(Statistics,
  Symbol[:max,:min,:null_count,:distinct_count,:max_value,:min_value],
  Type[Vector{UInt8},Vector{UInt8},Int64,Int64,Vector{UInt8},Vector{UInt8}],
  Symbol[:max,:min,:null_count,:distinct_count,:max_value,:min_value],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::Statistics, name::Symbol)
  if name === :max
    return (obj.values[name])::Vector{UInt8}
  elseif name === :min
    return (obj.values[name])::Vector{UInt8}
  elseif name === :null_count
    return (obj.values[name])::Int64
  elseif name === :distinct_count
    return (obj.values[name])::Int64
  elseif name === :max_value
    return (obj.values[name])::Vector{UInt8}
  elseif name === :min_value
    return (obj.values[name])::Vector{UInt8}
  else
    getfield(obj, name)
  end
end

meta(::Type{Statistics}) = __meta__Statistics

mutable struct StringType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function StringType(; kwargs...)
    obj = new(__meta__StringType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct StringType

const __meta__StringType = meta(StringType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{StringType}) = __meta__StringType

mutable struct UUIDType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function UUIDType(; kwargs...)
    obj = new(__meta__UUIDType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct UUIDType

const __meta__UUIDType = meta(UUIDType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{UUIDType}) = __meta__UUIDType

mutable struct MapType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function MapType(; kwargs...)
    obj = new(__meta__MapType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct MapType

const __meta__MapType = meta(MapType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{MapType}) = __meta__MapType

mutable struct ListType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function ListType(; kwargs...)
    obj = new(__meta__ListType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct ListType

const __meta__ListType = meta(ListType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{ListType}) = __meta__ListType

mutable struct EnumType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function EnumType(; kwargs...)
    obj = new(__meta__EnumType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct EnumType

const __meta__EnumType = meta(EnumType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{EnumType}) = __meta__EnumType

mutable struct DateType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function DateType(; kwargs...)
    obj = new(__meta__DateType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct DateType

const __meta__DateType = meta(DateType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{DateType}) = __meta__DateType

mutable struct NullType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function NullType(; kwargs...)
    obj = new(__meta__NullType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct NullType

const __meta__NullType = meta(NullType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{NullType}) = __meta__NullType

mutable struct DecimalType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function DecimalType(; kwargs...)
    obj = new(__meta__DecimalType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct DecimalType

const __meta__DecimalType = meta(DecimalType,
  Symbol[:scale,:precision],
  Type[Int32,Int32],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::DecimalType, name::Symbol)
  if name === :scale
    return (obj.values[name])::Int32
  elseif name === :precision
    return (obj.values[name])::Int32
  else
    getfield(obj, name)
  end
end

meta(::Type{DecimalType}) = __meta__DecimalType

mutable struct MilliSeconds <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function MilliSeconds(; kwargs...)
    obj = new(__meta__MilliSeconds, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct MilliSeconds

const __meta__MilliSeconds = meta(MilliSeconds,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{MilliSeconds}) = __meta__MilliSeconds

mutable struct MicroSeconds <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function MicroSeconds(; kwargs...)
    obj = new(__meta__MicroSeconds, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct MicroSeconds

const __meta__MicroSeconds = meta(MicroSeconds,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{MicroSeconds}) = __meta__MicroSeconds

mutable struct NanoSeconds <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function NanoSeconds(; kwargs...)
    obj = new(__meta__NanoSeconds, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct NanoSeconds

const __meta__NanoSeconds = meta(NanoSeconds,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{NanoSeconds}) = __meta__NanoSeconds

mutable struct TimeUnit <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function TimeUnit(; kwargs...)
    obj = new(__meta__TimeUnit, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct TimeUnit

const __meta__TimeUnit = meta(TimeUnit,
  Symbol[:MILLIS,:MICROS,:NANOS],
  Type[MilliSeconds,MicroSeconds,NanoSeconds],
  Symbol[:MILLIS,:MICROS,:NANOS],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::TimeUnit, name::Symbol)
  if name === :MILLIS
    return (obj.values[name])::MilliSeconds
  elseif name === :MICROS
    return (obj.values[name])::MicroSeconds
  elseif name === :NANOS
    return (obj.values[name])::NanoSeconds
  else
    getfield(obj, name)
  end
end

meta(::Type{TimeUnit}) = __meta__TimeUnit

mutable struct TimestampType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function TimestampType(; kwargs...)
    obj = new(__meta__TimestampType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct TimestampType

const __meta__TimestampType = meta(TimestampType,
  Symbol[:isAdjustedToUTC,:unit],
  Type[Bool,TimeUnit],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::TimestampType, name::Symbol)
  if name === :isAdjustedToUTC
    return (obj.values[name])::Bool
  elseif name === :unit
    return (obj.values[name])::TimeUnit
  else
    getfield(obj, name)
  end
end

meta(::Type{TimestampType}) = __meta__TimestampType

mutable struct TimeType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function TimeType(; kwargs...)
    obj = new(__meta__TimeType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct TimeType

const __meta__TimeType = meta(TimeType,
  Symbol[:isAdjustedToUTC,:unit],
  Type[Bool,TimeUnit],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::TimeType, name::Symbol)
  if name === :isAdjustedToUTC
    return (obj.values[name])::Bool
  elseif name === :unit
    return (obj.values[name])::TimeUnit
  else
    getfield(obj, name)
  end
end

meta(::Type{TimeType}) = __meta__TimeType

mutable struct IntType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function IntType(; kwargs...)
    obj = new(__meta__IntType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct IntType

const __meta__IntType = meta(IntType,
  Symbol[:bitWidth,:isSigned],
  Type[UInt8,Bool],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::IntType, name::Symbol)
  if name === :bitWidth
    return (obj.values[name])::UInt8
  elseif name === :isSigned
    return (obj.values[name])::Bool
  else
    getfield(obj, name)
  end
end

meta(::Type{IntType}) = __meta__IntType

mutable struct JsonType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function JsonType(; kwargs...)
    obj = new(__meta__JsonType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct JsonType

const __meta__JsonType = meta(JsonType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{JsonType}) = __meta__JsonType

mutable struct BsonType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function BsonType(; kwargs...)
    obj = new(__meta__BsonType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct BsonType

const __meta__BsonType = meta(BsonType,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{BsonType}) = __meta__BsonType

mutable struct LogicalType <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function LogicalType(; kwargs...)
    obj = new(__meta__LogicalType, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct LogicalType

const __meta__LogicalType = meta(LogicalType,
  Symbol[:STRING,:MAP,:LIST,:ENUM,:DECIMAL,:DATE,:TIME,:TIMESTAMP,:INTEGER,:UNKNOWN,:JSON,:BSON,:UUID],
  Type[StringType,MapType,ListType,EnumType,DecimalType,DateType,TimeType,TimestampType,IntType,NullType,JsonType,BsonType,UUIDType],
  Symbol[:STRING,:MAP,:LIST,:ENUM,:DECIMAL,:DATE,:TIME,:TIMESTAMP,:INTEGER,:UNKNOWN,:JSON,:BSON,:UUID],
  Int[1,2,3,4,5,6,7,8,10,11,12,13,14],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::LogicalType, name::Symbol)
  if name === :STRING
    return (obj.values[name])::StringType
  elseif name === :MAP
    return (obj.values[name])::MapType
  elseif name === :LIST
    return (obj.values[name])::ListType
  elseif name === :ENUM
    return (obj.values[name])::EnumType
  elseif name === :DECIMAL
    return (obj.values[name])::DecimalType
  elseif name === :DATE
    return (obj.values[name])::DateType
  elseif name === :TIME
    return (obj.values[name])::TimeType
  elseif name === :TIMESTAMP
    return (obj.values[name])::TimestampType
  elseif name === :INTEGER
    return (obj.values[name])::IntType
  elseif name === :UNKNOWN
    return (obj.values[name])::NullType
  elseif name === :JSON
    return (obj.values[name])::JsonType
  elseif name === :BSON
    return (obj.values[name])::BsonType
  elseif name === :UUID
    return (obj.values[name])::UUIDType
  else
    getfield(obj, name)
  end
end

meta(::Type{LogicalType}) = __meta__LogicalType

mutable struct SchemaElement <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function SchemaElement(; kwargs...)
    obj = new(__meta__SchemaElement, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct SchemaElement

const __meta__SchemaElement = meta(SchemaElement,
  Symbol[:_type,:type_length,:repetition_type,:name,:num_children,:converted_type,:scale,:precision,:field_id,:logicalType],
  Type[Int32,Int32,Int32,String,Int32,Int32,Int32,Int32,Int32,LogicalType],
  Symbol[:_type,:type_length,:repetition_type,:num_children,:converted_type,:scale,:precision,:field_id,:logicalType],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::SchemaElement, name::Symbol)
  if name === :_type
    return (obj.values[name])::Int32
  elseif name === :type_length
    return (obj.values[name])::Int32
  elseif name === :repetition_type
    return (obj.values[name])::Int32
  elseif name === :name
    return (obj.values[name])::String
  elseif name === :num_children
    return (obj.values[name])::Int32
  elseif name === :converted_type
    return (obj.values[name])::Int32
  elseif name === :scale
    return (obj.values[name])::Int32
  elseif name === :precision
    return (obj.values[name])::Int32
  elseif name === :field_id
    return (obj.values[name])::Int32
  elseif name === :logicalType
    return (obj.values[name])::LogicalType
  else
    getfield(obj, name)
  end
end

meta(::Type{SchemaElement}) = __meta__SchemaElement

mutable struct DataPageHeader <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function DataPageHeader(; kwargs...)
    obj = new(__meta__DataPageHeader, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct DataPageHeader

const __meta__DataPageHeader = meta(DataPageHeader,
  Symbol[:num_values,:encoding,:definition_level_encoding,:repetition_level_encoding,:statistics],
  Type[Int32,Int32,Int32,Int32,Statistics],
  Symbol[:statistics],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::DataPageHeader, name::Symbol)
  if name === :num_values
    return (obj.values[name])::Int32
  elseif name === :encoding
    return (obj.values[name])::Int32
  elseif name === :definition_level_encoding
    return (obj.values[name])::Int32
  elseif name === :repetition_level_encoding
    return (obj.values[name])::Int32
  elseif name === :statistics
    return (obj.values[name])::Statistics
  else
    getfield(obj, name)
  end
end

meta(::Type{DataPageHeader}) = __meta__DataPageHeader

mutable struct IndexPageHeader <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function IndexPageHeader(; kwargs...)
    obj = new(__meta__IndexPageHeader, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct IndexPageHeader

const __meta__IndexPageHeader = meta(IndexPageHeader,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{IndexPageHeader}) = __meta__IndexPageHeader

mutable struct DictionaryPageHeader <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function DictionaryPageHeader(; kwargs...)
    obj = new(__meta__DictionaryPageHeader, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct DictionaryPageHeader

const __meta__DictionaryPageHeader = meta(DictionaryPageHeader,
  Symbol[:num_values,:encoding,:is_sorted],
  Type[Int32,Int32,Bool],
  Symbol[:is_sorted],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::DictionaryPageHeader, name::Symbol)
  if name === :num_values
    return (obj.values[name])::Int32
  elseif name === :encoding
    return (obj.values[name])::Int32
  elseif name === :is_sorted
    return (obj.values[name])::Bool
  else
    getfield(obj, name)
  end
end

meta(::Type{DictionaryPageHeader}) = __meta__DictionaryPageHeader

mutable struct DataPageHeaderV2 <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function DataPageHeaderV2(; kwargs...)
    obj = new(__meta__DataPageHeaderV2, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct DataPageHeaderV2

const __meta__DataPageHeaderV2 = meta(DataPageHeaderV2,
  Symbol[:num_values,:num_nulls,:num_rows,:encoding,:definition_levels_byte_length,:repetition_levels_byte_length,:is_compressed,:statistics],
  Type[Int32,Int32,Int32,Int32,Int32,Int32,Bool,Statistics],
  Symbol[:is_compressed,:statistics],
  Int[],
  Dict{Symbol,Any}(:is_compressed => true)
)

function Base.getproperty(obj::DataPageHeaderV2, name::Symbol)
  if name === :num_values
    return (obj.values[name])::Int32
  elseif name === :num_nulls
    return (obj.values[name])::Int32
  elseif name === :num_rows
    return (obj.values[name])::Int32
  elseif name === :encoding
    return (obj.values[name])::Int32
  elseif name === :definition_levels_byte_length
    return (obj.values[name])::Int32
  elseif name === :repetition_levels_byte_length
    return (obj.values[name])::Int32
  elseif name === :is_compressed
    return (obj.values[name])::Bool
  elseif name === :statistics
    return (obj.values[name])::Statistics
  else
    getfield(obj, name)
  end
end

meta(::Type{DataPageHeaderV2}) = __meta__DataPageHeaderV2

mutable struct SplitBlockAlgorithm <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function SplitBlockAlgorithm(; kwargs...)
    obj = new(__meta__SplitBlockAlgorithm, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct SplitBlockAlgorithm

const __meta__SplitBlockAlgorithm = meta(SplitBlockAlgorithm,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{SplitBlockAlgorithm}) = __meta__SplitBlockAlgorithm

mutable struct BloomFilterAlgorithm <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function BloomFilterAlgorithm(; kwargs...)
    obj = new(__meta__BloomFilterAlgorithm, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct BloomFilterAlgorithm

const __meta__BloomFilterAlgorithm = meta(BloomFilterAlgorithm,
  Symbol[:BLOCK],
  Type[SplitBlockAlgorithm],
  Symbol[:BLOCK],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::BloomFilterAlgorithm, name::Symbol)
  if name === :BLOCK
    return (obj.values[name])::SplitBlockAlgorithm
  else
    getfield(obj, name)
  end
end

meta(::Type{BloomFilterAlgorithm}) = __meta__BloomFilterAlgorithm

mutable struct XxHash <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function XxHash(; kwargs...)
    obj = new(__meta__XxHash, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct XxHash

const __meta__XxHash = meta(XxHash,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{XxHash}) = __meta__XxHash

mutable struct BloomFilterHash <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function BloomFilterHash(; kwargs...)
    obj = new(__meta__BloomFilterHash, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct BloomFilterHash

const __meta__BloomFilterHash = meta(BloomFilterHash,
  Symbol[:XXHASH],
  Type[XxHash],
  Symbol[:XXHASH],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::BloomFilterHash, name::Symbol)
  if name === :XXHASH
    return (obj.values[name])::XxHash
  else
    getfield(obj, name)
  end
end

meta(::Type{BloomFilterHash}) = __meta__BloomFilterHash

mutable struct Uncompressed <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function Uncompressed(; kwargs...)
    obj = new(__meta__Uncompressed, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct Uncompressed

const __meta__Uncompressed = meta(Uncompressed,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{Uncompressed}) = __meta__Uncompressed

mutable struct BloomFilterCompression <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function BloomFilterCompression(; kwargs...)
    obj = new(__meta__BloomFilterCompression, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct BloomFilterCompression

const __meta__BloomFilterCompression = meta(BloomFilterCompression,
  Symbol[:UNCOMPRESSED],
  Type[Uncompressed],
  Symbol[:UNCOMPRESSED],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::BloomFilterCompression, name::Symbol)
  if name === :UNCOMPRESSED
    return (obj.values[name])::Uncompressed
  else
    getfield(obj, name)
  end
end

meta(::Type{BloomFilterCompression}) = __meta__BloomFilterCompression

mutable struct BloomFilterHeader <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function BloomFilterHeader(; kwargs...)
    obj = new(__meta__BloomFilterHeader, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct BloomFilterHeader

const __meta__BloomFilterHeader = meta(BloomFilterHeader,
  Symbol[:numBytes,:algorithm,:hash,:compression],
  Type[Int32,BloomFilterAlgorithm,BloomFilterHash,BloomFilterCompression],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::BloomFilterHeader, name::Symbol)
  if name === :numBytes
    return (obj.values[name])::Int32
  elseif name === :algorithm
    return (obj.values[name])::BloomFilterAlgorithm
  elseif name === :hash
    return (obj.values[name])::BloomFilterHash
  elseif name === :compression
    return (obj.values[name])::BloomFilterCompression
  else
    getfield(obj, name)
  end
end

meta(::Type{BloomFilterHeader}) = __meta__BloomFilterHeader

mutable struct PageHeader <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function PageHeader(; kwargs...)
    obj = new(__meta__PageHeader, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct PageHeader

const __meta__PageHeader = meta(PageHeader,
  Symbol[:_type,:uncompressed_page_size,:compressed_page_size,:crc,:data_page_header,:index_page_header,:dictionary_page_header,:data_page_header_v2],
  Type[Int32,Int32,Int32,Int32,DataPageHeader,IndexPageHeader,DictionaryPageHeader,DataPageHeaderV2],
  Symbol[:crc,:data_page_header,:index_page_header,:dictionary_page_header,:data_page_header_v2],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::PageHeader, name::Symbol)
  if name === :_type
    return (obj.values[name])::Int32
  elseif name === :uncompressed_page_size
    return (obj.values[name])::Int32
  elseif name === :compressed_page_size
    return (obj.values[name])::Int32
  elseif name === :crc
    return (obj.values[name])::Int32
  elseif name === :data_page_header
    return (obj.values[name])::DataPageHeader
  elseif name === :index_page_header
    return (obj.values[name])::IndexPageHeader
  elseif name === :dictionary_page_header
    return (obj.values[name])::DictionaryPageHeader
  elseif name === :data_page_header_v2
    return (obj.values[name])::DataPageHeaderV2
  else
    getfield(obj, name)
  end
end

meta(::Type{PageHeader}) = __meta__PageHeader

mutable struct KeyValue <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function KeyValue(; kwargs...)
    obj = new(__meta__KeyValue, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct KeyValue

const __meta__KeyValue = meta(KeyValue,
  Symbol[:key,:value],
  Type[String,String],
  Symbol[:value],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::KeyValue, name::Symbol)
  if name === :key
    return (obj.values[name])::String
  elseif name === :value
    return (obj.values[name])::String
  else
    getfield(obj, name)
  end
end

meta(::Type{KeyValue}) = __meta__KeyValue

mutable struct SortingColumn <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function SortingColumn(; kwargs...)
    obj = new(__meta__SortingColumn, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct SortingColumn

const __meta__SortingColumn = meta(SortingColumn,
  Symbol[:column_idx,:descending,:nulls_first],
  Type[Int32,Bool,Bool],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::SortingColumn, name::Symbol)
  if name === :column_idx
    return (obj.values[name])::Int32
  elseif name === :descending
    return (obj.values[name])::Bool
  elseif name === :nulls_first
    return (obj.values[name])::Bool
  else
    getfield(obj, name)
  end
end

meta(::Type{SortingColumn}) = __meta__SortingColumn

mutable struct PageEncodingStats <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function PageEncodingStats(; kwargs...)
    obj = new(__meta__PageEncodingStats, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct PageEncodingStats

const __meta__PageEncodingStats = meta(PageEncodingStats,
  Symbol[:page_type,:encoding,:count],
  Type[Int32,Int32,Int32],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::PageEncodingStats, name::Symbol)
  if name === :page_type
    return (obj.values[name])::Int32
  elseif name === :encoding
    return (obj.values[name])::Int32
  elseif name === :count
    return (obj.values[name])::Int32
  else
    getfield(obj, name)
  end
end

meta(::Type{PageEncodingStats}) = __meta__PageEncodingStats

mutable struct ColumnMetaData <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function ColumnMetaData(; kwargs...)
    obj = new(__meta__ColumnMetaData, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct ColumnMetaData

const __meta__ColumnMetaData = meta(ColumnMetaData,
  Symbol[:_type,:encodings,:path_in_schema,:codec,:num_values,:total_uncompressed_size,:total_compressed_size,:key_value_metadata,:data_page_offset,:index_page_offset,:dictionary_page_offset,:statistics,:encoding_stats,:bloom_filter_offset],
  Type[Int32,Vector{Int32},Vector{String},Int32,Int64,Int64,Int64,Vector{KeyValue},Int64,Int64,Int64,Statistics,Vector{PageEncodingStats},Int64],
  Symbol[:key_value_metadata,:index_page_offset,:dictionary_page_offset,:statistics,:encoding_stats,:bloom_filter_offset],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::ColumnMetaData, name::Symbol)
  if name === :_type
    return (obj.values[name])::Int32
  elseif name === :encodings
    return (obj.values[name])::Vector{Int32}
  elseif name === :path_in_schema
    return (obj.values[name])::Vector{String}
  elseif name === :codec
    return (obj.values[name])::Int32
  elseif name === :num_values
    return (obj.values[name])::Int64
  elseif name === :total_uncompressed_size
    return (obj.values[name])::Int64
  elseif name === :total_compressed_size
    return (obj.values[name])::Int64
  elseif name === :key_value_metadata
    return (obj.values[name])::Vector{KeyValue}
  elseif name === :data_page_offset
    return (obj.values[name])::Int64
  elseif name === :index_page_offset
    return (obj.values[name])::Int64
  elseif name === :dictionary_page_offset
    return (obj.values[name])::Int64
  elseif name === :statistics
    return (obj.values[name])::Statistics
  elseif name === :encoding_stats
    return (obj.values[name])::Vector{PageEncodingStats}
  elseif name === :bloom_filter_offset
    return (obj.values[name])::Int64
  else
    getfield(obj, name)
  end
end

meta(::Type{ColumnMetaData}) = __meta__ColumnMetaData

mutable struct EncryptionWithFooterKey <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function EncryptionWithFooterKey(; kwargs...)
    obj = new(__meta__EncryptionWithFooterKey, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct EncryptionWithFooterKey

const __meta__EncryptionWithFooterKey = meta(EncryptionWithFooterKey,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{EncryptionWithFooterKey}) = __meta__EncryptionWithFooterKey

mutable struct EncryptionWithColumnKey <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function EncryptionWithColumnKey(; kwargs...)
    obj = new(__meta__EncryptionWithColumnKey, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct EncryptionWithColumnKey

const __meta__EncryptionWithColumnKey = meta(EncryptionWithColumnKey,
  Symbol[:path_in_schema,:key_metadata],
  Type[Vector{String},Vector{UInt8}],
  Symbol[:key_metadata],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::EncryptionWithColumnKey, name::Symbol)
  if name === :path_in_schema
    return (obj.values[name])::Vector{String}
  elseif name === :key_metadata
    return (obj.values[name])::Vector{UInt8}
  else
    getfield(obj, name)
  end
end

meta(::Type{EncryptionWithColumnKey}) = __meta__EncryptionWithColumnKey

mutable struct ColumnCryptoMetaData <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function ColumnCryptoMetaData(; kwargs...)
    obj = new(__meta__ColumnCryptoMetaData, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct ColumnCryptoMetaData

const __meta__ColumnCryptoMetaData = meta(ColumnCryptoMetaData,
  Symbol[:ENCRYPTION_WITH_FOOTER_KEY,:ENCRYPTION_WITH_COLUMN_KEY],
  Type[EncryptionWithFooterKey,EncryptionWithColumnKey],
  Symbol[:ENCRYPTION_WITH_FOOTER_KEY,:ENCRYPTION_WITH_COLUMN_KEY],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::ColumnCryptoMetaData, name::Symbol)
  if name === :ENCRYPTION_WITH_FOOTER_KEY
    return (obj.values[name])::EncryptionWithFooterKey
  elseif name === :ENCRYPTION_WITH_COLUMN_KEY
    return (obj.values[name])::EncryptionWithColumnKey
  else
    getfield(obj, name)
  end
end

meta(::Type{ColumnCryptoMetaData}) = __meta__ColumnCryptoMetaData

mutable struct ColumnChunk <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function ColumnChunk(; kwargs...)
    obj = new(__meta__ColumnChunk, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct ColumnChunk

const __meta__ColumnChunk = meta(ColumnChunk,
  Symbol[:file_path,:file_offset,:meta_data,:offset_index_offset,:offset_index_length,:column_index_offset,:column_index_length,:crypto_metadata,:encrypted_column_metadata],
  Type[String,Int64,ColumnMetaData,Int64,Int32,Int64,Int32,ColumnCryptoMetaData,Vector{UInt8}],
  Symbol[:file_path,:meta_data,:offset_index_offset,:offset_index_length,:column_index_offset,:column_index_length,:crypto_metadata,:encrypted_column_metadata],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::ColumnChunk, name::Symbol)
  if name === :file_path
    return (obj.values[name])::String
  elseif name === :file_offset
    return (obj.values[name])::Int64
  elseif name === :meta_data
    return (obj.values[name])::ColumnMetaData
  elseif name === :offset_index_offset
    return (obj.values[name])::Int64
  elseif name === :offset_index_length
    return (obj.values[name])::Int32
  elseif name === :column_index_offset
    return (obj.values[name])::Int64
  elseif name === :column_index_length
    return (obj.values[name])::Int32
  elseif name === :crypto_metadata
    return (obj.values[name])::ColumnCryptoMetaData
  elseif name === :encrypted_column_metadata
    return (obj.values[name])::Vector{UInt8}
  else
    getfield(obj, name)
  end
end

meta(::Type{ColumnChunk}) = __meta__ColumnChunk

mutable struct RowGroup <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function RowGroup(; kwargs...)
    obj = new(__meta__RowGroup, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct RowGroup

const __meta__RowGroup = meta(RowGroup,
  Symbol[:columns,:total_byte_size,:num_rows,:sorting_columns,:file_offset,:total_compressed_size,:ordinal],
  Type[Vector{ColumnChunk},Int64,Int64,Vector{SortingColumn},Int64,Int64,Int16],
  Symbol[:sorting_columns,:file_offset,:total_compressed_size,:ordinal],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::RowGroup, name::Symbol)
  if name === :columns
    return (obj.values[name])::Vector{ColumnChunk}
  elseif name === :total_byte_size
    return (obj.values[name])::Int64
  elseif name === :num_rows
    return (obj.values[name])::Int64
  elseif name === :sorting_columns
    return (obj.values[name])::Vector{SortingColumn}
  elseif name === :file_offset
    return (obj.values[name])::Int64
  elseif name === :total_compressed_size
    return (obj.values[name])::Int64
  elseif name === :ordinal
    return (obj.values[name])::Int16
  else
    getfield(obj, name)
  end
end

meta(::Type{RowGroup}) = __meta__RowGroup

mutable struct TypeDefinedOrder <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function TypeDefinedOrder(; kwargs...)
    obj = new(__meta__TypeDefinedOrder, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct TypeDefinedOrder

const __meta__TypeDefinedOrder = meta(TypeDefinedOrder,
  Symbol[],
  Type[],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

meta(::Type{TypeDefinedOrder}) = __meta__TypeDefinedOrder

mutable struct ColumnOrder <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function ColumnOrder(; kwargs...)
    obj = new(__meta__ColumnOrder, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct ColumnOrder

const __meta__ColumnOrder = meta(ColumnOrder,
  Symbol[:TYPE_ORDER],
  Type[TypeDefinedOrder],
  Symbol[:TYPE_ORDER],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::ColumnOrder, name::Symbol)
  if name === :TYPE_ORDER
    return (obj.values[name])::TypeDefinedOrder
  else
    getfield(obj, name)
  end
end

meta(::Type{ColumnOrder}) = __meta__ColumnOrder

mutable struct PageLocation <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function PageLocation(; kwargs...)
    obj = new(__meta__PageLocation, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct PageLocation

const __meta__PageLocation = meta(PageLocation,
  Symbol[:offset,:compressed_page_size,:first_row_index],
  Type[Int64,Int32,Int64],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::PageLocation, name::Symbol)
  if name === :offset
    return (obj.values[name])::Int64
  elseif name === :compressed_page_size
    return (obj.values[name])::Int32
  elseif name === :first_row_index
    return (obj.values[name])::Int64
  else
    getfield(obj, name)
  end
end

meta(::Type{PageLocation}) = __meta__PageLocation

mutable struct OffsetIndex <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function OffsetIndex(; kwargs...)
    obj = new(__meta__OffsetIndex, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct OffsetIndex

const __meta__OffsetIndex = meta(OffsetIndex,
  Symbol[:page_locations],
  Type[Vector{PageLocation}],
  Symbol[],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::OffsetIndex, name::Symbol)
  if name === :page_locations
    return (obj.values[name])::Vector{PageLocation}
  else
    getfield(obj, name)
  end
end

meta(::Type{OffsetIndex}) = __meta__OffsetIndex

mutable struct ColumnIndex <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function ColumnIndex(; kwargs...)
    obj = new(__meta__ColumnIndex, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct ColumnIndex

const __meta__ColumnIndex = meta(ColumnIndex,
  Symbol[:null_pages,:min_values,:max_values,:boundary_order,:null_counts],
  Type[Vector{Bool},Vector{Vector{UInt8}},Vector{Vector{UInt8}},Int32,Vector{Int64}],
  Symbol[:null_counts],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::ColumnIndex, name::Symbol)
  if name === :null_pages
    return (obj.values[name])::Vector{Bool}
  elseif name === :min_values
    return (obj.values[name])::Vector{Vector{UInt8}}
  elseif name === :max_values
    return (obj.values[name])::Vector{Vector{UInt8}}
  elseif name === :boundary_order
    return (obj.values[name])::Int32
  elseif name === :null_counts
    return (obj.values[name])::Vector{Int64}
  else
    getfield(obj, name)
  end
end

meta(::Type{ColumnIndex}) = __meta__ColumnIndex

mutable struct AesGcmV1 <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function AesGcmV1(; kwargs...)
    obj = new(__meta__AesGcmV1, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct AesGcmV1

const __meta__AesGcmV1 = meta(AesGcmV1,
  Symbol[:aad_prefix,:aad_file_unique,:supply_aad_prefix],
  Type[Vector{UInt8},Vector{UInt8},Bool],
  Symbol[:aad_prefix,:aad_file_unique,:supply_aad_prefix],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::AesGcmV1, name::Symbol)
  if name === :aad_prefix
    return (obj.values[name])::Vector{UInt8}
  elseif name === :aad_file_unique
    return (obj.values[name])::Vector{UInt8}
  elseif name === :supply_aad_prefix
    return (obj.values[name])::Bool
  else
    getfield(obj, name)
  end
end

meta(::Type{AesGcmV1}) = __meta__AesGcmV1

mutable struct AesGcmCtrV1 <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function AesGcmCtrV1(; kwargs...)
    obj = new(__meta__AesGcmCtrV1, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct AesGcmCtrV1

const __meta__AesGcmCtrV1 = meta(AesGcmCtrV1,
  Symbol[:aad_prefix,:aad_file_unique,:supply_aad_prefix],
  Type[Vector{UInt8},Vector{UInt8},Bool],
  Symbol[:aad_prefix,:aad_file_unique,:supply_aad_prefix],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::AesGcmCtrV1, name::Symbol)
  if name === :aad_prefix
    return (obj.values[name])::Vector{UInt8}
  elseif name === :aad_file_unique
    return (obj.values[name])::Vector{UInt8}
  elseif name === :supply_aad_prefix
    return (obj.values[name])::Bool
  else
    getfield(obj, name)
  end
end

meta(::Type{AesGcmCtrV1}) = __meta__AesGcmCtrV1

mutable struct EncryptionAlgorithm <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function EncryptionAlgorithm(; kwargs...)
    obj = new(__meta__EncryptionAlgorithm, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct EncryptionAlgorithm

const __meta__EncryptionAlgorithm = meta(EncryptionAlgorithm,
  Symbol[:AES_GCM_V1,:AES_GCM_CTR_V1],
  Type[AesGcmV1,AesGcmCtrV1],
  Symbol[:AES_GCM_V1,:AES_GCM_CTR_V1],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::EncryptionAlgorithm, name::Symbol)
  if name === :AES_GCM_V1
    return (obj.values[name])::AesGcmV1
  elseif name === :AES_GCM_CTR_V1
    return (obj.values[name])::AesGcmCtrV1
  else
    getfield(obj, name)
  end
end

meta(::Type{EncryptionAlgorithm}) = __meta__EncryptionAlgorithm

mutable struct FileMetaData <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function FileMetaData(; kwargs...)
    obj = new(__meta__FileMetaData, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct FileMetaData

const __meta__FileMetaData = meta(FileMetaData,
  Symbol[:version,:schema,:num_rows,:row_groups,:key_value_metadata,:created_by,:column_orders,:encryption_algorithm,:footer_signing_key_metadata],
  Type[Int32,Vector{SchemaElement},Int64,Vector{RowGroup},Vector{KeyValue},String,Vector{ColumnOrder},EncryptionAlgorithm,Vector{UInt8}],
  Symbol[:key_value_metadata,:created_by,:column_orders,:encryption_algorithm,:footer_signing_key_metadata],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::FileMetaData, name::Symbol)
  if name === :version
    return (obj.values[name])::Int32
  elseif name === :schema
    return (obj.values[name])::Vector{SchemaElement}
  elseif name === :num_rows
    return (obj.values[name])::Int64
  elseif name === :row_groups
    return (obj.values[name])::Vector{RowGroup}
  elseif name === :key_value_metadata
    return (obj.values[name])::Vector{KeyValue}
  elseif name === :created_by
    return (obj.values[name])::String
  elseif name === :column_orders
    return (obj.values[name])::Vector{ColumnOrder}
  elseif name === :encryption_algorithm
    return (obj.values[name])::EncryptionAlgorithm
  elseif name === :footer_signing_key_metadata
    return (obj.values[name])::Vector{UInt8}
  else
    getfield(obj, name)
  end
end

meta(::Type{FileMetaData}) = __meta__FileMetaData

mutable struct FileCryptoMetaData <: Thrift.TMsg
  meta::ThriftMeta
  values::Dict{Symbol,Any}

  function FileCryptoMetaData(; kwargs...)
    obj = new(__meta__FileCryptoMetaData, Dict{Symbol,Any}())
    values = obj.values
    symdict = obj.meta.symdict
    for nv in kwargs
      fldname, fldval = nv
      fldtype = symdict[fldname].jtype
      (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
      values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
    end
    Thrift.setdefaultproperties!(obj)
    obj
  end
end # mutable struct FileCryptoMetaData

const __meta__FileCryptoMetaData = meta(FileCryptoMetaData,
  Symbol[:encryption_algorithm,:key_metadata],
  Type[EncryptionAlgorithm,Vector{UInt8}],
  Symbol[:key_metadata],
  Int[],
  Dict{Symbol,Any}()
)

function Base.getproperty(obj::FileCryptoMetaData, name::Symbol)
  if name === :encryption_algorithm
    return (obj.values[name])::EncryptionAlgorithm
  elseif name === :key_metadata
    return (obj.values[name])::Vector{UInt8}
  else
    getfield(obj, name)
  end
end

meta(::Type{FileCryptoMetaData}) = __meta__FileCryptoMetaData

# COV_EXCL_STOP


text:
#=
countDfs:
- Julia version:
- Author: Dan
- Date: 2021-11-28
=#

push!(LOAD_PATH, "/mnt/g/Python Programme/BALL.jl/src" )
using BALL
using BenchmarkTools

pdb_filepath = "1AKE.pdb"

comp = System(pdb_filepath)
dfs = DataFrameSystem(comp)

function distanceDfs()
    return distance(@view(dfs.residues[50,:]), @view(dfs.residues[60,:]))
end

distanceDfs()

elapsed = @elapsed distanceDfs()
println(elapsed)
@show @benchmark distanceDfs()


text:
@testset "independent" begin
    x = MOInput([rand(5) for _ in 1:4], 3)
    y = MOInput([rand(5) for _ in 1:4], 3)

    k = IndependentMOKernel(GaussianKernel())
    @test k isa IndependentMOKernel
    @test k isa MOKernel
    @test k isa Kernel
    @test k.kernel isa Kernel
    @test k(x[2], y[2]) isa Real

    @test kernelmatrix(k, x, y) == kernelmatrix(k, collect(x), collect(y))
    @test kernelmatrix(k, x, x) == kernelmatrix(k, x)

    x1 = MOInput(rand(5), 3) # Single dim input
    @test k(x1[1], x1[1]) isa Real
    @test kernelmatrix(k, x1) isa Matrix

    @test string(k) == "Independent Multi-Output Kernel\n\tSquared Exponential Kernel"
end


text:
using Base: LibGit2

function femtocleaner_prs(api, repo, auth)
    prs, _ = pull_requests(api, repo; params = Dict(
        :state => "open",
        :head => "$(GitHub.name(get(repo.owner))):fbot/deps"
    ), auth=auth)
    prs
end

function update_repo(api, repo, auth, commit_sig)
    with_cloned_repo(api, repo, auth) do x
        lrepo, local_dir = x
        is_julia_itself = GitHub.name(repo) == "JuliaLang/julia"
        changed_any, problematic_files = process_deprecations(lrepo, local_dir; is_julia_itself=is_julia_itself)
        if !changed_any
            # Close the PR
            pr = first(femtocleaner_prs(api, repo, auth))
            close_pull_request(api, repo, pr; auth=auth)
            create_comment(api, repo, pr, """
            My code has been updated and now I don't think there's anything to do here anymore.
            Maybe you changed the code, or maybe it's me. Either way, I'll see you next time.
            """; auth=auth)
            println("No changes left in $(GitHub.name(repo))")
        else
            # Diff the new changes against what's already in the PR
            lcommit = LibGit2.GitCommit(lrepo, LibGit2.commit(lrepo, "Fix deprecations"; author=commit_sig, committer=commit_sig, parent_ids=[LibGit2.GitHash(lrepo, "HEAD")]))
            rbranch = LibGit2.GitObject(lrepo, "refs/remotes/origin/fbot/deps")
            diff = LibGit2.diff_tree(lrepo, LibGit2.peel(lcommit), LibGit2.peel(rbranch))
            if count(diff) == 0
                println("No difference in new patch for $(GitHub.name(repo))")
            else
                println("Should update $(GitHub.name(repo))")
                pr = first(femtocleaner_prs(api, repo, auth))
                push_repo(api, lrepo, auth)
                create_comment(api, repo, pr, """
                My code has been updated. I now view the world differently.
                Am I still the same bot I was before?
                In any case, I've updated this PR to reflect my new knowledge. I hope you like it.
                """; auth=auth)
            end
        end
    end
end

function update_existing_repos(api, commit_sig, app_id)
    for inst in installations(api, get_auth(app_id))[1]
        try
            repos_with_open_prs = Repo[]
            auth = create_access_token(api, inst, get_auth(app_id))
            irepos, _ = repos(api, inst; auth=auth)
            has_open_prs(repo) = !isempty(femtocleaner_prs(api, repo, auth))
            append!(repos_with_open_prs, filter(has_open_prs, irepos))
            foreach(repos_with_open_prs) do repo
                update_repo(api, repo, auth, commit_sig)
            end
        catch e
            bt = catch_backtrace()
            Base.display_error(STDERR, e, bt)
        end
    end
end

function maybe_autdodeploy(event, listener, jwt, sourcerepo_installation, enabled)
    @assert event.kind == "push"
    repo = Repo(event.payload["repository"])
    (GitHub.name(repo) == "JuliaComputing/FemtoCleaner.jl") || return
    (event.payload["ref"] == "refs/heads/master") || return
    if !enabled
        warn("Push event received, but auto deployment is disabled")
        return
    end
    info("Commencing auto deployment")
    with(GitRepo, Pkg.dir("FemtoCleaner")) do repo
        LibGit2.fetch(repo)
        ahead_remote, ahead_local = LibGit2.revcount(repo, "origin/master", "master")
        rcount = min(ahead_remote, ahead_local)
        if ahead_local-rcount > 0
            warn("Local repository has more commits that origin. Aborting")
            return false
        end
        # Shut down the server, so the new process can replace it
        close(listener.server)
        LibGit2.reset!(repo, LibGit2.GitHash(event.payload["after"]), LibGit2.Consts.RESET_HARD)
        for (pkg, version) in JSON.parse(readstring(joinpath(dirname(@__FILE__),"..","dependencies.json")))
            with(GitRepo, Pkg.dir(pkg)) do deprepo
                for remote in LibGit2.remotes(deprepo)
                    LibGit2.fetch(deprepo; remote=remote)
                end
                LibGit2.reset!(deprepo, LibGit2.GitHash(version), LibGit2.Consts.RESET_HARD)
            end
        end
        if sourcerepo_installation != 0
            auth = create_access_token(Installation(sourcerepo_installation), jwt)
            create_comment(Repo("JuliaComputing/FemtoCleaner.jl"), event.payload["after"], :commit; auth=auth,
                params = Dict(
                    :body => "I have deployed this commit :shipit:."
                )
            )
        end
        @async begin
            run(`$(Base.julia_cmd()) --history-file=no -e 'using FemtoCleaner; FemtoCleaner.run_server()'`)
            println("Dead")
            sleep(10)
            exit()
        end
    end
end