text:
using Compat

mutable struct BoxTree2D

    # storage for the description of
    # the fmm tree

    nboxes::Int32
    nlev::Int32
    levelbox::Array{Int32,1}
    icolbox::Array{Int32,1}
    irowbox::Array{Int32,1}
    iparentbox::Array{Int32,1}
    ichildbox::Array{Int32,2}
    istartlev::Array{Int32,1}
    iboxlev::Array{Int32,1}
    icolleagbox::Array{Int32,2}
    nblevel::Array{Int32,1}
    neighbors::Array{Int32,2}
    nnbrs::Array{Int32,1}
    localonoff::Array{Int32,1}
    zll::Array{Float64,1}
    blength::Float64
end

mutable struct SortedPts2D

    # storage for points and sorted
    # versions/ladder structures for
    # tree

    ns::Int32
    nt::Int32
    src::Array{Float64,2}
    targ::Array{Float64,2}
    srcsort::Array{Float64,2}
    targsort::Array{Float64,2}
    isrcsort::Array{Int32,1}
    itargsort::Array{Int32,1}
    isrcladder::Array{Int32,2}
    itargladder::Array{Int32,2}
    ifexrad::Bool
    exrad::Array{Float64,1}
    exradsort::Array{Float64,1}

end

function SortedPts2D(src_in::Array{Float64,2},
                     targ_in::Array{Float64,2},
                     maxboxes)

    # constructor for sorted points storage
    # based on sources and targets

    src = copy(src_in)
    targ = copy(targ_in)
    srcsort = copy(src)
    targsort = copy(targ)

    m,ns = size(src)
    m,nt = size(targ)

    ns = convert(Int32,ns)
    nt = convert(Int32,nt)

    isrcsort = Array{Int32}(undef, ns)
    itargsort = Array{Int32}(undef, nt)

    isrcladder = Array{Int32}(undef, 2,maxboxes)
    itargladder = Array{Int32}(undef, 2,maxboxes)

    ifexrad = false

    exrad = Array{Float64}(undef, 1)
    exradsort = Array{Float64}(undef, 1)

    return SortedPts2D(ns,nt,src,targ,srcsort,
                       targsort,isrcsort,
                       itargsort,isrcladder,
                       itargladder,ifexrad,exrad,
                       exradsort)

end

function SortedPts2DExRad(src_in::Array{Float64,2},
                          targ_in::Array{Float64,2},
                          exrad_in::Array{Float64,1},
                          maxboxes)

    # constructor for sorted points storage
    # based on sources and targets

    m,ns = size(src_in)
    m,nt = size(targ_in)
    nex = length(exrad_in)

    @assert nex==ns "length of exrad should equal number of sources"

    src = copy(src_in)
    targ = copy(targ_in)
    srcsort = copy(src)
    targsort = copy(targ)
    exrad = copy(exrad_in)
    exradsort = copy(exrad)

    ns = convert(Int32,ns)
    nt = convert(Int32,nt)

    isrcsort = Array{Int32}(undef, ns)
    itargsort = Array{Int32}(undef, nt)

    isrcladder = Array{Int32}(undef, 2,maxboxes)
    itargladder = Array{Int32}(undef, 2,maxboxes)

    ifexrad = true

    return SortedPts2D(ns,nt,src,targ,srcsort,
                       targsort,isrcsort,
                       itargsort,isrcladder,
                       itargladder,ifexrad,
                       exrad,exradsort)

end

function BoxTree2DMaxBoxes(maxboxes,maxlev)

    # construct an empty tree with enough
    # storage for maxboxes boxes and maxlev
    # levels

    nboxes = -1
    nlev = -1
    levelbox = Array{Int32}(undef, maxboxes)
    icolbox = Array{Int32}(undef, maxboxes)
    irowbox = Array{Int32}(undef, maxboxes)
    iparentbox = Array{Int32}(undef, maxboxes)
    ichildbox = Array{Int32}(undef, 4,maxboxes)
    istartlev = Array{Int32}(undef, maxlev+1)
    iboxlev = Array{Int32}(undef, maxboxes)
    icolleagbox = Array{Int32}(undef, 9,maxboxes)
    nblevel = Array{Int32}(undef, maxlev+1)
    neighbors = Array{Int32}(undef, 12,maxboxes)
    nnbrs = Array{Int32}(undef, maxboxes)
    localonoff = Array{Int32}(undef, maxboxes)
    zll = Array{Float64}(undef, 2)
    blength = zero(Float64)

    return BoxTree2D(nboxes,nlev,levelbox,icolbox,
                     irowbox,iparentbox,ichildbox,istartlev,
                     iboxlev,icolleagbox,nblevel,
                     neighbors,nnbrs,localonoff,zll,
                     blength)

end

function BoxTree2DMaxBoxesST(src::Array{Float64,2},
                             targ::Array{Float64,2},
                             maxboxes;maxlev=45,
                             maxnodes=40,
                             ifverbose::Bool=true,
                             ifalltarg::Bool=false,
                             exrad::Array{Float64,1}
                             =Array{Float64}(undef,0),
                             ifignoremaxlevfail=false)

    function cprintln(str)
        if ifverbose
            println(str)
        end
    end

    # build a BoxTree2D based on src and target
    # locations
    #
    # Input:
    #
    # src - source locations
    # targ - target locations
    # maxboxes - maximum number of boxes in
    #            tree (determines how much
    #            memory is allocated)
    # maxnodes - maximum number of sources and
    #            targets in a box (total)
    # maxlev - maximum depth of tree
    #
    # Output:
    #
    # tree - level-restricted tree adapted to
    #        source and target locations
    # sorted_pts - src and targets sorted into
    #              tree
    # ier - flag indicating the success of the
    #       routine

    maxnodes = convert(Int32,maxnodes)
    maxlev = convert(Int32,maxlev)
    maxboxes = convert(Int32,maxboxes)

    ier = [zero(Int32)]

    cprintln("sorting points ...")

    if (length(exrad) > 0)
        sorted_pts = SortedPts2DExRad(src,targ,exrad,maxboxes)
    else
        sorted_pts = SortedPts2D(src,targ,maxboxes)
    end

    cprintln("allocating memory ...")

    tree = BoxTree2DMaxBoxes(maxboxes,maxlev)

    levelbox = tree.levelbox
    icolbox = tree.icolbox
    irowbox = tree.irowbox
    iparentbox = tree.iparentbox
    ichildbox = tree.ichildbox
    nblevel = tree.nblevel
    iboxlev = tree.iboxlev
    istartlev = tree.istartlev
    src = sorted_pts.src
    srcsort = sorted_pts.srcsort
    isrcsort = sorted_pts.isrcsort
    isrcladder = sorted_pts.isrcladder
    ns = sorted_pts.ns
    targ = sorted_pts.targ
    targsort = sorted_pts.targsort
    itargsort = sorted_pts.itargsort
    itargladder = sorted_pts.itargladder
    ifexrad = sorted_pts.ifexrad
    exrad = sorted_pts.exrad
    exradsort = sorted_pts.exradsort
    nt = sorted_pts.nt
    localonoff = tree.localonoff

    xmin = min(minimum(src[1,:]),minimum(targ[1,:]))
    xmax = max(maximum(src[1,:]),maximum(targ[1,:]))
    ymin = min(minimum(src[2,:]),minimum(targ[2,:]))
    ymax = max(maximum(src[2,:]),maximum(targ[2,:]))

    copyto!(tree.zll,[xmin;ymin])
    tree.blength = max(xmax-xmin,ymax-ymin)

    zll = tree.zll
    blength = tree.blength

    maxlev2 = maxlev
    if ifexrad
        exradmax = maximum(exrad)
        maxlev_exrad = floor(Int32,log2(blength/exradmax))
        maxlev2 = max(0,min(maxlev_exrad,maxlev))
        maxlev2 = convert(Int32,maxlev2)
        ifignoremaxlevfail = true
    end

    itemparray = Array{Int32}(undef, maxboxes)
    nboxes = Array{Int32}(undef, 1)
    nlev = Array{Int32}(undef, 1)

    cprintln("calling tree building routine ...")

    ccall( (:lrt2d_mktst_,LIBMBHFMM2D), Cvoid,
           (Ref{Int32},Ref{Int32},Ref{Int32},
            Ref{Int32},Ref{Int32},Ref{Int32},
            Ref{Int32},Ref{Int32},Ref{Int32},
            Ref{Int32},Ref{Int32},Ref{Int32},
            Ref{Int32},Ref{Float64},Ref{Float64},
            Ref{Int32},Ref{Int32},Ref{Int32},
            Ref{Float64},Ref{Float64},
            Ref{Int32},Ref{Int32},Ref{Int32},
            Ref{Int32},Ref{Float64},Ref{Float64},
            Ref{Int32},Ref{Int32}),levelbox,
           icolbox,irowbox,nboxes,nlev,
           iparentbox,ichildbox,nblevel,iboxlev,
           istartlev,maxboxes,itemparray,
           maxlev2,src,srcsort,isrcsort,
           isrcladder,ns,targ,targsort,itargsort,
           itargladder,nt,maxnodes,zll,blength,
           ier,localonoff)

    tree.nboxes = nboxes[1]
    tree.nlev = nlev[1]

    if (ier[1] != 0 && !(ifignoremaxlevfail && ier[1] == 4) )
        return tree, sorted_pts, ier[1]
    end

    ifixflag = [zero(Int32)]

    icolleagbox = tree.icolleagbox

    ccall( (:lrt2d_restrict_,LIBMBHFMM2D),
           Cvoid, (Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32},Ref{Int32},Ref{Int32}),
           levelbox,iparentbox,ichildbox,icolbox,
           irowbox,icolleagbox,nboxes,nlev,nblevel,
           iboxlev,istartlev,ifixflag)

    if (ifixflag[1] != 0)
        iflag = Array{Int32}(undef, maxboxes)
        cprintln("enforcing level restriction ...")
        ccall( (:lrt2d_fix_,LIBMBHFMM2D),
               Cvoid, (Ref{Int32},Ref{Int32},Ref{Int32},
                      Ref{Int32},Ref{Int32},Ref{Int32},
                      Ref{Int32},Ref{Int32},Ref{Int32},
                      Ref{Int32},Ref{Int32},Ref{Int32},
                      Ref{Int32},Ref{Int32}),
               levelbox,iparentbox,ichildbox,icolbox,
               irowbox,icolleagbox,nboxes,nlev,nblevel,
               iboxlev,istartlev,iflag,maxboxes,
               itemparray)
    end

    tree.nboxes = nboxes[1]
    tree.nlev = nlev[1]

    cprintln("testing tree ...")

    ccall( (:lrt2d_testtree_,LIBMBHFMM2D),
           Cvoid, (Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32}),
           levelbox,iparentbox,ichildbox,icolbox,
           irowbox,nboxes,nlev,nblevel,
           iboxlev,istartlev)

    ccall( (:lrt2d_mkcolls_,LIBMBHFMM2D),
           Cvoid, (Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32},Ref{Int32},Ref{Int32},
                  Ref{Int32}),
           icolbox,irowbox,icolleagbox,nboxes,
           nlev,iparentbox,ichildbox,nblevel,
           iboxlev,istartlev)

neighbors = tree.neighbors
nnbrs = tree.nnbrs

ccall( (:lrt2d_mknbrs_,LIBMBHFMM2D),
       Cvoid, (Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Int32},Ref{Int32}),
       neighbors,nnbrs,nboxes,ichildbox,
       iparentbox,icolleagbox,icolbox,irowbox)

cprintln("sorting points into tree ...")

ccall( (:lrt2d_ptsort_,LIBMBHFMM2D),
       Cvoid, (Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Int32},Ref{Float64},Ref{Float64},
              Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Float64},Ref{Float64},Ref{Int32}),
       levelbox,icolbox,irowbox,nboxes,nlev,
       iparentbox,ichildbox,nblevel,iboxlev,istartlev,
       src,srcsort,isrcsort,isrcladder,ns,
       zll,blength,ier)

if ifexrad
    copy!(exradsort,exrad[isrcsort])
end

ccall( (:lrt2d_ptsort_wc_,LIBMBHFMM2D),
       Cvoid, (Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Int32},Ref{Float64},Ref{Float64},
              Ref{Int32},Ref{Int32},Ref{Int32},
              Ref{Float64},Ref{Float64},Ref{Int32}),
       levelbox,icolbox,irowbox,nboxes,nlev,
       iparentbox,ichildbox,nblevel,iboxlev,istartlev,
       targ,targsort,itargsort,itargladder,nt,
       zll,blength,ier)

for i = 1:nboxes[1]
    localonoff[i] = 0
    if (itargladder[2,i]-itargladder[1,i]+1 > 0 || ifalltarg)
        localonoff[i] = 1
    end
end

return tree, sorted_pts, ier[1]

end


text:
Base.show(io :: IO, switches :: GradRuleSwitches) =
    print(io, typeof(switches));
Base.show(io :: IO, gs :: GradRuleSet) =
    print(io, typeof(gs));
Base.show(io :: IO, g :: GradRule) =
    print(io, typeof(g));

## --------------  Generic: switches

n_colleges(gs :: GradRuleSwitches) = gs.nColleges;

n_two_year(gs :: GradRuleSwitches) = gs.n2Year;
two_year_colleges(gs :: GradRuleSwitches) = one(ncInt) : n_two_year(gs);
is_two_year(gs :: GradRuleSwitches, iCollege :: Integer) =
    (iCollege <= n_two_year(gs));

can_graduate(gs :: GradRuleSwitches, ic) = !is_two_year(gs, ic);
can_graduate(g :: GradRule) = t_first_grad(g) < 10;
can_graduate(g :: GradRule, t :: Integer) =
    can_graduate(g)  &&  (t >= t_first_grad(g));

no_grad_colleges(gs :: GradRuleSwitches) = two_year_colleges(gs);
grad_colleges(gs :: GradRuleSwitches) = (n_two_year(gs) + 1) : n_colleges(gs);

# Does grad prob depend on level or h gain?
use_hc_level(gs :: GradRuleSwitches) = gs.useHcLevel;
use_hc_level(gr :: GradRule) = gr.useHcLevel;
use_hc_level!(gr :: GradRuleSwitches, doUse :: Bool) =
    gr.useHcLevel = doUse;

set_hmin!(switches :: GradRuleSwitches, hMin :: Double) =
    switches.hMin = hMin;

# Grad rules generally vary by college
varies_by_college(switches :: GradRuleSwitches) = true;
grad_rule_same!(switches :: GradRuleSwitches) =
    error("Not implemented for $switches");

## ------------------  Generic: For one college

# Min no of courses needed to graduate this year
min_courses_to_grad(g :: GradRule, t) = g.nMin;
t_first_grad(g :: GradRule) = g.tFirstGrad;
# h_grad(g :: GradRule) = g.hGrad;
# Is grad prob increasing in h?
increasing_in_h(gr :: GradRule) = use_hc_level(gr);

# ------  Generic: GradRuleSet

# Can graduate after at least this many years in college
function t_first_grad(gs :: GradRuleSwitches, iCollege :: Integer)
    if can_graduate(gs, iCollege)
        return gs.tFirstGrad
    else
        return TimeInt(99);
    end
end

Lazy.@forward  GradRuleSet.switches  (
    t_first_grad, n_two_year, two_year_colleges, can_graduate,
    grad_prob_min, grad_prob_max, min_courses_to_grad,
    varies_by_college, use_hc_level);

is_two_year(gs :: GradRuleSet, iCollege :: Integer) =
    (iCollege <= n_two_year(gs));

grad_prob_min(switches :: GradRuleSwitches) = switches.gradProbMin;
grad_prob_max(switches :: GradRuleSwitches) = switches.gradProbMax;
grad_prob_min(gr :: GradRule) = gr.gradProbMin;
grad_prob_max(gr :: GradRule) = gr.gradProbMax;

n_colleges(gs :: GradRuleSet) = gs.switches.nColleges;
# Parameter that determines how "hard" a college is. Related to `h` that is required for graduation.
h_grad(gs :: GradRuleSet, iCollege :: Integer) =
    values(gs.hGradV)[iCollege];

# Min No of courses needed to graduate this year
function min_courses_to_grad(gs :: GradRuleSwitches, iCollege :: Integer;
    modelUnits :: Bool = true)

    if can_graduate(gs, iCollege)
        nCourses = gs.minNcForGrad;
        if modelUnits
            nCourses = data_to_model_courses(nCourses);
        end
    else
        nCourses = ncInt(99);
    end
    return nCourses :: ncInt
end

function validate_grad_set(gr :: GradRuleSet)
    isValid = (n_colleges(gr) > 1);
    return isValid
end

"""
	$(SIGNATURES)

Table with settings. Columns are explanation and values.
All formatted into strings.
"""
function settings_table(gs :: GradRuleSwitches)
    nc = n_colleges(gs);
    tFirstGrad = Int(t_first_grad(gs, nc));
    minNcToGrad = Int(min_courses_to_grad(gs, nc; modelUnits = false));
    return [
        "Graduation rule"  " ";
        "Time to graduation"  "$tFirstGrad";
        "Min courses for graduation"  "$minNcToGrad"
    ]
end

settings_table(gs :: GradRuleSet) = settings_table(gs.switches);
StructLH.describe(gs :: GradRuleSet) = StructLH.describe(gs.switches);
StructLH.describe(switches :: GradRuleSwitches) = settings_table(switches);

## Probability that a student may graduate at the end of year `t`
#=
Array inputs.
Inputs are values at END of the year.
=#
function grad_prob(g :: GradRule, t :: Integer,
    h :: AbstractArray{Double},  n :: AbstractArray{T2},
    h0 :: AbstractArray{Double}) where T2 <: Integer

    @assert size(h) == size(n)
    sizeV = size(h);

    if t >= g.tFirstGrad
        gProb = Array{Double}(undef, size(h));
        for i1 in eachindex(h)
            gProb[i1] = grad_prob(g, t, h[i1], n[i1], h0[i1]);
        end
    else
        gProb = zeros(Double, sizeV);
    end

    return gProb :: Array{Double}
end

grad_prob(g :: GradRule, t :: Integer,  h :: AbstractArray{Double},
    n :: AbstractArray{T2}, h0 :: Double) where T2 <: Integer =
    grad_prob(g, t, h, n, fill(h0, size(h)));

## Graduation probability on an [h, n] grid; at end of t
# For one value of the endowment
function grad_prob_grid(g :: GradRule,  t :: Integer,
    hV :: AbstractVector{Double}, nTakenV :: AbstractVector{I1},
    h0 :: Double)  where  I1 <: Integer

    @assert all_at_least(diff(hV), 0.0) "hV not increasing: $hV"

    nh = length(hV);
    nn = length(nTakenV);
    if can_graduate(g, t)
        probM = Matrix{Double}(undef, nh, nn);
        for (i_n, n) in enumerate(nTakenV)
            for (i_h, h) in enumerate(hV)
                probM[i_h,i_n] = grad_prob(g, t, h, n, h0);
            end
        end

        # if !validate_grad_prob_grid(g, probM)
        #     @exfiltrate
        # end

        @assert validate_grad_prob_grid(g, probM)
    else
        probM = zeros(Double, nh, nn);
    end
    return probM
end

function validate_grad_prob_grid(gr :: GradRule,
    prob_hnM :: Matrix{F1}) where F1 <: AbstractFloat

    isValid = true;
    if !(all_at_least(prob_hnM, 0.0) && all_at_most(prob_hnM, 1.0))
        @warn "Out of bounds"
        isValid = false;
    end
    # This can be flat in `n` (at lower bound when students don't have enough to grad)
    if !all_at_least(diff(prob_hnM, dims = 2), -0.000001)
        minDiff = minimum(diff(prob_hnM, dims = 2));
        @warn "GradProbGrid: Not increasing in n. Min diff = $minDiff"
        isValid = false;
    end
    if increasing_in_h(gr)  &&  !all_at_least(diff(prob_hnM, dims = 1), 0.0)
        @warn "GradProbGrid: Not increasing in h"
        isValid = false;
    end
    if !isValid
        println("\nGrad prob grid by (h, n):")
        show_matrix(stdout, prob_hnM, 4);
    end
    return isValid
end

# Initialize min h for graduation with default values
function init_hgrad(objId :: ObjectId, switches :: GradRuleSwitches)

    # Assume that one cannot graduate from the 1st colleges. Set hGrad to something small
    @assert !can_graduate(switches, 1)
    @assert can_graduate(switches, 2)
    hGrad0 = Double(0.1);
    phGrad0 = Param(:x0, "hGrad college 1", "hGrad0",
        hGrad0, hGrad0, Double(0.1) * hGrad0, Double(10.0) * hGrad0, false);

    nc = n_colleges(switches);
    dhGradV = fill(Double(0.5), nc-1);
    ubV = fill(Double(2.0), nc-1);
    ubV[1] = Double(5.0);
    pdhGradV = Param(:dxV, "hGrad gradient", "dhGradV",
        dhGradV, dhGradV, Double(0.1) .* dhGradV, ubV, true);

    ownId = make_child_id(objId, :hGradV);
    pvec = ParamVector(ownId,  [phGrad0, pdhGradV]);
    return IncreasingVector(ownId, pvec, hGrad0, dhGradV)
end

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

ext: jl


text:
"""
verification_experiments()

Get list of all `most-standard` configurations of `MITgcm` and return as an Array of `MITgcm_config`

```
exps=verification_experiments()
```
"""
function verification_experiments()
MITgcm_download()
pth=joinpath(MITgcm_path[1],"verification")
lst=readdir(pth)
tmp=[isfile(joinpath(pth,i,"code","packages.conf")) for i in lst]
tmp2=[isfile(joinpath(pth,i,"code","SIZE.h")) for i in lst]
lst=lst[findall(tmp.|tmp2)]

pkg_build=fill(String[],size(lst))
pkg_run=fill(String[],size(lst))
for i in 1:length(lst)
    fil=joinpath(pth,lst[i],"code","packages.conf")
    if isfile(fil)
        tmp1=read(fil,String)
        tmp1=split(tmp1,"\n")
        tmp1=tmp1[findall((!isempty).(tmp1))]
        pkg_build[i]=tmp1[findall(first.(tmp1).!=='#')]
    end

    fil=joinpath(pth,lst[i],"input","data.pkg")
    tmp1=read(fil,String)
    tmp1=split(tmp1,"\n")
    tmp1=tmp1[findall((!isempty).(tmp1))]
    tmp1=tmp1[findall(first.(tmp1).!=='#')]
    pkg_run[i]=tmp1[findall([!occursin("&",i) for i in tmp1])]
end

exps=fill(MITgcm_config(),length(lst))
for i in 1:length(lst)
    ID = UUIDs.uuid4()
    exps[i]=MITgcm_config(configuration=lst[i],ID=ID)
end

return exps
end

function verification_experiments(nam::String)
    exps=verification_experiments()
    iexp=findall([exps[i].configuration==nam for i in 1:length(exps)])[1]
    exps[iexp]
end


text:
##################################################################
# Deprecations
##################################################################

@deprecate fsparv fsparv!
@deprecate sparin sparin!


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule RLIBM_32_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("RLIBM_32")
JLLWrappers.@generate_main_file("RLIBM_32", UUID("89926bb2-2aab-59d9-87f9-76bad54e3fa2"))
end  # module RLIBM_32_jll


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct ExpressRouteCircuitPeering <: SwaggerModel
    id::Any # spec type: Union{ Nothing, String } # spec name: id

    function ExpressRouteCircuitPeering(;id=nothing)
        o = new()
        validate_property(ExpressRouteCircuitPeering, Symbol("id"), id)
        setfield!(o, Symbol("id"), id)
        o
    end
end # type ExpressRouteCircuitPeering

const _property_map_ExpressRouteCircuitPeering = Dict{Symbol,Symbol}(Symbol("id")=>Symbol("id"))
const _property_types_ExpressRouteCircuitPeering = Dict{Symbol,String}(Symbol("id")=>"String")
Base.propertynames(::Type{ ExpressRouteCircuitPeering }) = collect(keys(_property_map_ExpressRouteCircuitPeering))
Swagger.property_type(::Type{ ExpressRouteCircuitPeering }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ExpressRouteCircuitPeering[name]))}
Swagger.field_name(::Type{ ExpressRouteCircuitPeering }, property_name::Symbol) =  _property_map_ExpressRouteCircuitPeering[property_name]

function check_required(o::ExpressRouteCircuitPeering)
    true
end

function validate_property(::Type{ ExpressRouteCircuitPeering }, name::Symbol, val)
end


text:
#   Copyright 2022 Velexi Corporation
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

"""
main.jl contains the main program for the `jlcodestyle` CLI.
"""

# --- Imports

using TestTools: TestTools, jlcodestyle

# --- Main program

# Parse CLI arguments
args = jlcodestyle.cli.parse_args()

# Handle --version option
if args["version"]
    println(
        "$(basename(PROGRAM_FILE)) $(TestTools.VERSION) " *
        "(from $(dirname(PROGRAM_FILE)))",
    )
    exit(0)
end

# Run main program
jlcodestyle.cli.run(
    args["paths"]; style=args["style"], overwrite=args["overwrite"], verbose=args["verbose"]
)


text:
# NamedDims.jl package (a Parametric Type pattern example)

#= Sample code from the package

"""
The `NamedDimsArray` constructor takes a list of names as `Symbol`s,
one per dimension, and an array to wrap.
"""
struct NamedDimsArray{L, T, N, A<:AbstractArray{T, N}} <: AbstractArray{T, N}
    # `L` is for labels, it should be an `NTuple{N, Symbol}`
    data::A
end

function NamedDimsArray{L}(orig::AbstractArray{T, N}) where {L, T, N}
    if !(L isa NTuple{N, Symbol})
        throw(ArgumentError(
            "A $N dimentional array, needs a $N-tuple of dimension names. Got: $L"
        ))
    end
    return NamedDimsArray{L, T, N, typeof(orig)}(orig)
end
=#

M = reshape(collect(1:9), 3, 3);
nda = NamedDimsArray{(:x, :y)}(M)
dimnames(nda)

#=
julia> M = reshape(collect(1:9), 3, 3);

julia> nda = NamedDimsArray{(:x, :y)}(M)
3×3 NamedDimsArray{(:x, :y),Int64,2,Array{Int64,2}}:
 1  4  7
 2  5  8
 3  6  9

julia> dimnames(nda)
(:x, :y)
=#

NamedDimsArray{(:x, :y),Int64,2,Array{Int64,2}} <: NamedDimsArray{(:x, :y)}
NamedDimsArray{(:x, :y),Int64,2,Array{Int64,2}} <: NamedDimsArray{(:a, :b)}
#=
julia> NamedDimsArray{(:x, :y),Int64,2,Array{Int64,2}} <: NamedDimsArray{(:x, :y)}
true

julia> NamedDimsArray{(:x, :y),Int64,2,Array{Int64,2}} <: NamedDimsArray{(:a, :b)}
false
=#

NamedDimsArray{(:x, :y)}
NamedDimsArray{(:x, :y), T, N, A} where A<:AbstractArray{T,N} where N where T
NamedDimsArray{L, T, N, A} where A<:AbstractArray{T,N} where N where T where L
#=
julia> NamedDimsArray{(:x, :y)}
NamedDimsArray{(:x, :y),T,N,A} where A<:AbstractArray{T,N} where N where T

julia> NamedDimsArray{(:x, :y), T, N, A} where A<:AbstractArray{T,N} where N where T
NamedDimsArray{(:x, :y),T,N,A} where A<:AbstractArray{T,N} where N where T

julia> NamedDimsArray{L, T, N, A} where A<:AbstractArray{T,N} where N where T where L
NamedDimsArray
=#


text:
# ---
# title: 30. Substring with Concatenation of All Words
# id: problem30
# author: Qling
# date: 2021-05-28
# difficulty: Hard
# categories: Hash Table, Two Pointers, String
# link: <https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/>
# hidden: true
# ---
#
# You are given a string `s` and an array of strings `words` of **the same
# length**. Return all starting indices of substring(s) in `s` that is a
# concatenation of each word in `words` **exactly once** , **in any order** ,
# and **without any intervening characters**.
#
# You can return the answer in **any order**.
#
#
#
# **Example 1:**
#
#
#
#     Input: s = "barfoothefoobarman", words = ["foo","bar"]
#     Output: [0,9]
#     Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
#     The output order does not matter, returning [9,0] is fine too.
#
#
# **Example 2:**
#
#
#
#     Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
#     Output: []
#
#
# **Example 3:**
#
#
#
#     Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
#     Output: [6,9,12]
#
#
#
#
# **Constraints:**
#
#   * `1 <= s.length <= 104`
#   * `s` consists of lower-case English letters.
#   * `1 <= words.length <= 5000`
#   * `1 <= words[i].length <= 30`
#   * `words[i]` consists of lower-case English letters.
#
#
## @lc code=start
using LeetCode
using DataStructures

function find_word_concatenation(s::String, words::Vector{String})::Vector{Int}
    (length(words) == 0 || length(words[1]) == 0) && return 0
    words_map = counter(words)
    results_indices = Int[]
    word_len, words_count = length(words[1]), length(words)

    for i in 1: (length(s) - word_len * words_count + 1)
        words_seen = DefaultDict{String, Int}(0)
        for j in 0: words_count - 1
            next_word_index = i + j * word_len
            ## Get the next word from the string
            word = s[next_word_index: next_word_index + word_len - 1]
            ## Break if we don't need this word
            !haskey(words_map, word) && break
            ## Add the word to the 'words_seen' map
            words_seen[word] += 1
            ## No need to process further if the word has higher frequency than required
            words_seen[word] > get(words_map, word, 0) && break

            ## Store index if we have found all the words
            (j + 1 == words_count) && push!(results_indices, i)
        end
    end

    return results_indices
end
## @lc code=end


text:
# Make functions to return available content and style images

"""
list_styles()

Gets a list of style images
"""
function list_styles()
    style_dir = joinpath(@__DIR__, "..", "style_images")
    return joinpath.(style_dir, readdir(style_dir))
end
"""
list_contents()

Gets a list of content images
"""
function list_contents()
    content_dir = joinpath.(@__DIR__, "..", "content_images")
    npr_general = joinpath.(@__DIR__, "..", "content_images", "mould_rosin_npr_general")
    content = joinpath.(content_dir, readdir(content_dir))
    pop!(content)  # Get rid of mould_rosen directory
    append!(content, joinpath.(npr_general, readdir(npr_general)))
end


text:
#=
cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.

Given this implementation of cons:

def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

Implement car and cdr.
=#

using Test
include("Solutions/problem5_elementsofapair.jl")

@test car(cons(3, 4)) == 3
@test cdr(cons(3, 4)) == 4

max_stars_repo_name: DominiqueCaron/daily-coding-problem

max_issues_repo_name: DominiqueCaron/daily-coding-problem

max_forks_repo_name: DominiqueCaron/daily-coding-problem


text:
using PressureFieldContact: calc_clamped_piecewise, traction

# TODO: remove this test when GenericLinearAlgebra tags a patch that includes PR #53
using GenericLinearAlgebra
@testset "convergence criterion when diagonal has zeros" begin
    M1 = Hermitian(zeros(3, 3))
    M1[1,1] = 0.01
    M2 = Hermitian(zeros(3, 3))
    M2[3, 3] = 0.01
    @test eigvals(M1) == GenericLinearAlgebra._eigvals!(copy(M1))
    @test eigvals(M2) == GenericLinearAlgebra._eigvals!(copy(M2))
    @test eigen(M1).values == GenericLinearAlgebra._eigen!(copy(M1)).values
    @test eigen(M2).values == GenericLinearAlgebra._eigen!(copy(M2)).values
end

@testset "clac_clamped_piecewise" begin
	x_1 = 0.3
	x_2 = 0.5
	y_1 = 1.1
	y_2 = 0.1
	@test y_1   ≈ calc_clamped_piecewise(x_1 - 0.1,        x_1, x_2, y_1, y_2)
	@test y_1   ≈ calc_clamped_piecewise(x_1,              x_1, x_2, y_1, y_2)
	@test y_1   ≈ calc_clamped_piecewise(x_1 + 10 * eps(), x_1, x_2, y_1, y_2)
	x_avg = (x_1 + x_2) / 2
	y_avg = (y_1 + y_2) / 2
	@test y_avg ≈ calc_clamped_piecewise(x_avg,            x_1, x_2, y_1, y_2)
	@test y_2   ≈ calc_clamped_piecewise(x_2 - 10 * eps(), x_1, x_2, y_1, y_2)
	@test y_2   ≈ calc_clamped_piecewise(x_2,              x_1, x_2, y_1, y_2)
	@test y_2   ≈ calc_clamped_piecewise(x_2 + 0.1,        x_1, x_2, y_1, y_2)
end

function verify_fric_calc_bri(ins::Bristle, T̄s::SVector{3,T}, p_dA::T) where {T}
	mag_T̄s = norm(T̄s)
	T_μs = ins.μs * T̄s / mag_T̄s * p_dA
	T_μd = ins.μd * T̄s / mag_T̄s * p_dA
	if mag_T̄s <= ins.μs
		return T̄s * p_dA
	elseif mag_T̄s <= ins.T̄s_μs
		return T_μs
	elseif ins.T̄s_μd <= mag_T̄s
		return T_μd
	else
		w_μd = (mag_T̄s - ins.T̄s_μs) / (ins.T̄s_μd - ins.T̄s_μs)
		w_μs = 1 - w_μd
		return T_μs * w_μs + T_μd * w_μd
	end
end

function verify_fric_calc_reg(ins::Regularized, vel_t::SVector{3,T}, p_dA::T) where {T}
	mag_vel_t = norm(vel_t)
	T_μs = -ins.μs * vel_t / mag_vel_t * p_dA
	T_μd = -ins.μd * vel_t / mag_vel_t * p_dA
	if mag_vel_t <= ins.v_c
		return -ins.μs * vel_t / ins.v_c * p_dA
	elseif mag_vel_t <= ins.v_μs
		return T_μs
	elseif ins.v_μd <= mag_vel_t
		return T_μd
	else
		w_μd = (mag_vel_t - ins.v_μs) / (ins.v_μd - ins.v_μs)
		w_μs = 1 - w_μd
		return T_μs * w_μs + T_μd * w_μd
	end
end

v_c = 1.0e-4
μs_ = 1.1
μd_ = 0.3
ins_bri = Bristle(BristleID(1), τ=0.01, k̄=1000.0, μs=μs_, μd=μd_, magic=1.0e-2)
T̂s_ = normalize(SVector(1.0, 2.0, 3.0))
p_dA_ = 0.133
@testset "bristle" begin
	for v_mag = LinRange(0.0, 4 * μs_, 100)
		T̄s = v_mag * T̂s_
		Tc = traction(ins_bri, T̄s, p_dA_)
		@test Tc ≈ verify_fric_calc_bri(ins_bri, T̄s, p_dA_)
	end
end

ins_reg = Regularized(v_c, μs=μs_, μd=μd_)
v_dir_ = normalize(SVector(1.0, 2.0, 3.0))
p_dA_ = 0.133
@testset "regularized" begin
	for v_mag = LinRange(0.0, 4 * v_c, 100)
		vel_t = v_mag * v_dir_
		Tc = traction(ins_reg, vel_t, p_dA_)
		@test Tc ≈ verify_fric_calc_reg(ins_reg, vel_t, p_dA_)
	end
end

function create_box_and_plane(n_quad_rule::Int64, tang_force_coe::Float64=0.0, v_tol::Float64=NaN)
    box_rad = 0.05
    i_prop_compliant = InertiaProperties(400.0)
    i_prop_rigid     = InertiaProperties(400.0, d=0.09)
    Ē = 1.0e9
    c_prop_compliant = ContactProperties(Ē=Ē)
    eM_box_rigid     = as_tri_eMesh(eMesh_box(box_rad))
    eM_box_compliant = eMesh_box(box_rad)

    ### Create mechanism and temporary structure
	mag_grav = 9.8054
    mech_scen = MechanismScenario()  # n_quad_rule=n_quad_rule)

	eM_plane = eMesh_half_plane(1.0)
    nt_plane = add_contact!(mech_scen, "plane", as_tet_eMesh(eM_plane), c_prop=c_prop_compliant)

    eM_box_1 = eMesh_box(box_rad * ones(SVector{3,Float64}))
	transform!(eM_box_1, SVector(0, 0, box_rad))
	nt_box_1 = add_body_contact!(mech_scen, "box_1", as_tri_eMesh(eM_box_1), i_prop=i_prop_rigid)

	μd = 0.3
	is_regularize = !isnan(v_tol)
	if is_regularize
		add_friction_regularize!(mech_scen, nt_plane.id, nt_box_1.id, μd=μd, v_tol=v_tol, n_quad_rule=n_quad_rule)
		vel_box = SVector(0.0, v_tol, 0.0)
	else
		add_friction_bristle!(mech_scen, nt_plane.id, nt_box_1.id, μd=μd, k̄=1.0e4, τ=0.03, n_quad_rule=n_quad_rule)
		vel_box = SVector(0.0, 0.0, 0.0)
	end
	finalize!(mech_scen)
	mass_time_grav = mag_grav * nt_box_1.body.inertia.mass
	area_box_face =  4 * box_rad^2
	pene = mass_time_grav / (Ē * area_box_face)
	set_state_spq!(mech_scen, nt_box_1.joint, vel=vel_box, trans=SVector(0.0, 0.0, -pene))
	mech_scen.τ_ext[5] = mass_time_grav * μd * tang_force_coe
	return mech_scen
end

i_box_y_vel = 11
v_tol = 1.0e-4

@testset "regularized friction" begin
	for n_quad_rule = 1:2
		# Test that the box slows down when traveling at v_tol and a force less than friction strength is applied
		mech_scen = create_box_and_plane(n_quad_rule, 0.999, v_tol)
		@test calcXd(get_state(mech_scen), mech_scen)[i_box_y_vel] < 0.0

		# Test that the box speeds up when traveling at v_tol and a force less than friction strength is applied
		mech_scen = create_box_and_plane(n_quad_rule, 1.001, v_tol)
		@test 0.0 < calcXd(get_state(mech_scen), mech_scen)[i_box_y_vel]
	end
end

@testset "spatial spring friction" begin
	for n_quad_rule = 1:2
		# Test that velocity of box is positive when pushed with 1.5 the friction strength
		mech_scen = create_box_and_plane(n_quad_rule, 1.5)
		rr = Radau_for_MechanismScenario(mech_scen)
		data_time, data_state = integrate_scenario_radau(rr, t_final=0.1)
		@test 0.00001 < data_state[end, i_box_y_vel]

		# Test that velocity of the box is zero when pushed with 0.5 the friction strength
		mech_scen = create_box_and_plane(n_quad_rule, 0.5)
		rr = Radau_for_MechanismScenario(mech_scen)
		data_time, data_state = integrate_scenario_radau(rr, t_final=1.0)
		@test abs(data_state[end, i_box_y_vel]) < 1.0e-12
	end
end

using ForwardDiff: Dual

@testset "decompose and factor K" begin
	for T = (Float64, Dual{Nothing,Float64,9})
		s = spatialStiffness{T}()
		M = Diagonal([1.0, 1.0, 1.0, 1000, 1000, 1000])
		s.K.data .= M * rand_pd(6) * M
		magic = 1.0e-2
		PressureFieldContact.decompose_K!(s, magic)
		K̄ = inv(s.K̄⁻¹_sqrt)^2
		t_1, t_2 = PressureFieldContact.calc_trace_12(K̄)
		@test t_1 ≈ (t_2 * magic^2)
		S = inv(s.S⁻¹)
		@test s.K ≈ S * K̄ * S
	end
end

@testset "spatial spring friction" begin
    ### Box properties
    box_rad = 0.05
    i_prop_compliant = InertiaProperties(400.0)
    i_prop_rigid     = InertiaProperties(400.0, d=0.09)
    Ē = 1.0e9
    c_prop_compliant = ContactProperties(Ē=Ē)
    eM_box_rigid     = as_tri_eMesh(eMesh_box(box_rad))
    eM_box_compliant = eMesh_box(box_rad)

    ### Create mechanism and temporary structure
    mech_scen = MechanismScenario()

    name_part = "part"
	eM_box = eMesh_half_plane(1.0)
    nt_part = add_body_contact!(mech_scen, name_part, as_tri_eMesh(eM_box), i_prop=i_prop_rigid)

    name_hol_1 = "hol_1"
    hol_rad = 0.2 * box_rad
    eM_hol_1 = eMesh_box(hol_rad * ones(SVector{3,Float64}))
	transform!(eM_hol_1, SVector{3,Float64}(0.0, 0.0, hol_rad))  # box_rad + hol_rad, 0.0, 0.0))

    joint_1 = Prismatic(SVector{3,Float64}(0.0, 0.0, 1.0))
    nt_hol_1 = add_body_contact!(mech_scen, name_hol_1, as_tet_eMesh(eM_hol_1), c_prop=c_prop_compliant, i_prop=i_prop_compliant, joint=joint_1)

    τ = 0.03
    k̄ = 1.0e6
    add_friction_bristle!(mech_scen, nt_part.id, nt_hol_1.id, μd=0.3, χ=0.6, k̄=k̄, τ=τ, n_quad_rule=2)

    finalize!(mech_scen)  # , calcXd!, n_quad_rule=2)
	mech_scen = mech_scen

    pene = hol_rad * 0.001
    set_configuration!(mech_scen.float.state, nt_hol_1.joint, [-pene])
    x = get_state(mech_scen)

	# #######################
	# if !@isdefined vis  ### Add meshcat visualizer
	# 	vis = Visualizer()
	# 	open(vis)
	# end
	# color_gray  = RGBA{Float32}(0.5, 0.5, 0.5, 1.0)
	# color_blue  = RGBA{Float32}(0.0, 0.0, 1.0, 1.0)
	# mvis = MechanismVisualizer(my_mechanism, vis)
	# set_mesh_visual!(mvis, mech_scen, nt_hol_1.id, color_blue)
	# set_mesh_visual!(mvis, mech_scen, nt_part.id,  color_gray)
	# set_configuration!(mech_scen, mvis, x)
	# #######################

	### Test 1 -- see if stiffness is what is expected
	calcXd(x, mech_scen)
	K_ana = (hol_rad^2) * 4 * k̄ * (Ē * (pene / hol_rad))
	s = mech_scen.float.bodyBodyCache.spatialStiffness
	S = inv(s.S⁻¹)
	K² = S * inv(s.K̄⁻¹_sqrt * s.K̄⁻¹_sqrt) * S
	K_44 = K²[4,4]
	K_55 = K²[5,5]
	@test K_44 ≈ K_55
	@test 0.99 * K_ana < K_55 < 1.01 * K_ana
end

function calc_it(t::SVector{3,Float64})
    box_rad = 0.05
    box_density = 400.0
    c_prop_compliant = ContactProperties(Ē=1.0e6)
    i_prop_rigid     = InertiaProperties(box_density, d=box_rad)
    eM_box_rigid     = as_tri_eMesh(eMesh_box(box_rad))
    mech_scen = MechanismScenario()  # n_quad_rule=2)
    nt_plane  = add_contact!(     mech_scen, "plane", as_tet_eMesh(eMesh_half_plane()),   c_prop=c_prop_compliant)
    nt_body_1 = add_body_contact!(mech_scen, "box_1", eM_box_rigid,     i_prop=i_prop_rigid)
    add_friction_bristle!(mech_scen, nt_plane.id,  nt_body_1.id, μd=1.0, χ=2.2, n_quad_rule=2)
    finalize!(mech_scen)
    set_state_spq!(mech_scen, nt_body_1.joint, trans=t + SVector(0.0, 0.0,  0.99 * box_rad), w=SVector(0.4, 0.3, 1.0))
    calcXd(get_state(mech_scen), mech_scen)
    tm = mech_scen.float
    cop, _ = PressureFieldContact.normal_wrench_cop(tm.bodyBodyCache)
    BF = mech_scen.ContactInstructions[1].FrictionModel
    PressureFieldContact.calc_patch_spatial_stiffness!(mech_scen.float, BF, cop.v)
    return mech_scen.float.bodyBodyCache.spatialStiffness.K, cop.v
end

t = SVector(0.35, 0.10, 0.0)
K_t, cop_t = calc_it(t)
K_0, cop_0 = calc_it(SVector(0.0, 0.0, 0.0))

@testset "spatial stiffness" begin
    @test K_0 ≈ K_t
    @test cop_t ≈ (cop_0 + t)
end

# @testset "transform_stiffness" begin
#     f2 = CartesianFrame3D()
#     f3 = CartesianFrame3D()
#     I3 = @SMatrix([9.0 2.0 1.0; 2.0 8.0 3.0; 1.0 3.0 7.0])
#     inertia_pre = SpatialInertia{Float64}(f2, I3, randn(SVector{3,Float64}), 1.5)
#     xform = Transform3D(f2, f3, rand(RotMatrix{3,Float64}), rand(SVector{3,Float64}))
#     i66 = SMatrix(transform(inertia_pre, xform))
#
#     s = spatialStiffness{Float64}()
#     s.K.data .= SMatrix(inertia_pre)
#     PressureFieldContact.transform_stiffness!(s, xform)
#
#     @test i66 ≈ s.K
# end


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

# file downloading

downloadcmd = nothing
if Sys.iswindows()
    downloadcmd = :powershell
    function download(url::AbstractString, filename::AbstractString)
        ps = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
        tls12 = "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12"
        client = "New-Object System.Net.Webclient"
        # in the following we escape ' with '' (see https://ss64.com/ps/syntax-esc.html)
        downloadfile = "($client).DownloadFile('$(replace(url, "'" => "''"))', '$(replace(filename, "'" => "''"))')"
        run(`$ps -NoProfile -Command "$tls12; $downloadfile"`)
        filename
    end
else
    function download(url::AbstractString, filename::AbstractString)
        global downloadcmd
        if downloadcmd === nothing
            for checkcmd in (:curl, :wget, :fetch)
                if success(pipeline(`which $checkcmd`, devnull))
                    downloadcmd = checkcmd
                    break
                end
            end
        end
        if downloadcmd == :wget
            try
                run(`wget -O $filename $url`)
            catch
                rm(filename)  # wget always creates a file
                rethrow()
            end
        elseif downloadcmd == :curl
            run(`curl -g -L -f -o $filename $url`)
        elseif downloadcmd == :fetch
            run(`fetch -f $filename $url`)
        else
            error("no download agent available; install curl, wget, or fetch")
        end
        filename
    end
end
function download(url::AbstractString)
    filename = tempname()
    download(url, filename)
end

"""
    download(url::AbstractString, [localfile::AbstractString])

Download a file from the given url, optionally renaming it to the given local file name.
Note that this function relies on the availability of external tools such as `curl`, `wget`
or `fetch` to download the file and is provided for convenience. For production use or
situations in which more options are needed, please use a package that provides the desired
functionality instead.
"""
download(url, filename)

max_stars_repo_name: blegat/julia

max_issues_repo_name: blegat/julia

max_forks_repo_name: blegat/julia


text:
# Julia wrapper for header: ft2build.h
# Automatically generated using Clang.jl

# Julia wrapper for header: freetype.h
# Automatically generated using Clang.jl

function FT_Init_FreeType(alibrary)
    ccall((:FT_Init_FreeType, libfreetype), FT_Error, (Ptr{FT_Library},), alibrary)
end

function FT_Done_FreeType(library)
    ccall((:FT_Done_FreeType, libfreetype), FT_Error, (FT_Library,), library)
end

function FT_New_Face(library, filepathname, face_index, aface)
    ccall((:FT_New_Face, libfreetype), FT_Error, (FT_Library, Cstring, FT_Long, Ptr{FT_Face}), library, filepathname, face_index, aface)
end

function FT_New_Memory_Face(library, file_base, file_size, face_index, aface)
    ccall((:FT_New_Memory_Face, libfreetype), FT_Error, (FT_Library, Ptr{FT_Byte}, FT_Long, FT_Long, Ptr{FT_Face}), library, file_base, file_size, face_index, aface)
end

function FT_Open_Face(library, args, face_index, aface)
    ccall((:FT_Open_Face, libfreetype), FT_Error, (FT_Library, Ptr{FT_Open_Args}, FT_Long, Ptr{FT_Face}), library, args, face_index, aface)
end

function FT_Attach_File(face, filepathname)
    ccall((:FT_Attach_File, libfreetype), FT_Error, (FT_Face, Cstring), face, filepathname)
end

function FT_Attach_Stream(face, parameters)
    ccall((:FT_Attach_Stream, libfreetype), FT_Error, (FT_Face, Ptr{FT_Open_Args}), face, parameters)
end

function FT_Reference_Face(face)
    ccall((:FT_Reference_Face, libfreetype), FT_Error, (FT_Face,), face)
end

function FT_Done_Face(face)
    ccall((:FT_Done_Face, libfreetype), FT_Error, (FT_Face,), face)
end

function FT_Select_Size(face, strike_index)
    ccall((:FT_Select_Size, libfreetype), FT_Error, (FT_Face, FT_Int), face, strike_index)
end

function FT_Request_Size(face, req)
    ccall((:FT_Request_Size, libfreetype), FT_Error, (FT_Face, FT_Size_Request), face, req)
end

function FT_Set_Char_Size(face, char_width, char_height, horz_resolution, vert_resolution)
    ccall((:FT_Set_Char_Size, libfreetype), FT_Error, (FT_Face, FT_F26Dot6, FT_F26Dot6, FT_UInt, FT_UInt), face, char_width, char_height, horz_resolution, vert_resolution)
end

function FT_Set_Pixel_Sizes(face, pixel_width, pixel_height)
    ccall((:FT_Set_Pixel_Sizes, libfreetype), FT_Error, (FT_Face, FT_UInt, FT_UInt), face, pixel_width, pixel_height)
end

function FT_Load_Glyph(face, glyph_index, load_flags)
    ccall((:FT_Load_Glyph, libfreetype), FT_Error, (FT_Face, FT_UInt, FT_Int32), face, glyph_index, load_flags)
end

function FT_Load_Char(face, char_code, load_flags)
    ccall((:FT_Load_Char, libfreetype), FT_Error, (FT_Face, FT_ULong, FT_Int32), face, char_code, load_flags)
end

function FT_Set_Transform(face, matrix, delta)
    ccall((:FT_Set_Transform, libfreetype), Cvoid, (FT_Face, Ptr{FT_Matrix}, Ptr{FT_Vector}), face, matrix, delta)
end

function FT_Render_Glyph(slot, render_mode)
    ccall((:FT_Render_Glyph, libfreetype), FT_Error, (FT_GlyphSlot, FT_Render_Mode), slot, render_mode)
end

function FT_Get_Kerning(face, left_glyph, right_glyph, kern_mode, akerning)
    ccall((:FT_Get_Kerning, libfreetype), FT_Error, (FT_Face, FT_UInt, FT_UInt, FT_UInt, Ptr{FT_Vector}), face, left_glyph, right_glyph, kern_mode, akerning)
end

function FT_Get_Track_Kerning(face, point_size, degree, akerning)
    ccall((:FT_Get_Track_Kerning, libfreetype), FT_Error, (FT_Face, FT_Fixed, FT_Int, Ptr{FT_Fixed}), face, point_size, degree, akerning)
end

function FT_Get_Glyph_Name(face, glyph_index, buffer, buffer_max)
    ccall((:FT_Get_Glyph_Name, libfreetype), FT_Error, (FT_Face, FT_UInt, FT_Pointer, FT_UInt), face, glyph_index, buffer, buffer_max)
end

function FT_Get_Postscript_Name(face)
    ccall((:FT_Get_Postscript_Name, libfreetype), Cstring, (FT_Face,), face)
end

function FT_Select_Charmap(face, encoding)
    ccall((:FT_Select_Charmap, libfreetype), FT_Error, (FT_Face, FT_Encoding), face, encoding)
end

function FT_Set_Charmap(face, charmap)
    ccall((:FT_Set_Charmap, libfreetype), FT_Error, (FT_Face, FT_CharMap), face, charmap)
end

function FT_Get_Charmap_Index(charmap)
    ccall((:FT_Get_Charmap_Index, libfreetype), FT_Int, (FT_CharMap,), charmap)
end

function FT_Get_Char_Index(face, charcode)
    ccall((:FT_Get_Char_Index, libfreetype), FT_UInt, (FT_Face, FT_ULong), face, charcode)
end

function FT_Get_First_Char(face, agindex)
    ccall((:FT_Get_First_Char, libfreetype), FT_ULong, (FT_Face, Ptr{FT_UInt}), face, agindex)
end

function FT_Get_Next_Char(face, char_code, agindex)
    ccall((:FT_Get_Next_Char, libfreetype), FT_ULong, (FT_Face, FT_ULong, Ptr{FT_UInt}), face, char_code, agindex)
end

function FT_Face_Properties(face, num_properties, properties)
    ccall((:FT_Face_Properties, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Parameter}), face, num_properties, properties)
end

function FT_Get_Name_Index(face, glyph_name)
    ccall((:FT_Get_Name_Index, libfreetype), FT_UInt, (FT_Face, Ptr{FT_String}), face, glyph_name)
end

function FT_Get_SubGlyph_Info(glyph, sub_index, p_index, p_flags, p_arg1, p_arg2, p_transform)
    ccall((:FT_Get_SubGlyph_Info, libfreetype), FT_Error, (FT_GlyphSlot, FT_UInt, Ptr{FT_Int}, Ptr{FT_UInt}, Ptr{FT_Int}, Ptr{FT_Int}, Ptr{FT_Matrix}), glyph, sub_index, p_index, p_flags, p_arg1, p_arg2, p_transform)
end

function FT_Get_FSType_Flags(face)
    ccall((:FT_Get_FSType_Flags, libfreetype), FT_UShort, (FT_Face,), face)
end

function FT_Face_GetCharVariantIndex(face, charcode, variantSelector)
    ccall((:FT_Face_GetCharVariantIndex, libfreetype), FT_UInt, (FT_Face, FT_ULong, FT_ULong), face, charcode, variantSelector)
end

function FT_Face_GetCharVariantIsDefault(face, charcode, variantSelector)
    ccall((:FT_Face_GetCharVariantIsDefault, libfreetype), FT_Int, (FT_Face, FT_ULong, FT_ULong), face, charcode, variantSelector)
end

function FT_Face_GetVariantSelectors(face)
    ccall((:FT_Face_GetVariantSelectors, libfreetype), Ptr{FT_UInt32}, (FT_Face,), face)
end

function FT_Face_GetVariantsOfChar(face, charcode)
    ccall((:FT_Face_GetVariantsOfChar, libfreetype), Ptr{FT_UInt32}, (FT_Face, FT_ULong), face, charcode)
end

function FT_Face_GetCharsOfVariant(face, variantSelector)
    ccall((:FT_Face_GetCharsOfVariant, libfreetype), Ptr{FT_UInt32}, (FT_Face, FT_ULong), face, variantSelector)
end

function FT_MulDiv(a, b, c)
    ccall((:FT_MulDiv, libfreetype), FT_Long, (FT_Long, FT_Long, FT_Long), a, b, c)
end

function FT_MulFix(a, b)
    ccall((:FT_MulFix, libfreetype), FT_Long, (FT_Long, FT_Long), a, b)
end

function FT_DivFix(a, b)
    ccall((:FT_DivFix, libfreetype), FT_Long, (FT_Long, FT_Long), a, b)
end

function FT_RoundFix(a)
    ccall((:FT_RoundFix, libfreetype), FT_Fixed, (FT_Fixed,), a)
end

function FT_CeilFix(a)
    ccall((:FT_CeilFix, libfreetype), FT_Fixed, (FT_Fixed,), a)
end

function FT_FloorFix(a)
    ccall((:FT_FloorFix, libfreetype), FT_Fixed, (FT_Fixed,), a)
end

function FT_Vector_Transform(vec, matrix)
    ccall((:FT_Vector_Transform, libfreetype), Cvoid, (Ptr{FT_Vector}, Ptr{FT_Matrix}), vec, matrix)
end

function FT_Library_Version(library, amajor, aminor, apatch)
    ccall((:FT_Library_Version, libfreetype), Cvoid, (FT_Library, Ptr{FT_Int}, Ptr{FT_Int}, Ptr{FT_Int}), library, amajor, aminor, apatch)
end

function FT_Face_CheckTrueTypePatents(face)
    ccall((:FT_Face_CheckTrueTypePatents, libfreetype), FT_Bool, (FT_Face,), face)
end

function FT_Face_SetUnpatentedHinting(face, value)
    ccall((:FT_Face_SetUnpatentedHinting, libfreetype), FT_Bool, (FT_Face, FT_Bool), face, value)
end
# Julia wrapper for header: ftadvanc.h
# Automatically generated using Clang.jl

function FT_Get_Advance(face, gindex, load_flags, padvance)
    ccall((:FT_Get_Advance, libfreetype), FT_Error, (FT_Face, FT_UInt, FT_Int32, Ptr{FT_Fixed}), face, gindex, load_flags, padvance)
end

function FT_Get_Advances(face, start, count, load_flags, padvances)
    ccall((:FT_Get_Advances, libfreetype), FT_Error, (FT_Face, FT_UInt, FT_UInt, FT_Int32, Ptr{FT_Fixed}), face, start, count, load_flags, padvances)
end
# Julia wrapper for header: ftbbox.h
# Automatically generated using Clang.jl

function FT_Outline_Get_BBox(outline, abbox)
    ccall((:FT_Outline_Get_BBox, libfreetype), FT_Error, (Ptr{FT_Outline}, Ptr{FT_BBox}), outline, abbox)
end
# Julia wrapper for header: ftbdf.h
# Automatically generated using Clang.jl

function FT_Get_BDF_Charset_ID(face, acharset_encoding, acharset_registry)
    ccall((:FT_Get_BDF_Charset_ID, libfreetype), FT_Error, (FT_Face, Ptr{Cstring}, Ptr{Cstring}), face, acharset_encoding, acharset_registry)
end

function FT_Get_BDF_Property(face, prop_name, aproperty)
    ccall((:FT_Get_BDF_Property, libfreetype), FT_Error, (FT_Face, Cstring, Ptr{BDF_PropertyRec}), face, prop_name, aproperty)
end
# Julia wrapper for header: ftbitmap.h
# Automatically generated using Clang.jl

function FT_Bitmap_Init(abitmap)
    ccall((:FT_Bitmap_Init, libfreetype), Cvoid, (Ptr{FT_Bitmap},), abitmap)
end

function FT_Bitmap_New(abitmap)
    ccall((:FT_Bitmap_New, libfreetype), Cvoid, (Ptr{FT_Bitmap},), abitmap)
end

function FT_Bitmap_Copy(library, source, target)
    ccall((:FT_Bitmap_Copy, libfreetype), FT_Error, (FT_Library, Ptr{FT_Bitmap}, Ptr{FT_Bitmap}), library, source, target)
end

function FT_Bitmap_Embolden(library, bitmap, xStrength, yStrength)
    ccall((:FT_Bitmap_Embolden, libfreetype), FT_Error, (FT_Library, Ptr{FT_Bitmap}, FT_Pos, FT_Pos), library, bitmap, xStrength, yStrength)
end

function FT_Bitmap_Convert(library, source, target, alignment)
    ccall((:FT_Bitmap_Convert, libfreetype), FT_Error, (FT_Library, Ptr{FT_Bitmap}, Ptr{FT_Bitmap}, FT_Int), library, source, target, alignment)
end

function FT_GlyphSlot_Own_Bitmap(slot)
    ccall((:FT_GlyphSlot_Own_Bitmap, libfreetype), FT_Error, (FT_GlyphSlot,), slot)
end

function FT_Bitmap_Done(library, bitmap)
    ccall((:FT_Bitmap_Done, libfreetype), FT_Error, (FT_Library, Ptr{FT_Bitmap}), library, bitmap)
end
# Julia wrapper for header: ftbzip2.h
# Automatically generated using Clang.jl

function FT_Stream_OpenBzip2(stream, source)
    ccall((:FT_Stream_OpenBzip2, libfreetype), FT_Error, (FT_Stream, FT_Stream), stream, source)
end
# Julia wrapper for header: ftcache.h
# Automatically generated using Clang.jl

function FTC_Manager_New(library, max_faces, max_sizes, max_bytes, requester, req_data, amanager)
    ccall((:FTC_Manager_New, libfreetype), FT_Error, (FT_Library, FT_UInt, FT_UInt, FT_ULong, FTC_Face_Requester, FT_Pointer, Ptr{FTC_Manager}), library, max_faces, max_sizes, max_bytes, requester, req_data, amanager)
end

function FTC_Manager_Reset(manager)
    ccall((:FTC_Manager_Reset, libfreetype), Cvoid, (FTC_Manager,), manager)
end

function FTC_Manager_Done(manager)
    ccall((:FTC_Manager_Done, libfreetype), Cvoid, (FTC_Manager,), manager)
end

function FTC_Manager_LookupFace(manager, face_id, aface)
    ccall((:FTC_Manager_LookupFace, libfreetype), FT_Error, (FTC_Manager, FTC_FaceID, Ptr{FT_Face}), manager, face_id, aface)
end

function FTC_Manager_LookupSize(manager, scaler, asize)
    ccall((:FTC_Manager_LookupSize, libfreetype), FT_Error, (FTC_Manager, FTC_Scaler, Ptr{FT_Size}), manager, scaler, asize)
end

function FTC_Node_Unref(node, manager)
    ccall((:FTC_Node_Unref, libfreetype), Cvoid, (FTC_Node, FTC_Manager), node, manager)
end

function FTC_Manager_RemoveFaceID(manager, face_id)
    ccall((:FTC_Manager_RemoveFaceID, libfreetype), Cvoid, (FTC_Manager, FTC_FaceID), manager, face_id)
end

function FTC_CMapCache_New(manager, acache)
    ccall((:FTC_CMapCache_New, libfreetype), FT_Error, (FTC_Manager, Ptr{FTC_CMapCache}), manager, acache)
end

function FTC_CMapCache_Lookup(cache, face_id, cmap_index, char_code)
    ccall((:FTC_CMapCache_Lookup, libfreetype), FT_UInt, (FTC_CMapCache, FTC_FaceID, FT_Int, FT_UInt32), cache, face_id, cmap_index, char_code)
end

function FTC_ImageCache_New(manager, acache)
    ccall((:FTC_ImageCache_New, libfreetype), FT_Error, (FTC_Manager, Ptr{FTC_ImageCache}), manager, acache)
end

function FTC_ImageCache_Lookup(cache, type, gindex, aglyph, anode)
    ccall((:FTC_ImageCache_Lookup, libfreetype), FT_Error, (FTC_ImageCache, FTC_ImageType, FT_UInt, Ptr{FT_Glyph}, Ptr{FTC_Node}), cache, type, gindex, aglyph, anode)
end

function FTC_ImageCache_LookupScaler(cache, scaler, load_flags, gindex, aglyph, anode)
    ccall((:FTC_ImageCache_LookupScaler, libfreetype), FT_Error, (FTC_ImageCache, FTC_Scaler, FT_ULong, FT_UInt, Ptr{FT_Glyph}, Ptr{FTC_Node}), cache, scaler, load_flags, gindex, aglyph, anode)
end

function FTC_SBitCache_New(manager, acache)
    ccall((:FTC_SBitCache_New, libfreetype), FT_Error, (FTC_Manager, Ptr{FTC_SBitCache}), manager, acache)
end

function FTC_SBitCache_Lookup(cache, type, gindex, sbit, anode)
    ccall((:FTC_SBitCache_Lookup, libfreetype), FT_Error, (FTC_SBitCache, FTC_ImageType, FT_UInt, Ptr{FTC_SBit}, Ptr{FTC_Node}), cache, type, gindex, sbit, anode)
end

function FTC_SBitCache_LookupScaler(cache, scaler, load_flags, gindex, sbit, anode)
    ccall((:FTC_SBitCache_LookupScaler, libfreetype), FT_Error, (FTC_SBitCache, FTC_Scaler, FT_ULong, FT_UInt, Ptr{FTC_SBit}, Ptr{FTC_Node}), cache, scaler, load_flags, gindex, sbit, anode)
end
# Julia wrapper for header: ftchapters.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftcid.h
# Automatically generated using Clang.jl

function FT_Get_CID_Registry_Ordering_Supplement(face, registry, ordering, supplement)
    ccall((:FT_Get_CID_Registry_Ordering_Supplement, libfreetype), FT_Error, (FT_Face, Ptr{Cstring}, Ptr{Cstring}, Ptr{FT_Int}), face, registry, ordering, supplement)
end

function FT_Get_CID_Is_Internally_CID_Keyed(face, is_cid)
    ccall((:FT_Get_CID_Is_Internally_CID_Keyed, libfreetype), FT_Error, (FT_Face, Ptr{FT_Bool}), face, is_cid)
end

function FT_Get_CID_From_Glyph_Index(face, glyph_index, cid)
    ccall((:FT_Get_CID_From_Glyph_Index, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_UInt}), face, glyph_index, cid)
end
# Julia wrapper for header: ftdriver.h
# Automatically generated using Clang.jl

# Julia wrapper for header: fterrdef.h
# Automatically generated using Clang.jl

# Julia wrapper for header: fterrors.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftfntfmt.h
# Automatically generated using Clang.jl

function FT_Get_Font_Format(face)
    ccall((:FT_Get_Font_Format, libfreetype), Cstring, (FT_Face,), face)
end

function FT_Get_X11_Font_Format(face)
    ccall((:FT_Get_X11_Font_Format, libfreetype), Cstring, (FT_Face,), face)
end
# Julia wrapper for header: ftgasp.h
# Automatically generated using Clang.jl

function FT_Get_Gasp(face, ppem)
    ccall((:FT_Get_Gasp, libfreetype), FT_Int, (FT_Face, FT_UInt), face, ppem)
end
# Julia wrapper for header: ftglyph.h
# Automatically generated using Clang.jl

function FT_Get_Glyph(slot, aglyph)
    ccall((:FT_Get_Glyph, libfreetype), FT_Error, (FT_GlyphSlot, Ptr{FT_Glyph}), slot, aglyph)
end

function FT_Glyph_Copy(source, target)
    ccall((:FT_Glyph_Copy, libfreetype), FT_Error, (FT_Glyph, Ptr{FT_Glyph}), source, target)
end

function FT_Glyph_Transform(glyph, matrix, delta)
    ccall((:FT_Glyph_Transform, libfreetype), FT_Error, (FT_Glyph, Ptr{FT_Matrix}, Ptr{FT_Vector}), glyph, matrix, delta)
end

function FT_Glyph_Get_CBox(glyph, bbox_mode, acbox)
    ccall((:FT_Glyph_Get_CBox, libfreetype), Cvoid, (FT_Glyph, FT_UInt, Ptr{FT_BBox}), glyph, bbox_mode, acbox)
end

function FT_Glyph_To_Bitmap(the_glyph, render_mode, origin, destroy)
    ccall((:FT_Glyph_To_Bitmap, libfreetype), FT_Error, (Ptr{FT_Glyph}, FT_Render_Mode, Ptr{FT_Vector}, FT_Bool), the_glyph, render_mode, origin, destroy)
end

function FT_Done_Glyph(glyph)
    ccall((:FT_Done_Glyph, libfreetype), Cvoid, (FT_Glyph,), glyph)
end

function FT_Matrix_Multiply(a, b)
    ccall((:FT_Matrix_Multiply, libfreetype), Cvoid, (Ptr{FT_Matrix}, Ptr{FT_Matrix}), a, b)
end

function FT_Matrix_Invert(matrix)
    ccall((:FT_Matrix_Invert, libfreetype), FT_Error, (Ptr{FT_Matrix},), matrix)
end
# Julia wrapper for header: ftgxval.h
# Automatically generated using Clang.jl

function FT_TrueTypeGX_Validate(face, validation_flags, tables, table_length)
    ccall((:FT_TrueTypeGX_Validate, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Bytes}, FT_UInt), face, validation_flags, tables, table_length)
end

function FT_TrueTypeGX_Free(face, table)
    ccall((:FT_TrueTypeGX_Free, libfreetype), Cvoid, (FT_Face, FT_Bytes), face, table)
end

function FT_ClassicKern_Validate(face, validation_flags, ckern_table)
    ccall((:FT_ClassicKern_Validate, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Bytes}), face, validation_flags, ckern_table)
end

function FT_ClassicKern_Free(face, table)
    ccall((:FT_ClassicKern_Free, libfreetype), Cvoid, (FT_Face, FT_Bytes), face, table)
end
# Julia wrapper for header: ftgzip.h
# Automatically generated using Clang.jl

function FT_Stream_OpenGzip(stream, source)
    ccall((:FT_Stream_OpenGzip, libfreetype), FT_Error, (FT_Stream, FT_Stream), stream, source)
end

function FT_Gzip_Uncompress(memory, output, output_len, input, input_len)
    ccall((:FT_Gzip_Uncompress, libfreetype), FT_Error, (FT_Memory, Ptr{FT_Byte}, Ptr{FT_ULong}, Ptr{FT_Byte}, FT_ULong), memory, output, output_len, input, input_len)
end
# Julia wrapper for header: ftimage.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftincrem.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftlcdfil.h
# Automatically generated using Clang.jl

function FT_Library_SetLcdFilter(library, filter)
    ccall((:FT_Library_SetLcdFilter, libfreetype), FT_Error, (FT_Library, FT_LcdFilter), library, filter)
end

function FT_Library_SetLcdFilterWeights(library, weights)
    ccall((:FT_Library_SetLcdFilterWeights, libfreetype), FT_Error, (FT_Library, Ptr{Cuchar}), library, weights)
end
# Julia wrapper for header: ftlist.h
# Automatically generated using Clang.jl

function FT_List_Find(list, data)
    ccall((:FT_List_Find, libfreetype), FT_ListNode, (FT_List, Ptr{Cvoid}), list, data)
end

function FT_List_Add(list, node)
    ccall((:FT_List_Add, libfreetype), Cvoid, (FT_List, FT_ListNode), list, node)
end

function FT_List_Insert(list, node)
    ccall((:FT_List_Insert, libfreetype), Cvoid, (FT_List, FT_ListNode), list, node)
end

function FT_List_Remove(list, node)
    ccall((:FT_List_Remove, libfreetype), Cvoid, (FT_List, FT_ListNode), list, node)
end

function FT_List_Up(list, node)
    ccall((:FT_List_Up, libfreetype), Cvoid, (FT_List, FT_ListNode), list, node)
end

function FT_List_Iterate(list, iterator, user)
    ccall((:FT_List_Iterate, libfreetype), FT_Error, (FT_List, FT_List_Iterator, Ptr{Cvoid}), list, iterator, user)
end

function FT_List_Finalize(list, destroy, memory, user)
    ccall((:FT_List_Finalize, libfreetype), Cvoid, (FT_List, FT_List_Destructor, FT_Memory, Ptr{Cvoid}), list, destroy, memory, user)
end
# Julia wrapper for header: ftlzw.h
# Automatically generated using Clang.jl

function FT_Stream_OpenLZW(stream, source)
    ccall((:FT_Stream_OpenLZW, libfreetype), FT_Error, (FT_Stream, FT_Stream), stream, source)
end
# Julia wrapper for header: ftmac.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftmm.h
# Automatically generated using Clang.jl

function FT_Get_Multi_Master(face, amaster)
    ccall((:FT_Get_Multi_Master, libfreetype), FT_Error, (FT_Face, Ptr{FT_Multi_Master}), face, amaster)
end

function FT_Get_MM_Var(face, amaster)
    ccall((:FT_Get_MM_Var, libfreetype), FT_Error, (FT_Face, Ptr{Ptr{FT_MM_Var}}), face, amaster)
end

function FT_Done_MM_Var(library, amaster)
    ccall((:FT_Done_MM_Var, libfreetype), FT_Error, (FT_Library, Ptr{FT_MM_Var}), library, amaster)
end

function FT_Set_MM_Design_Coordinates(face, num_coords, coords)
    ccall((:FT_Set_MM_Design_Coordinates, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Long}), face, num_coords, coords)
end

function FT_Set_Var_Design_Coordinates(face, num_coords, coords)
    ccall((:FT_Set_Var_Design_Coordinates, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Fixed}), face, num_coords, coords)
end

function FT_Get_Var_Design_Coordinates(face, num_coords, coords)
    ccall((:FT_Get_Var_Design_Coordinates, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Fixed}), face, num_coords, coords)
end

function FT_Set_MM_Blend_Coordinates(face, num_coords, coords)
    ccall((:FT_Set_MM_Blend_Coordinates, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Fixed}), face, num_coords, coords)
end

function FT_Get_MM_Blend_Coordinates(face, num_coords, coords)
    ccall((:FT_Get_MM_Blend_Coordinates, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Fixed}), face, num_coords, coords)
end

function FT_Set_Var_Blend_Coordinates(face, num_coords, coords)
    ccall((:FT_Set_Var_Blend_Coordinates, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Fixed}), face, num_coords, coords)
end

function FT_Get_Var_Blend_Coordinates(face, num_coords, coords)
    ccall((:FT_Get_Var_Blend_Coordinates, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Fixed}), face, num_coords, coords)
end

function FT_Get_Var_Axis_Flags(master, axis_index, flags)
    ccall((:FT_Get_Var_Axis_Flags, libfreetype), FT_Error, (Ptr{FT_MM_Var}, FT_UInt, Ptr{FT_UInt}), master, axis_index, flags)
end

function FT_Set_Named_Instance(face, instance_index)
    ccall((:FT_Set_Named_Instance, libfreetype), FT_Error, (FT_Face, FT_UInt), face, instance_index)
end
# Julia wrapper for header: ftmodapi.h
# Automatically generated using Clang.jl

function FT_Add_Module(library, clazz)
    ccall((:FT_Add_Module, libfreetype), FT_Error, (FT_Library, Ptr{FT_Module_Class}), library, clazz)
end

function FT_Get_Module(library, module_name)
    ccall((:FT_Get_Module, libfreetype), FT_Module, (FT_Library, Cstring), library, module_name)
end

function FT_Remove_Module(library, _module)
    ccall((:FT_Remove_Module, libfreetype), FT_Error, (FT_Library, FT_Module), library, _module)
end

function FT_Property_Set(library, module_name, property_name, value)
    ccall((:FT_Property_Set, libfreetype), FT_Error, (FT_Library, Ptr{FT_String}, Ptr{FT_String}, Ptr{Cvoid}), library, module_name, property_name, value)
end

function FT_Property_Get(library, module_name, property_name, value)
    ccall((:FT_Property_Get, libfreetype), FT_Error, (FT_Library, Ptr{FT_String}, Ptr{FT_String}, Ptr{Cvoid}), library, module_name, property_name, value)
end

function FT_Set_Default_Properties(library)
    ccall((:FT_Set_Default_Properties, libfreetype), Cvoid, (FT_Library,), library)
end

function FT_Reference_Library(library)
    ccall((:FT_Reference_Library, libfreetype), FT_Error, (FT_Library,), library)
end

function FT_New_Library(memory, alibrary)
    ccall((:FT_New_Library, libfreetype), FT_Error, (FT_Memory, Ptr{FT_Library}), memory, alibrary)
end

function FT_Done_Library(library)
    ccall((:FT_Done_Library, libfreetype), FT_Error, (FT_Library,), library)
end

function FT_Set_Debug_Hook(library, hook_index, debug_hook)
    ccall((:FT_Set_Debug_Hook, libfreetype), Cvoid, (FT_Library, FT_UInt, FT_DebugHook_Func), library, hook_index, debug_hook)
end

function FT_Add_Default_Modules(library)
    ccall((:FT_Add_Default_Modules, libfreetype), Cvoid, (FT_Library,), library)
end

function FT_Get_TrueType_Engine_Type(library)
    ccall((:FT_Get_TrueType_Engine_Type, libfreetype), FT_TrueTypeEngineType, (FT_Library,), library)
end
# Julia wrapper for header: ftmoderr.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftotval.h
# Automatically generated using Clang.jl

function FT_OpenType_Validate(face, validation_flags, BASE_table, GDEF_table, GPOS_table, GSUB_table, JSTF_table)
    ccall((:FT_OpenType_Validate, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Bytes}, Ptr{FT_Bytes}, Ptr{FT_Bytes}, Ptr{FT_Bytes}, Ptr{FT_Bytes}), face, validation_flags, BASE_table, GDEF_table, GPOS_table, GSUB_table, JSTF_table)
end

function FT_OpenType_Free(face, table)
    ccall((:FT_OpenType_Free, libfreetype), Cvoid, (FT_Face, FT_Bytes), face, table)
end
# Julia wrapper for header: ftoutln.h
# Automatically generated using Clang.jl

function FT_Outline_Decompose(outline, func_interface, user)
    ccall((:FT_Outline_Decompose, libfreetype), FT_Error, (Ptr{FT_Outline}, Ptr{FT_Outline_Funcs}, Ptr{Cvoid}), outline, func_interface, user)
end

function FT_Outline_New(library, numPoints, numContours, anoutline)
    ccall((:FT_Outline_New, libfreetype), FT_Error, (FT_Library, FT_UInt, FT_Int, Ptr{FT_Outline}), library, numPoints, numContours, anoutline)
end

function FT_Outline_New_Internal(memory, numPoints, numContours, anoutline)
    ccall((:FT_Outline_New_Internal, libfreetype), FT_Error, (FT_Memory, FT_UInt, FT_Int, Ptr{FT_Outline}), memory, numPoints, numContours, anoutline)
end

function FT_Outline_Done(library, outline)
    ccall((:FT_Outline_Done, libfreetype), FT_Error, (FT_Library, Ptr{FT_Outline}), library, outline)
end

function FT_Outline_Done_Internal(memory, outline)
    ccall((:FT_Outline_Done_Internal, libfreetype), FT_Error, (FT_Memory, Ptr{FT_Outline}), memory, outline)
end

function FT_Outline_Check(outline)
    ccall((:FT_Outline_Check, libfreetype), FT_Error, (Ptr{FT_Outline},), outline)
end

function FT_Outline_Get_CBox(outline, acbox)
    ccall((:FT_Outline_Get_CBox, libfreetype), Cvoid, (Ptr{FT_Outline}, Ptr{FT_BBox}), outline, acbox)
end

function FT_Outline_Translate(outline, xOffset, yOffset)
    ccall((:FT_Outline_Translate, libfreetype), Cvoid, (Ptr{FT_Outline}, FT_Pos, FT_Pos), outline, xOffset, yOffset)
end

function FT_Outline_Copy(source, target)
    ccall((:FT_Outline_Copy, libfreetype), FT_Error, (Ptr{FT_Outline}, Ptr{FT_Outline}), source, target)
end

function FT_Outline_Transform(outline, matrix)
    ccall((:FT_Outline_Transform, libfreetype), Cvoid, (Ptr{FT_Outline}, Ptr{FT_Matrix}), outline, matrix)
end

function FT_Outline_Embolden(outline, strength)
    ccall((:FT_Outline_Embolden, libfreetype), FT_Error, (Ptr{FT_Outline}, FT_Pos), outline, strength)
end

function FT_Outline_EmboldenXY(outline, xstrength, ystrength)
    ccall((:FT_Outline_EmboldenXY, libfreetype), FT_Error, (Ptr{FT_Outline}, FT_Pos, FT_Pos), outline, xstrength, ystrength)
end

function FT_Outline_Reverse(outline)
    ccall((:FT_Outline_Reverse, libfreetype), Cvoid, (Ptr{FT_Outline},), outline)
end

function FT_Outline_Get_Bitmap(library, outline, abitmap)
    ccall((:FT_Outline_Get_Bitmap, libfreetype), FT_Error, (FT_Library, Ptr{FT_Outline}, Ptr{FT_Bitmap}), library, outline, abitmap)
end

function FT_Outline_Render(library, outline, params)
    ccall((:FT_Outline_Render, libfreetype), FT_Error, (FT_Library, Ptr{FT_Outline}, Ptr{FT_Raster_Params}), library, outline, params)
end

function FT_Outline_Get_Orientation(outline)
    ccall((:FT_Outline_Get_Orientation, libfreetype), FT_Orientation, (Ptr{FT_Outline},), outline)
end
# Julia wrapper for header: ftparams.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftpfr.h
# Automatically generated using Clang.jl

function FT_Get_PFR_Metrics(face, aoutline_resolution, ametrics_resolution, ametrics_x_scale, ametrics_y_scale)
    ccall((:FT_Get_PFR_Metrics, libfreetype), FT_Error, (FT_Face, Ptr{FT_UInt}, Ptr{FT_UInt}, Ptr{FT_Fixed}, Ptr{FT_Fixed}), face, aoutline_resolution, ametrics_resolution, ametrics_x_scale, ametrics_y_scale)
end

function FT_Get_PFR_Kerning(face, left, right, avector)
    ccall((:FT_Get_PFR_Kerning, libfreetype), FT_Error, (FT_Face, FT_UInt, FT_UInt, Ptr{FT_Vector}), face, left, right, avector)
end

function FT_Get_PFR_Advance(face, gindex, aadvance)
    ccall((:FT_Get_PFR_Advance, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_Pos}), face, gindex, aadvance)
end
# Julia wrapper for header: ftrender.h
# Automatically generated using Clang.jl

function FT_Get_Renderer(library, format)
    ccall((:FT_Get_Renderer, libfreetype), FT_Renderer, (FT_Library, FT_Glyph_Format), library, format)
end

function FT_Set_Renderer(library, renderer, num_params, parameters)
    ccall((:FT_Set_Renderer, libfreetype), FT_Error, (FT_Library, FT_Renderer, FT_UInt, Ptr{FT_Parameter}), library, renderer, num_params, parameters)
end
# Julia wrapper for header: ftsizes.h
# Automatically generated using Clang.jl

function FT_New_Size(face, size)
    ccall((:FT_New_Size, libfreetype), FT_Error, (FT_Face, Ptr{FT_Size}), face, size)
end

function FT_Done_Size(size)
    ccall((:FT_Done_Size, libfreetype), FT_Error, (FT_Size,), size)
end

function FT_Activate_Size(size)
    ccall((:FT_Activate_Size, libfreetype), FT_Error, (FT_Size,), size)
end
# Julia wrapper for header: ftsnames.h
# Automatically generated using Clang.jl

function FT_Get_Sfnt_Name_Count(face)
    ccall((:FT_Get_Sfnt_Name_Count, libfreetype), FT_UInt, (FT_Face,), face)
end

function FT_Get_Sfnt_Name(face, idx, aname)
    ccall((:FT_Get_Sfnt_Name, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_SfntName}), face, idx, aname)
end

function FT_Get_Sfnt_LangTag(face, langID, alangTag)
    ccall((:FT_Get_Sfnt_LangTag, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_SfntLangTag}), face, langID, alangTag)
end
# Julia wrapper for header: ftstroke.h
# Automatically generated using Clang.jl

function FT_Outline_GetInsideBorder(outline)
    ccall((:FT_Outline_GetInsideBorder, libfreetype), FT_StrokerBorder, (Ptr{FT_Outline},), outline)
end

function FT_Outline_GetOutsideBorder(outline)
    ccall((:FT_Outline_GetOutsideBorder, libfreetype), FT_StrokerBorder, (Ptr{FT_Outline},), outline)
end

function FT_Stroker_New(library, astroker)
    ccall((:FT_Stroker_New, libfreetype), FT_Error, (FT_Library, Ptr{FT_Stroker}), library, astroker)
end

function FT_Stroker_Set(stroker, radius, line_cap, line_join, miter_limit)
    ccall((:FT_Stroker_Set, libfreetype), Cvoid, (FT_Stroker, FT_Fixed, FT_Stroker_LineCap, FT_Stroker_LineJoin, FT_Fixed), stroker, radius, line_cap, line_join, miter_limit)
end

function FT_Stroker_Rewind(stroker)
    ccall((:FT_Stroker_Rewind, libfreetype), Cvoid, (FT_Stroker,), stroker)
end

function FT_Stroker_ParseOutline(stroker, outline, opened)
    ccall((:FT_Stroker_ParseOutline, libfreetype), FT_Error, (FT_Stroker, Ptr{FT_Outline}, FT_Bool), stroker, outline, opened)
end

function FT_Stroker_BeginSubPath(stroker, to, open)
    ccall((:FT_Stroker_BeginSubPath, libfreetype), FT_Error, (FT_Stroker, Ptr{FT_Vector}, FT_Bool), stroker, to, open)
end

function FT_Stroker_EndSubPath(stroker)
    ccall((:FT_Stroker_EndSubPath, libfreetype), FT_Error, (FT_Stroker,), stroker)
end

function FT_Stroker_LineTo(stroker, to)
    ccall((:FT_Stroker_LineTo, libfreetype), FT_Error, (FT_Stroker, Ptr{FT_Vector}), stroker, to)
end

function FT_Stroker_ConicTo(stroker, control, to)
    ccall((:FT_Stroker_ConicTo, libfreetype), FT_Error, (FT_Stroker, Ptr{FT_Vector}, Ptr{FT_Vector}), stroker, control, to)
end

function FT_Stroker_CubicTo(stroker, control1, control2, to)
    ccall((:FT_Stroker_CubicTo, libfreetype), FT_Error, (FT_Stroker, Ptr{FT_Vector}, Ptr{FT_Vector}, Ptr{FT_Vector}), stroker, control1, control2, to)
end

function FT_Stroker_GetBorderCounts(stroker, border, anum_points, anum_contours)
    ccall((:FT_Stroker_GetBorderCounts, libfreetype), FT_Error, (FT_Stroker, FT_StrokerBorder, Ptr{FT_UInt}, Ptr{FT_UInt}), stroker, border, anum_points, anum_contours)
end

function FT_Stroker_ExportBorder(stroker, border, outline)
    ccall((:FT_Stroker_ExportBorder, libfreetype), Cvoid, (FT_Stroker, FT_StrokerBorder, Ptr{FT_Outline}), stroker, border, outline)
end

function FT_Stroker_GetCounts(stroker, anum_points, anum_contours)
    ccall((:FT_Stroker_GetCounts, libfreetype), FT_Error, (FT_Stroker, Ptr{FT_UInt}, Ptr{FT_UInt}), stroker, anum_points, anum_contours)
end

function FT_Stroker_Export(stroker, outline)
    ccall((:FT_Stroker_Export, libfreetype), Cvoid, (FT_Stroker, Ptr{FT_Outline}), stroker, outline)
end

function FT_Stroker_Done(stroker)
    ccall((:FT_Stroker_Done, libfreetype), Cvoid, (FT_Stroker,), stroker)
end

function FT_Glyph_Stroke(pglyph, stroker, destroy)
    ccall((:FT_Glyph_Stroke, libfreetype), FT_Error, (Ptr{FT_Glyph}, FT_Stroker, FT_Bool), pglyph, stroker, destroy)
end

function FT_Glyph_StrokeBorder(pglyph, stroker, inside, destroy)
    ccall((:FT_Glyph_StrokeBorder, libfreetype), FT_Error, (Ptr{FT_Glyph}, FT_Stroker, FT_Bool, FT_Bool), pglyph, stroker, inside, destroy)
end
# Julia wrapper for header: ftsynth.h
# Automatically generated using Clang.jl

function FT_GlyphSlot_Embolden(slot)
    ccall((:FT_GlyphSlot_Embolden, libfreetype), Cvoid, (FT_GlyphSlot,), slot)
end

function FT_GlyphSlot_Oblique(slot)
    ccall((:FT_GlyphSlot_Oblique, libfreetype), Cvoid, (FT_GlyphSlot,), slot)
end
# Julia wrapper for header: ftsystem.h
# Automatically generated using Clang.jl

# Julia wrapper for header: fttrigon.h
# Automatically generated using Clang.jl

# Julia wrapper for header: fttypes.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftwinfnt.h
# Automatically generated using Clang.jl

function FT_Get_WinFNT_Header(face, aheader)
    ccall((:FT_Get_WinFNT_Header, libfreetype), FT_Error, (FT_Face, Ptr{FT_WinFNT_HeaderRec}), face, aheader)
end
# Julia wrapper for header: t1tables.h
# Automatically generated using Clang.jl

function FT_Has_PS_Glyph_Names(face)
    ccall((:FT_Has_PS_Glyph_Names, libfreetype), FT_Int, (FT_Face,), face)
end

function FT_Get_PS_Font_Info(face, afont_info)
    ccall((:FT_Get_PS_Font_Info, libfreetype), FT_Error, (FT_Face, PS_FontInfo), face, afont_info)
end

function FT_Get_PS_Font_Private(face, afont_private)
    ccall((:FT_Get_PS_Font_Private, libfreetype), FT_Error, (FT_Face, PS_Private), face, afont_private)
end

function FT_Get_PS_Font_Value(face, key, idx, value, value_len)
    ccall((:FT_Get_PS_Font_Value, libfreetype), FT_Long, (FT_Face, PS_Dict_Keys, FT_UInt, Ptr{Cvoid}, FT_Long), face, key, idx, value, value_len)
end
# Julia wrapper for header: ttnameid.h
# Automatically generated using Clang.jl

# Julia wrapper for header: tttables.h
# Automatically generated using Clang.jl

function FT_Get_Sfnt_Table(face, tag)
    ccall((:FT_Get_Sfnt_Table, libfreetype), Ptr{Cvoid}, (FT_Face, FT_Sfnt_Tag), face, tag)
end

function FT_Load_Sfnt_Table(face, tag, offset, buffer, length)
    ccall((:FT_Load_Sfnt_Table, libfreetype), FT_Error, (FT_Face, FT_ULong, FT_Long, Ptr{FT_Byte}, Ptr{FT_ULong}), face, tag, offset, buffer, length)
end

function FT_Sfnt_Table_Info(face, table_index, tag, length)
    ccall((:FT_Sfnt_Table_Info, libfreetype), FT_Error, (FT_Face, FT_UInt, Ptr{FT_ULong}, Ptr{FT_ULong}), face, table_index, tag, length)
end

function FT_Get_CMap_Language_ID(charmap)
    ccall((:FT_Get_CMap_Language_ID, libfreetype), FT_ULong, (FT_CharMap,), charmap)
end

function FT_Get_CMap_Format(charmap)
    ccall((:FT_Get_CMap_Format, libfreetype), FT_Long, (FT_CharMap,), charmap)
end
# Julia wrapper for header: tttags.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftconfig.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftheader.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftmodule.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftoption.h
# Automatically generated using Clang.jl

# Julia wrapper for header: ftstdlib.h
# Automatically generated using Clang.jl


text:
function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    precompile(Tuple{typeof(SIMDPirates.capture_muladd),Expr,Nothing,Expr})
    precompile(Tuple{typeof(SIMDPirates.capture_muladd),Expr,Nothing,Symbol})
    precompile(Tuple{typeof(SIMDPirates.getneutral),Symbol,Type{Float32}})
    precompile(Tuple{typeof(SIMDPirates.getneutral),Symbol,Type{Int32}})
    precompile(Tuple{typeof(SIMDPirates.getneutral),Symbol,Type{Int64}})
    precompile(Tuple{typeof(SIMDPirates.llvmconst),Int64,Type{T} where T,Int64})
    precompile(Tuple{typeof(SIMDPirates.llvmins),Symbol,Int64,Type{T} where T})
    precompile(Tuple{typeof(SIMDPirates.mulexpr),SubArray{Any,1,Array{Any,1},Tuple{UnitRange{Int64}},true}})
    precompile(Tuple{typeof(SIMDPirates.subvector),String,Int64,String,String,Int64,Int64})
    precompile(Tuple{typeof(SIMDPirates.vsub),VectorizationBase.SVec{8,Float32},VectorizationBase.SVec{8,Float64}})
end


text:
## Low level gemm! call with pointers
## Borrowed from Knet.jl

using Base.LinAlg
using Base.LinAlg.BLAS: libblas, BlasInt,  @blasfunc

# C := alpha*op(A)*op(B) + beta*C, where:
# op(X) is one of op(X) = X, or op(X) = XT, or op(X) = XH,
# alpha and beta are scalars,
# A, B and C are matrices:
# op(A) is an m-by-k matrix,
# op(B) is a k-by-n matrix,
# C is an m-by-n matrix.

for (gemm, elty) in ((:dgemm_,:Float64), (:sgemm_,:Float32))
    @eval begin
        function gemm!(transA::Char, transB::Char, M::Int, N::Int, K::Int, alpha::($elty), A::Ptr{$elty}, B::Ptr{$elty}, beta::($elty), C::Ptr{$elty})
            if transA=='N'; lda=M; else; lda=K; end
            if transB=='N'; ldb=K; else; ldb=N; end
            ldc = M;
            ccall((@blasfunc($gemm), libblas), Void,
                  (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt},
                   Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt},
                   Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty},
                   Ptr{BlasInt}),
                  &transA, &transB, &M, &N, &K,
                  &alpha, A, &lda, B, &ldb, &beta, C, &ldc)
        end
    end
end


text:
using Documenter, CliffordAlgebras

makedocs(
    sitename = "CliffordAlgebras.jl Documentation",
    modules = [CliffordAlgebras]
)

deploydocs(
    repo = "github.com/ATell-SoundTheory/CliffordAlgebras.jl.git",
    versions = nothing,
)

max_stars_repo_name: ATell-SoundTheory/CliffordAlgebras

max_issues_repo_name: ATell-SoundTheory/CliffordAlgebras


text:
using Convex
using SCS
using LinearAlgebra

"
The Goemans-Williamson algorithm for the MAXCUT problem.

From: https://github.com/ericproffitt/MaxCut
"

function goemansWilliamson(W::Matrix{T}; tol::Real=1e-1, iter::Int=100) where T<:Real
	"Partition a graph into two disjoint sets such that the sum of the edge weights
	which cross the partition is as large as possible (known to be NP-hard)."

	"A cut of a graph can be produced by assigning either 1 or -1 to each vertex.  The Goemans-Williamson
	algorithm relaxes this binary condition to allow for vector assignments drawn from the (n-1)-sphere
	(choosing an n-1 dimensional space will ensure seperability).  This relaxation can then be written as
	an SDP.  Once the optimal vector assignments are found, origin centered hyperplanes are generated and
	their corresponding cuts evaluated.  After 'iter' trials, or when the desired tolerance is reached,
	the hyperplane with the highest corresponding binary cut is used to partition the vertices."

	"W:		Adjacency matrix."
	"tol:	Maximum acceptable distance between a cut and the MAXCUT upper bound."
	"iter:	Maximum number of hyperplane iterations before a cut is chosen."

	LinearAlgebra.checksquare(W)
	@assert LinearAlgebra.issymmetric(W)	"Adjacency matrix must be symmetric."
	@assert all(W .>= 0)			"Entries of the adjacency matrix must be nonnegative."
	@assert all(diag(W) .== 0)		"Diagonal entries of adjacency matrix must be zero."
	@assert tol > 0					"The tolerance 'tol' must be positive."
	@assert iter > 0				"The number of iterations 'iter' must be a positive integer."

	"This is the standard SDP Relaxation of the MAXCUT problem, a reference can be found at
	http://www.sfu.ca/~mdevos/notes/semidef/GW.pdf."
	k = size(W, 1)
	S = Semidefinite(k)

	expr = dot(W, S)
	constr = [S[i,i] == 1.0 for i in 1:k]
	problem = minimize(expr, constr...)
	solve!(problem, SCSSolver(verbose=0))

	### Ensure symmetric positive-definite.
	A = 0.5 * (S.value + S.value')
	A += (max(0, -eigmin(A)) + eps(1e3))*I

	X = Matrix(cholesky(A))

	### A non-trivial upper bound on MAXCUT.
	upperbound = (sum(W) - dot(W, S.value)) / 4

	"Random origin-centered hyperplanes, generated to produce partitions of the graph."
	maxcut = 0
	maxpartition = nothing

	for i in 1:iter
		gweval = X' * randn(k)
		partition = (findall(x->x>0, gweval), findall(x->x<0, gweval))
		cut = sum(W[partition...])

		if cut > maxcut
			maxpartition = partition
			maxcut = cut
		end

		upperbound - maxcut < tol && break
		i == iter && println("Max iterations reached.")
	end
	return round(maxcut; digits=3), maxpartition
end

using Test
@testset "max cut" begin
	W = [0 5 2 1 0;
		 5 0 3 2 0;
		 2 3 0 0 0;
		 1 2 0 0 4;
		 0 0 0 4 0]

	maxcut, maxpartition = goemansWilliamson(W)
	@test maxcut == 14
	@test [2,5] in maxpartition
end


text:
module RecallsAnalysis

using Recalls
using DataFrames

function note_dataframe(notes = Recalls.NOTES; sortby = :timestamp)
    df = DataFrame(Recalls.note_table(notes), copycols = false)
    if sortby !== nothing
        sort!(df, sortby)
    end
    return df
end

function variables_dataframe(variables)
    foldl(variables, init = DataFrame()) do df, row
        push!(df, row; cols = :union)
    end
end

function splat_variables(df = note_dataframe(); copycols = true, makeunique = true)
    return hcat(
        variables_dataframe(df.variables),
        select(df, Not(:variables), copycols = false),
        copycols = copycols,
        makeunique = makeunique,
    )
end

function note_dataframes_groupby_location(notes = Recalls.NOTES)
    dfs = DataFrame[]
    for gdf in groupby(note_dataframe(notes), :location)
        push!(dfs, splat_variables(gdf))
    end
    return dfs
end

end


text:
@testset "hermite polynomials" begin
  x = -5:0.5:5
  @test hermite.(0, x) ≈ ones(size(x))
  @test hermite.(1, x) ≈ x
  @test hermite.(2, x) ≈ @. x^2 - 1
  @test hermite.(3, x) ≈ @. x^3 - 3 * x
  @test hermite.(4, x) ≈ @. x^4 - 6 * x^2 + 3
  @test hermite.(5, x) ≈ @. x^5 - 10 * x^3 + 15 * x
  @test hermite.(6, x) ≈ @. x^6 - 15 * x^4 + 45 * x^2 - 15
  @test hermite.(7, x) ≈ @. x^7 - 21 * x^5 + 105 * x^3 - 105 * x
  @test hermite.(8, x) ≈ @. x^8 - 28 * x^6 + 210 * x^4 - 420 * x^2 + 105
  @test hermite.(9, x) ≈ @. x^9 - 36 * x^7 + 378 * x^5 - 1260 * x^3 + 945 * x
  @test hermite.(10, x) ≈ @. x^10 - 45 * x^8 + 630 * x^6 - 3150 * x^4 + 4725 * x^2 - 945
end

@testset "HermiteBasis dimensions" begin
  # all have at most length 3, so should not depend higher-order components
  indices = [[0, 1, 2], [3, 4, 1], [1, 1, 1], [0], [1, 2], [5, 8]]
  basis = HermiteBasis(indices)
  @test length(basis) == length(indices)
  for _=1:100
    theta_base = randn(3)
    theta_useless = randn(5)
    theta = [theta_base..., theta_useless...]
    theta_prime = [theta_base..., similar(theta_useless)...]
    @test basis(theta) ≈ basis(theta_prime)
  end
end

function finite_diff(f, epsilon, i)
  function diff(x)
    epsilon_vec = zeros(length(x))
    epsilon_vec[i] = epsilon
    (f(x .+ epsilon_vec)[i] - f(x)[i]) / epsilon
  end
end

@testset "TransportFamily{HermiteBasis} inversion" begin
  # create a typical Hermite family
  T = TransportFamily([
    HermiteBasis([[0], [1], [2], [3]]),
    HermiteBasis([[0, 1], [1, 0], [1, 1]]),
    HermiteBasis([[0, 0, 2], [0, 2, 0], [2, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]),
  ])
  r = randn(3)
  while true
    # sample a gamma that suggests the map is monotonic
    gamma = [randn(4), randn(3), randn(6)]
    Tgam = T(gamma)
    points = map(_ -> randn(3), 1:1000)
    if !all(i -> all(point -> finite_diff(Tgam, 1e-5, i)(point) > 1e-8, points), 1:3)
      continue
    end

    # with such a gamma, it is very likely the map is invertible: test inversion
    @test Tgam(inverse(Tgam, r)) ≈ r
    break
  end
end

max_stars_repo_name: mvarble/gen-transport-mcmc

max_issues_repo_name: mvarble/gen-transport-mcmc

max_forks_repo_name: mvarble/gen-transport-mcmc


text:
function initialize!(integrator, cache::DImplicitEulerCache) end
function initialize!(integrator, cache::DImplicitEulerConstantCache) end

@muladd function perform_step!(integrator, cache::DImplicitEulerConstantCache, repeat_step=false)
  @unpack t,dt,uprev,u,f,p = integrator
  alg = unwrap_alg(integrator, true)

  # initial guess
  guess = zero(u)

  # Wont work for non-mutable types
  zero_func! = (out, x) -> begin
                out = f((x .- uprev) ./ dt, x, p, t)
              end
  u = NLsolve.nlsolve(zero_func!, guess).zero

  if integrator.opts.adaptive && integrator.success_iter > 0
    # local truncation error (LTE) bound by dt^2/2*max|y''(t)|
    # use 2nd divided differences (DD) a la SPICE and Shampine

    # TODO: check numerical stability
    uprev2 = integrator.uprev2
    tprev = integrator.tprev

    dt1 = dt*(t+dt-tprev)
    dt2 = (t-tprev)*(t+dt-tprev)
    c = 7/12 # default correction factor in SPICE (LTE overestimated by DD)
    r = c*dt^2 # by mean value theorem 2nd DD equals y''(s)/2 for some s

    tmp = r*integrator.opts.internalnorm.((u - uprev)/dt1 - (uprev - uprev2)/dt2,t)
    atmp = calculate_residuals(tmp, uprev, u, integrator.opts.abstol, integrator.opts.reltol,integrator.opts.internalnorm,t)
    integrator.EEst = integrator.opts.internalnorm(atmp,t)
  else
    integrator.EEst = 1
  end

  integrator.u = u
end

@muladd function perform_step!(integrator, cache::DImplicitEulerCache, repeat_step=false)
  @unpack t,dt,uprev,u,f,p = integrator
  @unpack atmp,tmp = cache
  alg = unwrap_alg(integrator, true)

  # initial guess
  guess = tmp
  guess .= zero(eltype(u))

  zero_func! = (out, x) -> begin
                f(out, (x .- uprev) ./ dt, x, p, t)
              end
  u .= NLsolve.nlsolve(zero_func!, guess).zero

  if integrator.opts.adaptive && integrator.success_iter > 0
    # local truncation error (LTE) bound by dt^2/2*max|y''(t)|
    # use 2nd divided differences (DD) a la SPICE and Shampine

    # TODO: check numerical stability
    uprev2 = integrator.uprev2
    tprev = integrator.tprev

    dt1 = dt*(t+dt-tprev)
    dt2 = (t-tprev)*(t+dt-tprev)
    c = 7/12 # default correction factor in SPICE (LTE overestimated by DD)
    r = c*dt^2 # by mean value theorem 2nd DD equals y''(s)/2 for some s

    @.. tmp = r*integrator.opts.internalnorm((u - uprev)/dt1 - (uprev - uprev2)/dt2,t)
    calculate_residuals!(atmp, tmp, uprev, u, integrator.opts.abstol, integrator.opts.reltol,integrator.opts.internalnorm,t)
    integrator.EEst = integrator.opts.internalnorm(atmp,t)
  else
    integrator.EEst = 1
  end
end


text:
@testset "evaluating sphere" begin
    sphere1 = ImplicitSphere(v0, 1.0)
    @test sphere1.center === v0
    @test sphere1.radius === 1.0

	sp2 = ImplicitSphere([0,0,0], 15.0)
	@test sp2.center === SVector(0.0, 0, 0)
	@test sp2.radius === 15.0

	sp3 = ImplicitSphere([0,0,0], 15)
	@test sp3.center === SVector(0, 0, 0)
	@test sp3.radius === 15

	sp4 = ImplicitSphere([0,0,0.], 15)
	@test sp4.center === SVector(0., 0, 0)
	@test sp4.radius === 15.0

    @test isapprox(value(evaluate(sphere1, v0)), -1)

    @test isapprox(value(evaluate(sphere1, SVector(1, 0, 0))), 0)
    @test isapprox(value(evaluate(sphere1, SVector(1.0, 0.0, 0.0))), 0)
    @test isapprox(value(evaluate(sphere1, SVector(0.0, 1.0, 0.0))), 0)
    @test isapprox(value(evaluate(sphere1, SVector(0.0, 0.0, 1.0))), 0)

    @test value(evaluate(sphere1, SVector(0, 0, 1.0001))) > 0

    sphere2 = ImplicitSphere(SVector(-1.0, -1.0, -1.0), 1.0)
    @test isapprox(value(evaluate(sphere2, SVector(-1.0, -1.0, -1.0))), -1)

    @test isapprox(value(evaluate(sphere2, SVector(-1, -1, 0))), 0)
    @test isapprox(value(evaluate(sphere2, SVector(-1.0, -1.0, 0.0))), 0)
    @test isapprox(value(evaluate(sphere2, SVector(-1.0, 0.0, -1.0))), 0)
    @test isapprox(value(evaluate(sphere2, SVector(-1.0, -1.0, 0.0))), 0)

    @test value(evaluate(sphere2, SVector(0, 0, 0))) > 0
    @test value(evaluate(sphere2, SVector(-1.0001, -1.0, 0.0))) > 0

    sphere3 = ImplicitSphere(SVector(5, 5, 5), 5)

    @test isapprox(value(evaluate(sphere3, SVector(5, 5, 0))), 0)
    @test isapprox(value(evaluate(sphere3, SVector(5.0, 5.0, 0.0))), 0)
    @test isapprox(value(evaluate(sphere3, SVector(5.0, 0.0, 5.0))), 0)
    @test isapprox(value(evaluate(sphere3, SVector(0.0, 5.0, 5.0))), 0)

    @test value(evaluate(sphere3,SVector(0.0, 5.0001, 5.0))) > 0

    # Integer
    sphere4 = ImplicitSphere(SVector(0, 0, 0), 1)
    @test isapprox(value(evaluate(sphere1, v0)), -1)
end

@testset "evaluating plane" begin
    n1 = SVector(1,0,0.0);
    pl1 = ImplicitPlane(n1, n1)

    @test pl1.normal === n1
    @test pl1.point === n1

	pl2 = ImplicitPlane([0,0,0], [1,0,0])
	@test pl2.point === SVector(0,0,0)
	@test pl2.normal === SVector(1,0,0)

	pl3 = ImplicitPlane([0.,0,0], [1,0,0])
	@test pl3.point === SVector(0.,0,0)
	@test pl3.normal === SVector(1.,0,0)

    @test isapprox(value(evaluate(pl1, n1)), 0)
    @test isapprox(value(evaluate(pl1, SVector(0,0,0))), -1)
    @test isapprox(value(evaluate(pl1, SVector(2,0,0))), 1)

    @test value(evaluate(pl1, SVector(0.9999,0,0))) < 0
    @test value(evaluate(pl1, SVector(1.0001,0,0))) > 0

    @test isapprox(value(evaluate(pl1, SVector(1, 17.52, -37.12))), 0)
    @test isapprox(value(evaluate(pl1, SVector(1, 9446.644, -151677.09))), 0)

    @test value(evaluate(pl1, SVector(1.0001, 17.52, -37.12))) > 0
    @test value(evaluate(pl1, SVector(1.0001, 9446.644, -151677.09))) > 0

    @test value(evaluate(pl1, SVector(0.9999, 17.52, -37.12))) < 0
    @test value(evaluate(pl1, SVector(0.9999, 9446.644, -151677.09))) < 0
end

@testset "evaluating cylinder" begin
	n1 = SVector(0, 0, 1.0)
	cyl = ImplicitCylinder(n1, v0, 1.)

	@test cyl.center === v0
	@test cyl.axis === n1
	@test cyl.radius === 1.

	cyl2 = ImplicitCylinder([0,0,1], [0,0,0], 0.00001)
	@test cyl2.axis === SVector(0.0, 0, 1)
	@test cyl2.center === SVector(0.0, 0, 0)

	cyl3 = ImplicitCylinder([0,0,1.], [0,0,0], 15)
	@test cyl3.axis === SVector(0.0, 0, 1)
	@test cyl3.center === SVector(0.0, 0, 0)

	@test isapprox(value(evaluate(cyl, [1, 0, 0])), 0)
	@test isapprox(value(evaluate(cyl, [0, 1, 0])), 0)
	@test isapprox(value(evaluate(cyl, [-1, 0, 0])), 0)
	@test isapprox(value(evaluate(cyl, [0, -1, 0])), 0)

	@test isapprox(value(evaluate(cyl, [0, 0, 1])), -1)
	@test isapprox(value(evaluate(cyl, [0, 0, -1])), -1)

	@test value(evaluate(cyl, [1.0001, 0, 0])) > 0
	@test value(evaluate(cyl, [0, 1.0001, 0])) > 0
	@test value(evaluate(cyl, [-1.0001, 0, 0])) > 0
	@test value(evaluate(cyl, [0, -1.0001, 0])) > 0

	@test value(evaluate(cyl, [0.9999, 0, 0])) < 0
	@test value(evaluate(cyl, [0, 0.9999, 0])) < 0
	@test value(evaluate(cyl, [-0.9999, 0, 0])) < 0
	@test value(evaluate(cyl, [0, -0.9999, 0])) < 0
end

@testset "surface normals" begin
	@testset "plane" begin
		n1 = SVector(1,0,0.0);
		pl1 = ImplicitPlane(n1, n1)

		@test normal(pl1, v0) == n1
		@test normal(pl1, rand(SVector{3})) == n1
		@test isapprox(dot(normal(pl1, rand(SVector{3})), [1,0,0]), 1)
	end

	@testset "cylinder" begin
		n1 = SVector(0, 0, 1.0)
		cyl = ImplicitCylinder(n1, v0, 1.)

		cyl2 = ImplicitCylinder(n1, v0, 17)

		@test normal(cyl, [1,0,0]) == normal(cyl2, [1,0,0])
		@test normal(cyl, [1,0,0]) == [1, 0, 0]

		@test normal(cyl, [3.14, 0, 5]) == [1, 0, 0]
		@test normal(cyl, [-3.14, 0, -5]) == [-1, 0, 0]

		@test normal(cyl, [0, 3.14, 5]) == [0, 1, 0]
		@test normal(cyl, [0, -3.14, -5]) == [0, -1, 0]
	end

end