text:
@testset "AStar" begin
    using Agents.Pathfinding

    moore = Pathfinding.moore_neighborhood(2)
    vonneumann = Pathfinding.vonneumann_neighborhood(2)
    gspace = GridSpace((5, 5))
    cspace = ContinuousSpace((5., 5.))
    atol = 0.0001
    @testset "constructors" begin
        # GridSpace
        @test_throws AssertionError AStar(gspace; admissibility = -1.0)
        # Default/DirectDistance metric
        cost = AStar(gspace).cost_metric
        @test typeof(cost) <: DirectDistance{2}
        @test cost.direction_costs == [10, 14]
        @test_throws AssertionError AStar(gspace; cost_metric = DirectDistance{2}([1]))
        @test_throws AssertionError AStar(
            gspace;
            diagonal_movement = false,
            cost_metric = DirectDistance{2}([])
        )

        # MaxDistance metric
        cost = AStar(gspace; cost_metric = MaxDistance{2}()).cost_metric
        @test typeof(cost) <: MaxDistance{2}

        # PenaltyMap metric
        @test_throws TypeError AStar(gspace; cost_metric = PenaltyMap)
        @test_throws AssertionError AStar(gspace; cost_metric = PenaltyMap([1 1]))

        cost = AStar(gspace; cost_metric = PenaltyMap(fill(1, 5, 5))).cost_metric
        @test typeof(cost) <: PenaltyMap{2}
        @test typeof(cost.base_metric) <: DirectDistance{2}
        @test cost.pmap == fill(1, 5, 5)

        cost = AStar(gspace; cost_metric = PenaltyMap(fill(1, 5, 5), MaxDistance{2}())).cost_metric
        @test typeof(cost) <: PenaltyMap{2}
        @test typeof(cost.base_metric) <: MaxDistance{2}
        @test cost.pmap == fill(1, 5, 5)
        pmap = zeros(Int, 1, 1, 1)
        @test_throws TypeError AStar(gspace; cost_metric = PenaltyMap(pmap))

        # ContinuousSpace
        @test_throws AssertionError AStar(cspace; walkmap = trues((10, 10)), cost_metric = PenaltyMap(fill(1, 5, 5)))
        @test_throws AssertionError AStar(cspace; walkmap = trues((10, 10)), cost_metric = PenaltyMap(fill(1, 5, 5)))

        astar = AStar(cspace; walkmap = trues(10, 10))
        @test astar isa AStar{2,true,true,Float64}
        astar = AStar(cspace; cost_metric = PenaltyMap(fill(1, 5, 5)))
        @test astar isa AStar{2,true,true,Float64}
    end

    @testset "API functions" begin
        # GridSpace
        pathfinder = AStar(gspace)
        model = ABM(Agent3, gspace; properties = (pf = pathfinder,))
        a = add_agent!((5, 2), model, 654.5)
        @test is_stationary(a, model.pf)

        plan_route!(a, (1, 3), model.pf)
        @test !is_stationary(a, model.pf)
        @test length(model.pf.agent_paths) == 1

        move_along_route!(a, model, model.pf)
        @test a.pos == (1, 3)

        delete!(model.pf.agent_paths, 1)
        @test length(model.pf.agent_paths) == 0
        @test plan_best_route!(a, [(5, 1), (1, 1), (3, 3)], model.pf) == (5, 1)
        @test length(model.pf.agent_paths) == 1

        kill_agent!(a, model, model.pf)
        @test length(model.pf.agent_paths) == 0

        @test isnothing(penaltymap(model.pf))
        pmap = fill(1, 5, 5)
        pathfinder = AStar(gspace; cost_metric = PenaltyMap(pmap))
        model = ABM(Agent3, gspace; properties = (pf = pathfinder, ))
        @test penaltymap(model.pf) == pmap

        pathfinder.walkmap[:, 3] .= false
        npos = collect(nearby_walkable((5, 4), model, model.pf))
        ans = [(4, 4), (5, 5), (1, 4), (4, 5), (1, 5)]
        @test length(npos) == length(ans)
        @test all(x in npos for x in ans)
        @test all(pathfinder.walkmap[random_walkable(model, model.pf)...] for _ in 1:10)

        sp = GridSpace((5, 5); periodic = false)
        pf = AStar(sp)
        model = ABM(Agent3, sp; properties = (pf = pf,))
        model.pf.walkmap[3, :] .= 0
        a = add_agent!((1, 3), model, 0.)
        @test plan_best_route!(a, [(1, 3), (4, 1)], model.pf) == (1, 3)
        @test isnothing(plan_best_route!(a, [(5, 3), (4, 1)], model.pf))

        # ContinuousSpace
        pathfinder = AStar(cspace; walkmap = trues(10, 10))
        model = ABM(Agent6, cspace; properties = (pf = pathfinder,))
        a = add_agent!((0., 0.), model, (0., 0.), 0.)
        @test is_stationary(a, model.pf)

        plan_route!(a, (4., 4.), model.pf)
        @test !is_stationary(a, model.pf)
        @test length(model.pf.agent_paths) == 1

        move_along_route!(a, model, model.pf, 0.35355)
        @test all(isapprox.(a.pos, (4.75, 4.75); atol))
        # test waypoint skipping
        move_agent!(a, (0.25, 0.25), model)
        plan_route!(a, (0.75, 1.25), model.pf)
        move_along_route!(a, model, model.pf, 0.807106)
        @test all(isapprox.(a.pos, (0.75, 0.849999); atol)) || all(isapprox.(a.pos, (0.467156, 0.967156); atol))
        # make sure it doesn't overshoot the end
        move_along_route!(a, model, model.pf, 20.)
        @test all(isapprox.(a.pos, (0.75, 1.25); atol))

        delete!(model.pf.agent_paths, 1)
        @test length(model.pf.agent_paths) == 0

        model.pf.walkmap[:, 3] .= 0
        @test all(get_spatial_property(random_walkable(model, model.pf), model.pf.walkmap, model) for _ in 1:10)
        rpos = [random_walkable((2.5, 0.75), model, model.pf, 2.0) for _ in 1:50]
        @test all(get_spatial_property(x, model.pf.walkmap, model) && edistance(x, (2.5, 0.75), model) <= 2.0 + atol for x in rpos)

        pcspace = ContinuousSpace((5., 5.); periodic = false)
        pathfinder = AStar(pcspace; walkmap = trues(10, 10))
        model = ABM(Agent6, pcspace; properties = (pf = pathfinder,))
        a = add_agent!((0., 0.), model, (0., 0.), 0.)
        @test all(plan_best_route!(a, [(2.5, 2.5), (4.99,0.), (0., 4.99)], model.pf) .≈ (2.5, 2.5))
        @test length(model.pf.agent_paths) == 1
        move_along_route!(a, model, model.pf, 1.0)
        @test all(isapprox.(a.pos, (0.7071, 0.7071); atol))

        model.pf.walkmap[:, 3] .= 0
        move_agent!(a, (2.5, 2.5), model)
        @test all(plan_best_route!(a, [(3., 0.3), (2.5, 2.5)], model.pf) .≈ (2.5, 2.5))
        @test isnothing(plan_best_route!(a, [(3., 0.3), (1., 0.1)], model.pf))

        kill_agent!(a, model, model.pf)
        @test length(model.pf.agent_paths) == 0

        @test isnothing(penaltymap(model.pf))
        pmap = fill(1, 10, 10)
        pathfinder = AStar(cspace; cost_metric = PenaltyMap(pmap))
        @test penaltymap(pathfinder) == pmap

        @test all(get_spatial_property(random_walkable(model, model.pf), model.pf.walkmap, model) for _ in 1:10)
        rpos = [random_walkable((2.5, 0.75), model, model.pf, 2.0) for _ in 1:50]
        @test all(get_spatial_property(x, model.pf.walkmap, model) && edistance(x, (2.5, 0.75), model) <= 2.0 + atol for x in rpos)
    end

    @testset "metrics" begin
        pfinder_2d_np_m = AStar{2,false,true,Int64,DirectDistance{2}}(
            Dict(),
            (10, 10),
            copy(moore),
            0.0,
            trues(10, 10),
            DirectDistance{2}(),
        )
        pfinder_2d_np_nm = AStar{2,false,false,Int64,DirectDistance{2}}(
            Dict(),
            (10, 10),
            copy(vonneumann),
            0.0,
            trues(10, 10),
            DirectDistance{2}(),
        )
        pfinder_2d_p_m = AStar{2,true,true,Int64,DirectDistance{2}}(
            Dict(),
            (10, 10),
            copy(moore),
            0.0,
            trues(10, 10),
            DirectDistance{2}(),
        )
        pfinder_2d_p_nm = AStar{2,true,false,Int64,DirectDistance{2}}(
            Dict(),
            (10, 10),
            copy(vonneumann),
            0.0,
            trues(10, 10),
            DirectDistance{2}(),
        )
        pmap = fill(0, 10, 10)
        pmap[:, 6] .= 100
        pmap[1, 6] = 0

        @test delta_cost(pfinder_2d_np_m, DirectDistance{2}(), (1, 1), (4, 6)) == 62
        @test delta_cost(pfinder_2d_p_m, DirectDistance{2}(), (1, 1), (8, 6)) == 62
        @test delta_cost(pfinder_2d_np_nm, DirectDistance{2}(), (1, 1), (4, 6)) == 80
        @test delta_cost(pfinder_2d_p_nm, DirectDistance{2}(), (1, 1), (8, 6)) == 80

        @test delta_cost(pfinder_2d_np_m, MaxDistance{2}(), (1, 1), (4, 6)) == 5
        @test delta_cost(pfinder_2d_p_m, MaxDistance{2}(), (1, 1), (8, 6)) == 5
        @test delta_cost(pfinder_2d_np_nm, MaxDistance{2}(), (1, 1), (4, 6)) == 5
        @test delta_cost(pfinder_2d_p_nm, MaxDistance{2}(), (1, 1), (8, 6)) == 5

        @test delta_cost(pfinder_2d_np_m, PenaltyMap(pmap), (1, 1), (4, 6)) == 162
        @test delta_cost(pfinder_2d_p_m, PenaltyMap(pmap), (1, 1), (8, 6)) == 162
        @test delta_cost(pfinder_2d_np_nm, PenaltyMap(pmap), (1, 1), (4, 6)) == 180
        @test delta_cost(pfinder_2d_p_nm, PenaltyMap(pmap), (1, 1), (8, 6)) == 180
    end

    @testset "pathing" begin
        wlk = trues(7, 6)
        wlk[2:7, 1] .= false
        wlk[7, 3:6] .= false
        wlk[[2:4; 6], 4] .= false
        wlk[2:5, 5] .= false
        wlk[2, 2] = false
        wlk[4, 3] = false
        wlk[5, 3] = false

        pfinder_2d_np_m = AStar{2,false,true,Float64,DirectDistance{2}}(
            Dict(),
            (10., 10.),
            copy(moore),
            0.0,
            wlk,
            DirectDistance{2}(),
        )
        pfinder_2d_np_nm = AStar{2,false,false,Float64,DirectDistance{2}}(
            Dict(),
            (10., 10.),
            copy(vonneumann),
            0.0,
            wlk,
            DirectDistance{2}(),
        )
        pfinder_2d_p_m = AStar{2,true,true,Float64,DirectDistance{2}}(
            Dict(),
            (10., 10.),
            copy(moore),
            0.0,
            wlk,
            DirectDistance{2}(),
        )
        pfinder_2d_p_nm = AStar{2,true,false,Float64,DirectDistance{2}}(
            Dict(),
            (10., 10.),
            copy(vonneumann),
            0.0,
            wlk,
            DirectDistance{2}(),
        )

        p = collect(Pathfinding.find_path(pfinder_2d_np_m, (1, 1), (6, 6)))
        @test p == [(1, 2), (1, 3), (1, 4), (1, 5), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6)]
        p = collect(Pathfinding.find_path(pfinder_2d_np_nm, (1, 1), (6, 6)))
        @test p ==
            [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6)]
        p = collect(Pathfinding.find_path(pfinder_2d_p_m, (1, 1), (6, 6)))
        @test p == [(2, 6), (3, 6), (4, 6), (5, 6), (6, 6)]
        p = collect(Pathfinding.find_path(pfinder_2d_p_nm, (1, 1), (6, 6)))
        @test p == [(1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6)]

        # Continuous
        model = ABM(Agent6, ContinuousSpace((10., 10.)))
        p = collect(Pathfinding.find_continuous_path(pfinder_2d_np_m, (0.25, 0.25), (7.8, 9.5)))
        testp = [(0.71429, 2.5), (0.71429, 4.16667), (0.71429, 5.83333), (0.71429, 7.5), (2.14286, 9.16667), (3.57143, 9.16667), (5.0, 9.16667), (6.42857, 9.16667), (7.85714, 9.16667), (7.8, 9.5)]
        @test length(p) == length(testp)
        @test all(all(isapprox.(p[i], testp[i]; atol)) for i in 1:length(p))

        p = collect(Pathfinding.find_continuous_path(pfinder_2d_p_m, (0.25, 0.25), (7.8, 9.5)))
        testp = [(2.14286, 9.16667), (3.57143, 9.16667), (5.0, 9.16667), (6.42857, 9.16667), (7.85714, 9.16667), (7.8, 9.5)]
        @test length(p) == length(testp)
        @test all(all(isapprox.(p[i], testp[i]; atol)) for i in 1:length(p))
    end
end


text:
##################################################
############### LOAD DATA ########################
##################################################

include(joinpath(dirname(@__FILE__), "data_tests/test01.jl"))
omib_sys_file = System(PowerModelsData(omib_file_dir), runchecks = false)

##################################################
############### SOLVE PROBLEM ####################
##################################################
#Define Fault: Change of YBus
Ybus_change = ThreePhaseFault(
    1.0, #change at t = 1.0
    Ybus_fault,
) #New YBus

path1 = (joinpath(pwd(), "test-Base-1"))
!isdir(path1) && mkdir(path1)
try
    #Define Simulation Problem
    sim = Simulation(
        path1,
        omib_sys, #system
        (0.0, 30.0), #time span
        Ybus_change;
        system_to_file = true,
    )

    o_system = System(joinpath(path1, "input_system.json"))
    for b in get_components(Bus, o_system)
        b_sys = get_component(Bus, omib_sys, get_name(b))
        b_file = get_component(Bus, omib_sys_file, get_name(b))
        @test get_angle(b) == get_angle(b_sys)
        @test get_angle(b) == get_angle(b_file)
    end

finally
    @info("removing test files")
    rm(path1, force = true, recursive = true)
end

path2 = (joinpath(pwd(), "test-Base-2"))
!isdir(path2) && mkdir(path2)
try
    #Define Simulation Problem
    sim = Simulation!(
        path2,
        omib_sys, #system
        (0.0, 30.0), #time span
        Ybus_change;
        system_to_file = true,
    )

    m_system = System(joinpath(path2, "initialized_system.json"))
    for b in get_components(Bus, m_system)
        b_sys = get_component(Bus, omib_sys, get_name(b))
        b_file = get_component(Bus, omib_sys_file, get_name(b))
        @test get_angle(b) == get_angle(b_sys)
        if get_bustype(b) == PSY.BusTypes.REF
            @test get_angle(b) == get_angle(b_file)
        else
            @test get_angle(b) != get_angle(b_file)
        end
    end

finally
    @info("removing test files")
    rm(path2, force = true, recursive = true)
end

ext: jl


text:
"""
    tinker08MF(lnν, z, Δm)

Halo multiplicity function.

*Reference*: Equation (3, 5-8) and Table 2 of Tinker et al., ApJ, 688, 709 (2008)
- `tinker08MF(lnν, z, Δm)` corresponds to f(σ)/2 in this reference, where σ=√(δc/ν).

# Arguments
- `lnν::Real`: natural logarithm of a threshold, ν, i.e., `lnν` = log(ν), defined by ν ≡ [δc/σ(R,z)]^2. Here, δc = 1.6865 and σ(R,z) is the r.m.s. mass fluctuation within a top-hat smoothing of scale R at a redshift `z`.
- `z::Real`: redshift.
- `Δm::Real`: overdensity within a spherical region of radius R, whose mean density is equal to Δm times the mean **mass** density of the Universe.

Tinker et al. (2008)'s multiplicity function is NOT normalized, i.e,

``∫_-∞^∞ dlnν tinker08MF(lnν, z, Δm) ≠ 1``

This function is based on [Cosmology Routine Library (CRL)](https://wwwmpa.mpa-garching.mpg.de/~komatsu/crl/).
"""
function tinker08MF(lnν::Real, z::Real, Δm::Real)
    Δ = [200, 300, 400, 600, 800, 1200, 1600, 2400, 3200]
    A0 = [0.186, 0.200, 0.212, 0.218, 0.248, 0.255, 0.260, 0.260, 0.260]
    a0 = [1.47, 1.52, 1.56, 1.61, 1.87, 2.13, 2.30, 2.53, 2.66]
    b0 = [2.57, 2.25, 2.05, 1.87, 1.59, 1.51, 1.46, 1.44, 1.41]
    c0 = [1.19, 1.27, 1.34, 1.45, 1.58, 1.80, 1.97, 2.24, 2.44]
    As = Spline1D(Δ, A0)
    as = Spline1D(Δ, a0)
    bs = Spline1D(Δ, b0)
    cs = Spline1D(Δ, c0)
    α = 10^(-(0.75 / log10(Δm / 75))^1.2)
    if z < 3
        A = As(Δm) * (1 + z)^-0.14
        a = as(Δm) * (1 + z)^-0.06
        b = bs(Δm) * (1 + z)^-α
    else
        A = As(Δm) * 4^-0.14
        a = as(Δm) * 4^-0.06
        b = bs(Δm) * 4^-α
    end
    c = cs(Δm)
    ν = exp(lnν)
    σ = 1.6865 / √ν
    mf = 0.5 * A * ((σ / b)^-a + 1) * exp(-c / σ^2)
end

"""
    tinker10MF(lnν, z, Δm)

Halo multiplicity function.

*Reference*: Equation (8-12) and Table 4 of Tinker et al., ApJ, 724, 878 (2010)
- `tinker10MF(lnν, z, Δm)` corresponds to f(σ)/2 in this reference, where σ=√(δc/ν).

# Arguments
- `lnν::Real`: natural logarithm of a threshold, ν, i.e., `lnν` = log(ν), defined by ν ≡ [δc/σ(R,z)]^2. Here, δc = 1.6865 and σ(R,z) is the r.m.s. mass fluctuation within
    a top-hat smoothing of scale R at a redshift `z`.
- `z::Real`: redshift.
- `Δm::Real`: overdensity within a spherical region of radius R, whose mean density is equal to Δm times the mean **mass** density of the Universe.

Tinker et al. (2010)'s multiplicity function is normalized at **z=0**, i.e,

``∫_-∞^∞ dlnν tinker10MF(lnν, z=0, Δm) = 1``

It is not normalized for other `z`.

This function is based on [Cosmology Routine Library (CRL)](https://wwwmpa.mpa-garching.mpg.de/~komatsu/crl/).
"""
function tinker10MF(lnν::Real, z::Real, Δm::Real)
    Δ = [200, 300, 400, 600, 800, 1200, 1600, 2400, 3200]
    α0 = [0.368, 0.363, 0.385, 0.389, 0.393, 0.365, 0.379, 0.355, 0.327]
    β0 = [0.589, 0.585, 0.544, 0.543, 0.564, 0.623, 0.637, 0.673, 0.702]
    γ0 = [0.864, 0.922, 0.987, 1.09, 1.20, 1.34, 1.50, 1.68, 1.81]
    ϕ0 = [-0.729, -0.789, -0.910, -1.05, -1.20, -1.26, -1.45, -1.50, -1.49]
    η0 =
        [-0.243, -0.261, -0.261, -0.273, -0.278, -0.301, -0.301, -0.319, -0.336]
    αs = Spline1D(Δ, α0)
    βs = Spline1D(Δ, β0)
    γs = Spline1D(Δ, γ0)
    ϕs = Spline1D(Δ, ϕ0)
    ηs = Spline1D(Δ, η0)
    if z < 3
        β = βs(Δm) * (1 + z)^0.20
        ϕ = ϕs(Δm) * (1 + z)^-0.08
        η = ηs(Δm) * (1 + z)^0.27
        γ = γs(Δm) * (1 + z)^-0.01
    else
        β = βs(Δm) * 4^0.20
        ϕ = ϕs(Δm) * 4^-0.08
        η = ηs(Δm) * 4^0.27
        γ = γs(Δm) * 4^-0.01
    end
    ν = exp(lnν)
    σ = 1.6865 / √ν
    mf = 0.5 * αs(Δm) * (1 + (β^2 * ν)^-ϕ) * ν^η * exp(-γ * ν / 2) * √ν
end


text:
"""
    ReTest.watch(args...; kwargs...)

Run `retest(args...; kwargs...)` repeatedly each time `Revise` detects file updates.
`Revise` must be loaded beforehand in your Julia session.

!!! warning
    This experimental function is not tested and is currently very basic.
"""
function watch(args...; kwargs...)
    Revise = get_revise(true)
    logs = Revise.debug_logger(; min_level=Revise.Debug).logs
    local len
    try
        while true
            if !@isdefined(len) || length(logs) > len
                if !@isdefined(len) ||
                        any(x -> x.message != "LineOffset", @view(logs[len+1:end]))
                    try
                        retest(args...; kwargs...)
                    catch ex
                        if ex isa InterruptException
                            break
                        end
                    end
                    printstyled("\nwatching...\n", bold=true, color=:cyan)
                end
                len = length(logs)
            else
                sleep(0.1)
                Revise.revise()
            end
        end
    catch ex
        ex isa InterruptException || rethrow()
    end
    nothing
end

max_issues_repo_name: rfourquet/InlineTest

max_forks_repo_name: rfourquet/InlineTest


text:
# softmax illustration
function softmax(v)
    max = maximum(v)
    explist = [exp(x - max) for x in v]
    expsum = sum(explist)
    dist = [exp_ / expsum for exp_ in explist]
end

v = rand(5)
dist = softmax(v)

println(dist)
# softmax function: sum of classes is 1.0
println(sum(dist))

max_stars_repo_name: Bingwen-Hu/hackaway

max_issues_repo_name: Bingwen-Hu/hackaway

max_forks_repo_name: Bingwen-Hu/hackaway


text:
using FastHenryHelper
using Test

# compare what an element shows to string
function testelement(e::Element, verified::String)
  ebuf = IOBuffer()
  show(ebuf,e)
  @test String(take!(ebuf)) == verified
end

function testelementdebug(e::Element, verified::String)
  ebuf = IOBuffer()
  show(ebuf,e)
  debugio = open("debug.txt","w")
  println(debugio, String(take!(ebuf)))
  close(debugio)
  verifiedio = open("verified.txt","w")
  println(verifiedio, verified)
  close(verifiedio)
  warn("testelementdebug called")
end

include("testelement.jl")
include("groupsfortests.jl")
include("testcontext.jl")
include("testtraversetree.jl")
include("testtransform.jl")
#include("testmesh.jl")
include("testplot.jl")
include("testgroups.jl")
include("testutil.jl")


text:
# ------------------------------------------------------------------
# Licensed under the MIT License. See LICENSE in the project root.
# ------------------------------------------------------------------

"""
    LeaveOneOut(; loss=Dict())

Leave-one-out validation. Optionally, specify `loss` function
from `LossFunctions.jl` for some of the variables.

## References

* Stone. 1974. [Cross-Validatory Choice and Assessment of Statistical Predictions]
  (https://rss.onlinelibrary.wiley.com/doi/abs/10.1111/j.2517-6161.1974.tb00994.x)
"""
struct LeaveOneOut <: ErrorEstimationMethod
  loss::Dict{Symbol,SupervisedLoss}
end

LeaveOneOut(; loss=Dict()) = LeaveOneOut(loss)

function error(solver, problem, method::LeaveOneOut)
  # uniform weights
  weighting = UniformWeighting()

  # point folds
  folding = PointFolding()

  wcv = WeightedCrossValidation(weighting, folding,
                                lambda=1, loss=method.loss)

  error(solver, problem, wcv)
end


text:
include("QuickFind.jl")
include("QuickUnion.jl")
include("WQuickUnion.jl")
include("DisjointSet.jl")

using BenchmarkTools
using StatsBase
using JLD

BenchmarkTools.DEFAULT_PARAMETERS.seconds = 2500
BenchmarkTools.DEFAULT_PARAMETERS.samples = 500000

function twoVals(n)
    s = sample(Base.OneTo(n), 2, replace = false)
    return (s[1], s[2])
end

function QuickFindSetup(n, frac)
    qf = QuickFind(n)

    while num_groups(qf) / length(qf) > frac
        vals = twoVals(n)
        unite!(qf, vals[1], vals[2])
    end
    return qf
end

function QuickUnionSetup(n, frac)
    qf = QuickUnion(n)

    while num_groups(qf) / length(qf) > frac
        vals = twoVals(n)
        unite!(qf, vals[1], vals[2])
    end
    return qf
end

function WQuickUnionSetup(n, frac)
    qf = WQuickUnion(n)

    while num_groups(qf) / length(qf) > frac
        vals = twoVals(n)
        unite!(qf, vals[1], vals[2])
    end
    return qf
end

function DisjointSetSetup(n, frac)
    qf = DisjointSet(n)

    while num_groups(qf) / length(qf) > frac
        vals = twoVals(n)
        unite!(qf, vals[1], vals[2])
    end
    return qf
end;

ns = [100, 1000, 2500, 5000, 10000, 50000, 100000, 250000, 500000]
percents = [0, 0.1, 0.25, 0.5, 0.75, 0.9]

benchmarkFindValuesQF =
    Array{BenchmarkTools.Trial,2}(undef, Base.length(ns), Base.length(percents))
benchmarkUniteValuesQF = similar(benchmarkFindValuesQF)
benchmarkRootValuesQU =
    Array{BenchmarkTools.Trial,2}(undef, Base.length(ns), Base.length(percents))
benchmarkFindValuesQU = similar(benchmarkRootValuesQU)
benchmarkUniteValuesQU = similar(benchmarkFindValuesQU)
benchmarkRootValuesWQU =
    Array{BenchmarkTools.Trial,2}(undef, Base.length(ns), Base.length(percents))
benchmarkFindValuesWQU = similar(benchmarkRootValuesWQU)
benchmarkUniteValuesWQU = similar(benchmarkFindValuesWQU)
benchmarkRootValuesDJU =
    Array{BenchmarkTools.Trial,2}(undef, Base.length(ns), Base.length(percents))
benchmarkFindValuesDJU = similar(benchmarkRootValuesDJU)
benchmarkUniteValuesDJU = similar(benchmarkFindValuesDJU)

for (nsi, n) in enumerate(ns), (pi, p) in enumerate(percents)
    qf = QuickFindSetup(n, 1 - p)
    ft = @benchmark find($qf, t) setup = (t = twoVals($n))
    benchmarkFindValuesQF[nsi, pi] = ft

    ut = @benchmark unite!(f[1], f[2]) setup =
        (f = (deepcopy($qf), twoVals($n)))
    benchmarkUniteValuesQF[nsi, pi] = ut
end

for (nsi, n) in enumerate(ns), (pi, p) in enumerate(percents)
    rt = @benchmark root(f[1], f[2][1]) setup =
        (f = (QuickUnionSetup($n, 1 - $p), twoVals($n)))
    benchmarkRootValuesQU[nsi, pi] = rt

    ft = @benchmark find(f[1], f[2][1], f[2][2]) setup =
        (f = (QuickUnionSetup($n, 1 - $p), twoVals($n)))
    benchmarkFindValuesQU[nsi, pi] = ft

    ut = @benchmark unite!(f[1], f[2][1], f[2][2]) setup =
        (f = (QuickUnionSetup($n, 1 - $p), twoVals($n)))
    benchmarkUniteValuesQU[nsi, pi] = ut
end

for (nsi, n) in enumerate(ns), (pi, p) in enumerate(percents)
    rt = @benchmark root(f[1], f[2][1]) setup =
        (f = (WQuickUnionSetup($n, 1 - $p), twoVals($n)))
    benchmarkRootValuesWQU[nsi, pi] = rt

    ft = @benchmark find(f[1], f[2][1], f[2][2]) setup =
        (f = (WQuickUnionSetup($n, 1 - $p), twoVals($n)))
    benchmarkFindValuesWQU[nsi, pi] = ft

    ut = @benchmark unite!(f[1], f[2][1], f[2][2]) setup =
        (f = (WQuickUnionSetup($n, 1 - $p), twoVals($n)))
    benchmarkUniteValuesWQU[nsi, pi] = ut
end

for (nsi, n) in enumerate(ns), (pi, p) in enumerate(percents)
    rt = @benchmark root!(f[1], f[2][1]) setup =
        (f = (DisjointSetSetup($n, 1 - $p), twoVals($n)))
    benchmarkRootValuesDJU[nsi, pi] = rt

    ft = @benchmark find!(f[1], f[2][1], f[2][2]) setup =
        (f = (DisjointSetSetup($n, 1 - $p), twoVals($n)))
    benchmarkFindValuesDJU[nsi, pi] = ft

    ut = @benchmark unite!(f[1], f[2][1], f[2][2]) setup =
        (f = (DisjointSetSetup($n, 1 - $p), twoVals($n)))
    benchmarkUniteValuesDJU[nsi, pi] = ut
end

save(
    "benchmark.jld",
    "benchmarkFindValuesQF",
    benchmarkFindValuesQF,
    "benchmarkUniteValuesQF",
    benchmarkUniteValuesQF,
    "benchmarkRootValuesQU",
    benchmarkRootValuesQU,
    "benchmarkFindValuesQU",
    benchmarkFindValuesQU,
    "benchmarkUniteValuesQU",
    benchmarkUniteValuesQU,
    "benchmarkRootValuesWQU",
    benchmarkRootValuesWQU,
    "benchmarkFindValuesWQU",
    benchmarkFindValuesWQU,
    "benchmarkUniteValuesWQU",
    benchmarkUniteValuesWQU,
    "benchmarkRootValuesDJU",
    benchmarkRootValuesDJU,
    "benchmarkFindValuesDJU",
    benchmarkFindValuesDJU,
    "benchmarkUniteValuesDJU",
    benchmarkUniteValuesDJU,
)


text:
# Model interconnections

"""
`series(sys1::LTISystem, sys2::LTISystem)`

Connect systems in series, equivalent to `sys2*sys1`
"""
series(sys1::LTISystem, sys2::LTISystem) = sys2*sys1

"""
`series(sys1::LTISystem, sys2::LTISystem)`

Connect systems in parallel, equivalent to `sys2+sys1`
"""
parallel(sys1::LTISystem, sys2::LTISystem) = sys1 + sys2

append() = LTISystem[]
"""
`append(systems::StateSpace...), append(systems::TransferFunction...)`

Append systems in block diagonal form
"""
function append(systems::StateSpace...)
    Ts = systems[1].Ts
    if !all(s.Ts == Ts for s in systems)
        error("Sampling time mismatch")
    end
    A = blockdiag([s.A for s in systems]...)
    B = blockdiag([s.B for s in systems]...)
    C = blockdiag([s.C for s in systems]...)
    D = blockdiag([s.D for s in systems]...)
    return StateSpace(A, B, C, D, Ts)
end

function append(systems::TransferFunction...)
    Ts = systems[1].Ts
    if !all(s.Ts == Ts for s in systems)
        error("Sampling time mismatch")
    end
    mat = blockdiag([s.matrix for s in systems]...)
    return TransferFunction(mat, Ts)
end

append(systems::LTISystem...) = append(promote(systems...)...)

function Base.vcat(systems::StateSpace...)
    # Perform checks
    nu = systems[1].nu
    if !all(s.nu == nu for s in systems)
        error("All systems must have same input dimension")
    end
    Ts = systems[1].Ts
    if !all(s.Ts == Ts for s in systems)
        error("Sampling time mismatch")
    end
    A = blockdiag([s.A for s in systems]...)
    B = vcat([s.B for s in systems]...)
    C = blockdiag([s.C for s in systems]...)
    D = vcat([s.D for s in systems]...)

    return StateSpace(A, B, C, D, Ts)
end

function Base.vcat(systems::TransferFunction...)
    # Perform checks
    nu = systems[1].nu
    if !all(s.nu == nu for s in systems)
        error("All systems must have same input dimension")
    end
    Ts = systems[1].Ts
    if !all(s.Ts == Ts for s in systems)
        error("Sampling time mismatch")
    end
    mat = vcat([s.matrix for s in systems]...)
    return TransferFunction(mat, Ts)
end

Base.vcat(systems::LTISystem...) = vcat(promote(systems...)...)

function Base.hcat(systems::StateSpace...)
    # Perform checks
    ny = systems[1].ny
    if !all(s.ny == ny for s in systems)
        error("All systems must have same output dimension")
    end
    Ts = systems[1].Ts
    if !all(s.Ts == Ts for s in systems)
        error("Sampling time mismatch")
    end
    A = blockdiag([s.A for s in systems]...)
    B = blockdiag([s.B for s in systems]...)
    C = hcat([s.C for s in systems]...)
    D = hcat([s.D for s in systems]...)

    return StateSpace(A, B, C, D, Ts)
end

function Base.hcat(systems::TransferFunction...)
    # Perform checks
    ny = systems[1].ny
    if !all(s.ny == ny for s in systems)
        error("All systems must have same output dimension")
    end
    Ts = systems[1].Ts
    if !all(s.Ts == Ts for s in systems)
        error("Sampling time mismatch")
    end
    mat = hcat([s.matrix for s in systems]...)
    return TransferFunction(mat, Ts)
end

Base.hcat(systems::LTISystem...) = hcat(promote(systems...)...)

function Base._cat_t(::Val{1}, T::Type{<:LTISystem}, X...)
        vcat(convert.(T, X)...)
end

function Base._cat_t(::Val{2}, T::Type{<:LTISystem}, X...)
        hcat(convert.(T, X)...)
end

# Used in typed_hvcat
Base.typed_hcat(::Type{T}, X...) where {T<:LTISystem} = hcat(convert.(T, X)...)
# Ambiguity
Base.typed_hcat(::Type{T}, X::Number...) where {T<:LTISystem, N} = hcat(convert.(T, X)...)

# function hvcat(rows::Tuple{Vararg{Int}}, systems::Union{Number,AbstractVecOrMat{<:Number},LTISystem}...)
#     T = Base.promote_typeof(systems...)
#     nbr = length(rows)  # number of block rows
#     rs = Array{T,1}(nbr)
#     a = 1
#     for i = 1:nbr
#         rs[i] = hcat(convert.(T,systems[a:a-1+rows[i]])...)
#         a += rows[i]
#     end
#     vcat(rs...)
# end

# function _get_common_sampling_time(sys_vec::Union{AbstractVector{LTISystem},AbstractVecOrMat{<:Number},Number})
#     Ts = -1.0 # Initalize corresponding to undefined sampling time
#
#     for sys in sys_vec
#         if !all(s.Ts == Ts for s in systems])
#             error("Sampling time mismatch")
#         end
#     end
#
# end

# function Base.hcat{T<:Number}(systems::Union{T,AbstractVecOrMat{T},TransferFunction}...)
#     S = promote_type(map(e->typeof(e),systems)...) # TODO: Should be simplified
#
#     idx_first_tf = findfirst(e -> isa(e, TransferFunction), systems)
#     Ts = sys_tuple[idx_first_tf].Ts
#
#     if S <: TransferFunction
#         hcat(map(e->convert(TransferFunction,e),systems)...)
#     else
#         cat(2,systems...)
#     end
# end

blockdiag(mats::Matrix...) = blockdiag(promote(mats...)...)

function blockdiag(mats::Matrix{T}...) where T
    rows = Int[size(m, 1) for m in mats]
    cols = Int[size(m, 2) for m in mats]
    res = zeros(T, sum(rows), sum(cols))
    m = 1
    n = 1
    for ind=1:length(mats)
        mat = mats[ind]
        i = rows[ind]
        j = cols[ind]
        res[m:m + i - 1, n:n + j - 1] = mat
        m += i
        n += j
    end
    return res
end


text:
# Converts infix expression into reverse Polish notation
# (Only 1-digit numbers are allowed.)

operators = {
    # opname => (operator, precedence)
    '+' => (+, 6),
    '-' => (-, 6),
    '*' => (*, 7),
    '/' => (/, 7),
}

is_operator(op) = haskey(operators, op)
get_operator(ch) = operators[ch][1];
get_precedence(ch) = operators[ch][2];
PREC_OFFSET = 100

function in2post(expr::ASCIIString)
    opstack = Char[]
    precedence_stack = Int[]
    output = Char[]
    prec_offset = 0

    for ch in expr
        if ch == '('
            prec_offset += PREC_OFFSET
        elseif ch == ')'
            prec_offset -= PREC_OFFSET
        elseif is_operator(ch)
            precedence = get_precedence(ch) + prec_offset
            while !isempty(opstack) &&
                precedence <= precedence_stack[end]
                push!(output, pop!(opstack))
                pop!(precedence_stack)
            end
            push!(opstack, ch)
            push!(precedence_stack, precedence)
        else
            push!(output, ch)
        end
    end

    if prec_offset != 0
        warn("Unbalanced parentheses!")
    end
    [output, reverse(opstack)]
end

function eval_post(postexp)
    numstack = Int[]
    for ch in postexp
        if is_operator(ch)
            b = pop!(numstack);
            a = pop!(numstack);
            push!(numstack, get_operator(ch)(a, b))
        else
            push!(numstack, ch - '0');
        end
    end
    assert(length(numstack) == 1)
    numstack[end]
end

expr = strip(readline())
postexp = in2post(expr)
@printf("The converted RPN is: %s,\nwhich = %d",
    join(postexp), eval_post(postexp))

# Conclusion: Julia is far from mature enough to use in production.

max_stars_repo_name: gyk/TrivialSolutions

max_issues_repo_name: gyk/TrivialSolutions

max_forks_repo_name: gyk/TrivialSolutions


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

mutable struct IoK8sApiCoreV1SecurityContext <: SwaggerModel
    allowPrivilegeEscalation::Any # spec type: Union{ Nothing, Bool } # spec name: allowPrivilegeEscalation
    capabilities::Any # spec type: Union{ Nothing, IoK8sApiCoreV1Capabilities } # spec name: capabilities
    privileged::Any # spec type: Union{ Nothing, Bool } # spec name: privileged
    procMount::Any # spec type: Union{ Nothing, String } # spec name: procMount
    readOnlyRootFilesystem::Any # spec type: Union{ Nothing, Bool } # spec name: readOnlyRootFilesystem
    runAsGroup::Any # spec type: Union{ Nothing, Int64 } # spec name: runAsGroup
    runAsNonRoot::Any # spec type: Union{ Nothing, Bool } # spec name: runAsNonRoot
    runAsUser::Any # spec type: Union{ Nothing, Int64 } # spec name: runAsUser
    seLinuxOptions::Any # spec type: Union{ Nothing, IoK8sApiCoreV1SELinuxOptions } # spec name: seLinuxOptions

    function IoK8sApiCoreV1SecurityContext(;allowPrivilegeEscalation=nothing, capabilities=nothing, privileged=nothing, procMount=nothing, readOnlyRootFilesystem=nothing, runAsGroup=nothing, runAsNonRoot=nothing, runAsUser=nothing, seLinuxOptions=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("allowPrivilegeEscalation"), allowPrivilegeEscalation)
        setfield!(o, Symbol("allowPrivilegeEscalation"), allowPrivilegeEscalation)
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("capabilities"), capabilities)
        setfield!(o, Symbol("capabilities"), capabilities)
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("privileged"), privileged)
        setfield!(o, Symbol("privileged"), privileged)
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("procMount"), procMount)
        setfield!(o, Symbol("procMount"), procMount)
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("readOnlyRootFilesystem"), readOnlyRootFilesystem)
        setfield!(o, Symbol("readOnlyRootFilesystem"), readOnlyRootFilesystem)
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("runAsGroup"), runAsGroup)
        setfield!(o, Symbol("runAsGroup"), runAsGroup)
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("runAsNonRoot"), runAsNonRoot)
        setfield!(o, Symbol("runAsNonRoot"), runAsNonRoot)
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("runAsUser"), runAsUser)
        setfield!(o, Symbol("runAsUser"), runAsUser)
        validate_property(IoK8sApiCoreV1SecurityContext, Symbol("seLinuxOptions"), seLinuxOptions)
        setfield!(o, Symbol("seLinuxOptions"), seLinuxOptions)
        o
    end
end # type IoK8sApiCoreV1SecurityContext

const _property_map_IoK8sApiCoreV1SecurityContext = Dict{Symbol,Symbol}(Symbol("allowPrivilegeEscalation")=>Symbol("allowPrivilegeEscalation"), Symbol("capabilities")=>Symbol("capabilities"), Symbol("privileged")=>Symbol("privileged"), Symbol("procMount")=>Symbol("procMount"), Symbol("readOnlyRootFilesystem")=>Symbol("readOnlyRootFilesystem"), Symbol("runAsGroup")=>Symbol("runAsGroup"), Symbol("runAsNonRoot")=>Symbol("runAsNonRoot"), Symbol("runAsUser")=>Symbol("runAsUser"), Symbol("seLinuxOptions")=>Symbol("seLinuxOptions"))
const _property_types_IoK8sApiCoreV1SecurityContext = Dict{Symbol,String}(Symbol("allowPrivilegeEscalation")=>"Bool", Symbol("capabilities")=>"IoK8sApiCoreV1Capabilities", Symbol("privileged")=>"Bool", Symbol("procMount")=>"String", Symbol("readOnlyRootFilesystem")=>"Bool", Symbol("runAsGroup")=>"Int64", Symbol("runAsNonRoot")=>"Bool", Symbol("runAsUser")=>"Int64", Symbol("seLinuxOptions")=>"IoK8sApiCoreV1SELinuxOptions")
Base.propertynames(::Type{ IoK8sApiCoreV1SecurityContext }) = collect(keys(_property_map_IoK8sApiCoreV1SecurityContext))
Swagger.property_type(::Type{ IoK8sApiCoreV1SecurityContext }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApiCoreV1SecurityContext[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1SecurityContext }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1SecurityContext[property_name]

function check_required(o::IoK8sApiCoreV1SecurityContext)
    true
end

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


text:
println("testing ransac")

# Just a simple line fitting test for the moment
# Adapted from fitlinedemo()
outliers = 0.2
sigma = 0.02
outsigma = 30*sigma  # outlying points have a distribution that is
                     # 30 times as spread as the inlying points
npts = 100           # Number of 3D data points
vpts = round(Int, (1-outliers)*npts)  # No of valid points
opts = npts - vpts                    # No of outlying points

# Define a line:
#    Y = m*X
#    Z = 0
m = 6
# Generate npts points in the line
X = rand(1,npts)
Y = m*X
Z = zeros(size(Y))

XYZ =  [X
    	Y
    	Z]

# Add uniform noise of +/-sigma
XYZ = XYZ + (2*rand(size(XYZ))-1)*sigma

# Generate opts random outliers
n = size(XYZ,2)
ind = randperm(n)[1:opts]  # get a random set of point indices of length opts

# Perform RANSAC fitting of the line
t = 0.02  # inlier tolerance
(V, P, inliers) = ransacfitline(XYZ, t)

# get slope of line and test values with a generous tolerance given
# the stochasic nature of things
slope = (V[2,2]-V[2,1])/(V[1,2]-V[1,1])
@test abs(slope-m) < 0.2
@test maximum(V[3,:]) < 0.1  # Check Z is close to 0


text:
@testset "KNN" begin
	using Test
	import GenerativeAD.Models.KNNAnomaly
	import StatsBase: fit!, predict

	M = 4
	N1 = 100
	N2 = 50
	X = randn(M, N1)
	Y = randn(M, N2)
	model = KNNAnomaly(3, :gamma)
	@test_throws ErrorException predict(model, Y)
	fit!(model, X)
	@test length(predict(model, Y)) == N2
	@test all(predict(model, Y, 5) .!= predict(model, Y))
	@test length(predict(model, Y, 5)) == N2
	@test all(predict(model, Y, 3, :kappa) .!= predict(model, Y))
	@test length(predict(model, Y, 3, :kappa)) == N2
	@test all(predict(model, Y, 9, :delta) .!= predict(model, Y))
	@test length(predict(model, Y, 11, :delta)) == N2
end


text:
module StomCond

include("../docstring_style.jl")

"""
Calculate the total leaf conductance of water vapor [mol m^-2 s^-1].

# Arguments

* `g_bw`: Leaf boundary layer conductance of water vapor [mol m^-2 s^-1].
* `g_sw`: Stomatal conductance of water vapor [mol m^-2 s^-1].

# See also

[`total_cond_co2`](@ref) and [`total_cond_cos`](@ref)
"""
total_cond_h2o(g_bw, g_sw) = g_bw * g_sw / (g_bw + g_sw)

end  # module


text:
__precompile__()
module SeisConvert
#This module contains a series of functions to convert seismic data
#between different formats.
# By Xiaotao Yang
#
###############################################################
"""
Data format for: SeisData, SeisChannel, SeisEvent.data
Field	Description
:n	Number of channels [^1]
:c	TCP connections feeding data to this object [^1]
:id	Channel ids. use NET.STA.LOC.CHAN format when possible
:name	Freeform channel names
:loc	Location (position) vector; any subtype of InstrumentPosition
:fs	Sampling frequency in Hz; set to 0.0 for irregularly-sampled data.
:gain	Scalar gain; divide data by the gain to convert to units
:resp	Instrument response; any subtype of InstrumentResponse
:units	String describing data units. UCUM standards are assumed.
:src	Freeform string describing data source.
:misc	Dictionary for non-critical information.
:notes	Timestamped notes; includes automatically-logged acquisition and
| processing information.
:t	Matrix of time gaps, formatted [Sample# GapLength]
| gaps are in μs measured from the Unix epoch
:x	Data
[^1]: Not present in SeisChannel objects.
"""
###############################################################
# JLD2 file format for RAW waveform data:
# The JLD2 data includes the following metadata (based on the format defined in SeisDownload):
# info/DLtimestamplist: this saves the tiem stamps as indices of each time group
# info/stationlist: this is the list of stations in each time group, defined by the timestamplist
# info/starttime: starttime of the group, can be the minimum start time for multiple data segments.
# info/endtime: endtime of the group, can be the maximum end time for multiple data segments.
# info/DL_time_unit: length of the data in time (duration), not number of samples
# SeisData under each timestamp group, the data file (attribute) is named by the stationname in stationlist.
#           Usually in the format of NET.STA.LOC.CHAN
#
###############################################################
# JLD2 file format for seismic cross-correlation data, saved in CorrData type (defined by SeisNoise package):
# The CorrData is saved under each timestamp group. CorrData may include multiple correlation data may include
# multiple segments of data, e.g., multiple hourly stacks. These stacks share the same metadata for the same
# station pair.
# The following is from SeisNoise.
#
"""
   CorrData
A structure for cross-correlations of ambient noise data.
## Fields: CorrData
| **Field** | **Description** |
|:------------|:-------------|
| :name       | Freeform channel names |
| :id         | Channel ids. use NET.STA.LOC.CHAN format when possible. |
| :loc        | Location (position) object. |
| :comp       | 1st channel, 2nd channel [ZZ,RT,..]
| :rotated    | Rotation applied: true or false
| :corr_type  | Could be: "corr", "deconv", "coh"
| :fs         | Sampling frequency in Hz. |
| :gain       | Scalar gain; divide data by the gain to convert to units  |
| :freqmin    | Minimum frequency for whitening.  |
| :freqmax    | Maximum frequency for whitening. |
| :cc_len     | Length of each correlation in seconds. |
| :cc_step    | Spacing between correlation windows in seconds. |
| :whitened   | Whitening applied.
| :time_norm  | Apply one-bit whitening with "one_bit". |
| :resp       | Instrument response object, format [zeros poles] |
| :misc       | Dictionary for non-critical information. |
| :notes      | Timestamped notes; includes automatically-logged acquisition and |
|             | processing information. |
| :maxlag     | Maximum lag time in seconds to keep from correlations. |
| :t          | Starttime of each correlation. |
| :corr       | Correlations stored in columns. |
"""
###############################################################
# SAC data format:
# Follows the standard SAC format.
#

using SeisIO

# import individual function for each conversion
include("utilities.jl")
include("sac2jld2.jl")
include("segy2jld2.jl")
include("seisconvert_parallel.jl")
include("jld22sac.jl")  #converting jld2 format to sac
include("corr2seis.jl")

end # module


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/FEMBasis.jl/blob/master/LICENSE

using Documenter, FEMBasis

makedocs(modules=[FEMBasis],
         format = Documenter.HTML(),
         checkdocs = :all,
         sitename = "FEMBasis.jl",
         pages = ["index.md"])


text:
using LambdaTAME: low_rank_matching, rank_one_matching
using LambdaTAME: search_Krylov_space, TAME_score

@testset "Matching Routines" begin

    U = rand(A_TOST.n,5)
    V = rand(B_TOST.n,5)
    X = U*V'
    x = reshape(X,A_TOST.n*B_TOST.n)
    u = rand(A_TOST.n)
    v = rand(B_TOST.n)

    mapping = Dict([(i,i) for i in 1:A_TOST.n])
    #=
    @testset "Shared" begin

        TOST_triangle_count, TOST_gaped_triangles, _ =  TAME_score(A_TOST,A_TOST,mapping)
        #UTOST_triangle_count, UTOST_gaped_triangles, _ =  LambdaTAME.TAME_score(A_UTOST,A_UTOST,mapping)
        UST_triangle_count, UST_gaped_triangles, _ = TAME_score(A_UST,A_UST,mapping)

        #@test TOST_triangle_count == UTOST_triangle_count
        @test TOST_triangle_count == UST_triangle_count

        @test TOST_gaped_triangles == UST_gaped_triangles
        #@test UTOST_gaped_triangles == UST_gaped_triangles

    end
    =#

    @testset "low level matching" begin

        # TODO: degree_based_matching()
        @inferred low_rank_matching(U,V)
        @test_nothrow low_rank_matching(U,V)
        @inferred rank_one_matching(u,v)
        @test_nothrow rank_one_matching(u,v)

        @testset "bipartite_matching_primal_dual tests" begin
            @test_nothrow bipartite_matching_primal_dual(X;primalDualTol=1e-5) #solve to a less strict degree

            val,noute,match1,match2 = @inferred bipartite_matching_primal_dual(X;primalDualTol=1e-5)
            val_adj,noute_adj,match1_adj,match2_adj = bipartite_matching_primal_dual(X';primalDualTol=1e-5)

            @test length(match1) == size(X,1) && length(match2) == size(X,2)
            @test length(match1_adj) == size(X,2) && length(match2_adj) == size(X,1) #ensure match1 is A_to_B
            @test (val == val_adj) && (noute == noute_adj)  #check symmetry
            @test match1 == match2_adj && match2 == match1_adj
        end
    end

    #=
    @testset "ΛTAME" begin
        d = 5
        U = rand(A_TOST.n,d)
        V = rand(B_TOST.n,d)

        #for returnScoringTimings in [returnTimings(),noTimings()]
            #@isinferred search_Krylov_space(B_TOST,A_TOST,V,U;returnScoringTimings)
            """
            println( search_Krylov_space(B_TOST,A_TOST,V,U;returnScoringTimings))
            @test (@inferred search_Krylov_space(B_TOST,A_TOST,V,U;returnScoringTimings)) == 1
            @test (@inferred search_Krylov_space(B_UST,A_UST,V,U;returnScoringTimings)) == 1
            @test (@inferred search_Krylov_space(B_UST_MM,A_UST_MM,V,U;returnScoringTimings)) == 1
                #work around for @inInferred macro found
                #   src: https://discourse.julialang.org/t/more-informative-inferred-especially-for-unit-testing/5481/2
            """

        TOST_best_score, TOST_best_i, TOST_best_j, TOST_best_matching = @inferred search_Krylov_space(A_TOST,B_TOST,U,V;returnScoringTimings=returnTimings())
        UST_best_score, UST_best_i, UST_best_j, UST_best_matching = @inferred search_Krylov_space(A_UST,B_UST,U,V;returnScoringTimings=returnTimings())
        UST_MM_best_score,UST_MM_best_matched_motifs, UST_MM_best_i, UST_MM_best_j, UST_MM_best_matching = @inferred search_Krylov_space(A_UST_MM,B_UST_MM,U,V;returnScoringTimings=returnTimings())

        TOST_best_score, TOST_best_i, TOST_best_j, TOST_best_matching = @inferred search_Krylov_space(A_TOST,B_TOST,U,V;returnScoringTimings=noTimings())
        UST_best_score, UST_best_i, UST_best_j, UST_best_matching = @inferred search_Krylov_space(A_UST,B_UST,U,V;returnScoringTimings=noTimings())
        UST_MM_best_score,UST_MM_best_matched_motifs, UST_MM_best_i, UST_MM_best_j, UST_MM_best_matching = @inferred search_Krylov_space(A_UST_MM,B_UST_MM,U,V;returnScoringTimings=noTimings())

        #ThirdOrderSymTensor to UnweightedSymTensor should be the same
        @test TOST_best_score == UST_best_score
        @test UST_best_i == TOST_best_i
        @test UST_best_j == TOST_best_j
        @test UST_best_matching == TOST_best_matching
        @test UST_best_matching == UST_MM_best_matching

        @test TOST_best_score == UST_MM_best_matched_motifs[end]#/(2*3)
            # MM version score is num of edges, and input is two third order tensors
            # divide by 2 for the two tensors, and 3 for the edges per triangles
        #@test UST_best_i == UST_MM_best_i
        #@test UST_best_j == UST_MM_best_j
        @test UST_best_matching == UST_best_matching
        #end
    end
    =#
    """
    @testset "LowRankTAME" begin
    end

    @testset "TAME" begin
    end
    """

    @testset "TAME_score" begin

        #TODO: update
        @testset "Embedding Based" begin

            _ = @inferred TAME_score(A_TOST,B_TOST,U,V)
            _ = @inferred TAME_score(A_TOST,B_TOST,X)
            _ = @inferred TAME_score(A_TOST,B_TOST,x)
            #_ = @inferred TAME_score(A_UTOST,B_UTOST,X)
            _ = @inferred TAME_score(A_UST,B_UST,X)
            _ = @inferred TAME_score(A_UST_MM,B_UST_MM,X)
        end
        #TODO make mapping

        @testset "Mapping Based" begin

            @testset "Higher Level" begin

                for (A,B) in [(A_TOST,B_TOST),(A_UST,B_UST),(A_UST_Cycle,B_UST_Cycle),(A_UST_MM,B_UST_MM),(A_UST_Cycle_MM,B_UST_Cycle_MM)]
                    if typeof(A) <: Vector #multimotif must have array accessed
                        m = A[1].n
                        n = B[1].n
                    else
                        m = A.n
                        n = B.n
                    end
                    A_to_B_array = collect(1:m)
                    B_to_A_array = -ones(Int,n)

                    A_to_B_dict = Dict([(i,i) for i in A_to_B_array]) #using an identity map

                    idx = 1
                    while idx <= n && idx <= m
                        B_to_A_array[idx] = idx
                        idx += 1
                    end
                    B_to_A_dict = Dict([(j,i) for (i,j) in A_to_B_dict])
                        #matchings may be incomplete

                    #check
                    for (A_to_B, B_to_A) in [(A_to_B_dict,B_to_A_dict)]#(A_to_B_array,B_to_A_array)]
                        _,gapedMotifs = TAME_score(A,A,A_to_B)
                        if typeof(A) <: Vector
                            _,A_to_B_matchedMotifs  = TAME_score(A,A,A_to_B)
                            @test all([matchedMotif == size(ten.indices,2) for (matchedMotif,ten) in zip(A_to_B_matchedMotifs,A)])
                        else
                            _,gapedMotifs = TAME_score(A,A,A_to_B)
                            @test gapedMotifs == 0
                        end

                        if typeof(A) <: Vector
                            A_to_B_score,A_to_B_matchedMotifs = TAME_score(A,B,A_to_B)
                            B_to_A_score,B_to_A_matchedMotifs = TAME_score(B,A,B_to_A)
                            check_motifMatch = all([A_to_B_m == B_to_A_m for (A_to_B_m,B_to_A_m) in zip(A_to_B_matchedMotifs,B_to_A_matchedMotifs)])
                            #check_motifMiss = all([A_to_B_g == B_to_A_g for (A_to_B_g,B_to_A_g) in zip(B_to_A_gapedMotifs,B_to_A_gapedMotifs)])
                            @test A_to_B_score == B_to_A_score
                            @test check_motifMatch
                        else
                            A_to_B_matchedMotifs,A_to_B_gapedMotifs = TAME_score(A,B,A_to_B)
                            B_to_A_matchedMotifs,B_to_A_gapedMotifs = TAME_score(B,A,B_to_A)

                            @test (A_to_B_matchedMotifs == B_to_A_matchedMotifs)
                        end
                    end
                end
            end
            @testset "Low Level" begin

            end
        end

    end

end

max_stars_repo_name: chuckcol/LambdaTAME

max_issues_repo_name: chuckcol/LambdaTAME

max_forks_repo_name: chuckcol/LambdaTAME


text:
stensor(D::Integer) = SArray{Tuple{ntuple(d -> 2, D)...}}
stensor(D::Integer, T::Type) = stensor(D){T}

export Tensor
@computed struct Tensor{D,T} # <: AbstractArray{D,T}
    values::AbstractArray{stensor(D, T),2}
    lmax::Int
end

@doc """
    struct Tensor{D,T}

Tensor of rank `D` with elements of type `T`, stored component-wise.

The components are stored "normalized", i.e. projected onto the dyad
vectors `eθ^a` and `eϕ^a`. This removes singularities at the poles by
multiplying the `ϕ` components with respective powers of `sin θ`. This
also means that covariant (index down) and contravariant (index up)
indices are represented in the same way.

eθ^a = [1, 0]           eθ_a = [1, 0]
eϕ^a = [0, 1/(sin θ)]   eϕ_a = [1, sin θ]

eθ and eϕ are orthogonal, and both have length 1.

g_ab = diag[1, (sin θ)^2]
g_ab = eθ_a eϕ_b + eθ_b eϕ_a = m_a m̄_b + m̄_a m_b

Example:

Scalar `s`: stored as is
Vector `v^a`: store `[eθ_a v^a, eϕ_a v_a]`
Tensor `t_ab`: store `t[1,1] = eθ^a eθ^b t_ab`
                     `t[1,2] = eθ^a eϕ^b t_ab`
                     `t[2,1] = eϕ^a eθ^b t_ab`
                     `t[2,2] = eϕ^a eϕ^b t_ab`
""" Tensor

export SpinTensor
struct SpinTensor{D,T} # <: AbstractVector{T}
    coeffs::AbstractArray{<:AbstractArray{T},D}
    lmax::Int
end

@doc """
    struct SpinTensor{D,T}

Tensor of rank `D` with elements of type `T`, stored separated by spin
weights.

Grouping tensor components by their spin weight allows representing
tensors via spin-weighted spherical harmonics, and allows calculating
covariant derivatives (covariant with respect to the unit sphere).

Note that we use a convention where `m^a m̄_a = 2`.
""" SpinTensor

# Convenience constructors
Tensor{D}(values::AbstractArray{<:SArray{X,T} where {X},2}, lmax::Int) where {D,T<:Number} = Tensor{D,T}(values, lmax)
Tensor{0}(values::AbstractArray{<:Number,2}, lmax::Int) = Tensor{0}(stensor(0).(values), lmax)
Tensor(values::AbstractArray{<:SArray,2}, lmax::Int) = Tensor{ndims(zero(eltype(values)))}(values, lmax)
Tensor(values::AbstractArray{<:Number,2}, lmax::Int) = Tensor{0}(values, lmax)

SpinTensor{D}(coeffs::AbstractArray{<:AbstractArray{T},D}, lmax::Int) where {D,T<:Number} = SpinTensor{D,T}(coeffs, lmax)
SpinTensor{0}(coeffs::AbstractArray{<:Number}, lmax::Int) = SpinTensor{0}(stensor(0)((coeffs,)), lmax)
SpinTensor(coeffs::AbstractArray{<:AbstractArray,D}, lmax::Int) where {D} = SpinTensor{D}(coeffs, lmax)
SpinTensor(coeffs::AbstractArray{<:Number}, lmax::Int) = SpinTensor{0}(coeffs, lmax)

# Basic operations
Base.eltype(::Tensor{D,T}) where {D,T} = T
Base.:(==)(t1::Tensor{D}, t2::Tensor{D}) where {D} = t1.lmax == t2.lmax && t1.values == t2.values
Base.isapprox(t1::Tensor{D}, t2::Tensor{D}; kws...) where {D} = t1.lmax == t2.lmax && isapprox(t1.values, t2.values; kws...)
LinearAlgebra.norm(t::Tensor; kws...) where {D} = norm(t.values; kws...)
Base.copy(t::Tensor{D}) where {D} = Tensor{D}(copy(t.values), t.lmax)
Base.zero(t::Tensor{D}) where {D} = Tensor{D}(zero(t.values), t.lmax)
Base.:-(t::Tensor{D}) where {D} = Tensor{D}(-t.values, t.lmax)
Base.conj(t::Tensor{D}) where {D} = Tensor{D}(conj(t.values), t.lmax)
function Base.:+(t1::Tensor{D}, t2::Tensor{D}) where {D}
    t1.lmax == t2.lmax || throw(DimensionMismatch())
    return Tensor{D}(t1.values + t2.values, t1.lmax)
end
function Base.:-(t1::Tensor{D}, t2::Tensor{D}) where {D}
    t1.lmax == t2.lmax || throw(DimensionMismatch())
    return Tensor{D}(t1.values - t2.values, t1.lmax)
end
Base.:*(a::Number, t::Tensor{D}) where {D} = Tensor{D}(a * t.values, t.lmax)
Base.:*(t::Tensor{D}, a::Number) where {D} = Tensor{D}(t.values * a, t.lmax)
Base.:/(t::Tensor{D}, a::Number) where {D} = Tensor{D}(t.values / a, t.lmax)

Base.eltype(::SpinTensor{D,T}) where {D,T} = T
Base.:(==)(t1::SpinTensor{D}, t2::SpinTensor{D}) where {D} = t1.lmax == t2.lmax && t1.coeffs == t2.coeffs
Base.isapprox(t1::SpinTensor{D}, t2::SpinTensor{D}; kws...) where {D} = t1.lmax == t2.lmax && isapprox(t1.coeffs, t2.coeffs; kws...)
LinearAlgebra.norm(t::SpinTensor; kws...) where {D} = norm(t.coeffs; kws...)
Base.copy(t::SpinTensor{D}) where {D} = SpinTensor{D}(copy.(t.coeffs), t.lmax)
Base.zero(t::SpinTensor{D}) where {D} = SpinTensor{D}(zero.(t.coeffs), t.lmax)
Base.:-(t::SpinTensor{D}) where {D} = SpinTensor{D}(-t.coeffs, t.lmax)
Base.conj(t::SpinTensor{D}) where {D} = SpinTensor{D}(conj(t.coeffs), t.lmax)
function Base.:+(t1::SpinTensor{D}, t2::SpinTensor{D}) where {D}
    t1.lmax == t2.lmax || throw(DimensionMismatch())
    return SpinTensor{D}(t1.coeffs + t2.coeffs, t1.lmax)
end
function Base.:-(t1::SpinTensor{D}, t2::SpinTensor{D}) where {D}
    t1.lmax == t2.lmax || throw(DimensionMismatch())
    return SpinTensor{D}(t1.coeffs - t2.coeffs, t1.lmax)
end
Base.:*(a::Number, t::SpinTensor{D}) where {D} = SpinTensor{D}(a * t.coeffs, t.lmax)
Base.:*(t::SpinTensor{D}, a::Number) where {D} = SpinTensor{D}(t.coeffs * a, t.lmax)
Base.:/(t::SpinTensor{D}, a::Number) where {D} = SpinTensor{D}(t.coeffs / a, t.lmax)

export filter_modes
function filter_modes(spintensor::SpinTensor{D}) where {D}
    T = eltype(spintensor)
    @assert T <: Complex
    coeffs = spintensor.coeffs
    lmax = spintensor.lmax
    twos = ntuple(d -> 2, D)
    weights = SVector{2}(+1, -1)
    lfilter = lmax * 2 ÷ 3
    coeffs′ = SArray{Tuple{twos...}}([
        begin
            cs = coeffs[ij]
            @assert size(cs) == ash_nmodes(lmax)
            s = sum(SVector{D,Int}(weights[i] for i in Tuple(ij)))
            [
                begin
                    l, m = ash_mode_numbers(s, ind, lmax)
                    abs(s) ≤ l ≤ lfilter && abs(m) ≤ l ? c : zero(c)
                end for (ind, c) in zip(CartesianIndices(cs), cs)
            ]
        end for ij in CartesianIndices(twos)
    ])
    return SpinTensor{D}(coeffs′, lmax)::SpinTensor{D,T}
end

"Convert `Tensor` to `SpinTensor`"
function SpinTensor{D}(tensor::Tensor{D,T}) where {D,T<:Complex}
    lmax = tensor.lmax
    # This represents `m` in terms of `eθ` and `eϕ`
    #     m^a = eθ^a + im eϕ^a
    #     m^a m_a = 0
    #     m^a m̄_a = 2
    m = SVector{2}(1, im)
    m̄ = conj(m)
    mm̄ = SVector{2}(m, m̄)
    mm̄::SVector{2,SVector{2,Complex{Int}}}
    weights = SVector{2}(+1, -1)
    twos = ntuple(d -> 2, D)
    coeffss = [
        begin
            values = [
                sum(prod(SVector{D,Complex{Int}}(mm̄[ij[d]][ab[d]] for d in 1:D)) * v[ab] for ab in CartesianIndices(twos)) for
                v in tensor.values
            ]
            s = sum(SVector{D,Int}(weights[i] for i in Tuple(ij)))
            coeffs = ash_transform(values, s, lmax)
            coeffs
        end for ij in CartesianIndices(twos)
    ]
    spintensor = SpinTensor{D}(SArray{Tuple{twos...}}(coeffss), lmax)
    return spintensor::SpinTensor{D,T}
end
SpinTensor{D}(tensor::Tensor{D,<:Real}) where {D} = SpinTensor{D}(Tensor{D}(map(x -> Complex.(x), tensor.values), tensor.lmax))
SpinTensor(tensor::Tensor{D}) where {D} = SpinTensor{D}(tensor)

"Convert `SpinTensor` to `Tensor`"
function Tensor{D}(spintensor::SpinTensor{D}) where {D}
    T = eltype(spintensor)
    @assert T <: Complex
    spintensor::SpinTensor{D,T}
    lmax = spintensor.lmax
    # See above
    m = SVector{2}(1, im)
    m̄ = conj(m)
    m̄m = SVector{2}(m̄, m)
    m̄m::SVector{2,SVector{2,Complex{Int}}}
    weights = SVector{2}(+1, -1)
    twos = ntuple(d -> 2, D)
    valuess = [
        begin
            s = sum(SVector{D,Int}(weights[i] for i in Tuple(ij)))
            values = ash_evaluate(spintensor.coeffs[ij], s, lmax)
            values
        end for ij in CartesianIndices(twos)
    ]
    values = [
        SArray{Tuple{twos...}}(
            sum(valuess[ij][n] * prod(SVector{D,Complex{Int}}(m̄m[ij[d]][ab[d]] for d in 1:D)) for ij in CartesianIndices(twos)) /
            2^D for ab in CartesianIndices(twos)
        ) for n in CartesianIndices(valuess[begin])
    ]
    tensor = Tensor{D}(values, lmax)
    return tensor::Tensor{D,T}
end
Tensor(spintensor::SpinTensor{D}) where {D} = Tensor{D}(spintensor)

export tensor_gradient!
"Calculate gradient"
function tensor_gradient!(dspintensor::SpinTensor{D1,R}, spintensor::SpinTensor{D,T}) where {D1,R<:Complex,D,T<:Complex}
    @assert D1 == D + 1
    lmax = spintensor.lmax
    @assert dspintensor.lmax == lmax

    weights = SVector{2}(+1, -1)
    twos = ntuple(d -> 2, D)
    coeffs = spintensor.coeffs
    dcoeffs = dspintensor.coeffs
    for ab in CartesianIndices(twos)
        s = sum(SVector{D,Int}(weights[ab[d]] for d in 1:D))
        ash_eth!(dcoeffs[ab, 1], coeffs[ab], s, lmax)
        dcoeffs[ab, 1] .*= -1
        ash_ethbar!(dcoeffs[ab, 2], coeffs[ab], s, lmax)
        dcoeffs[ab, 2] .*= -1
    end
    return dspintensor::SpinTensor{D + 1,R}
end

export tensor_gradient
"Calculate gradient"
function tensor_gradient(spintensor::SpinTensor{D,T}) where {D,T<:Complex}
    lmax = spintensor.lmax
    weights = SVector{2}(+1, -1)
    twos = ntuple(d -> 2, D)
    coeffs = spintensor.coeffs
    dcoeffs = [
        begin
            s = sum(SVector{D,Int}(weights[ab[d]] for d in 1:D))
            if ab1 == 1
                -ash_eth(coeffs[ab], s, lmax)
            else
                -ash_ethbar(coeffs[ab], s, lmax)
            end
        end for ab in CartesianIndices(twos), ab1 in 1:2
    ]
    dspintensor = SpinTensor{D + 1}(stensor(D + 1)(dcoeffs), lmax)
    return dspintensor::SpinTensor{D + 1,T}
end


text:
using IICGP
using Dates

rootdir = joinpath(homedir(), "Documents/git/ICGP-results/")
# rootdir = dirname(@__DIR__)
resdir = joinpath(rootdir, "results/")
#fetch_backup(rootdir, clean=true)

# Filters parameters
min_date = DateTime(2021, 11, 30, 14)
max_date = DateTime(2021, 11, 30, 15)
#savedir_index = 1
labels = Vector{String}()
colors = Vector{Symbol}()
rom_names = ["boxing"]
reducers = ["pooling"]
dotime = false
dosave = true
baselines = true

objectives_names = ["Atari score", "Atari score (≠ seed)"]
pareto_gen = [1, 9000, 17000, 25000]
pareto_xlim = (0, 1)
pareto_ylim = (0, 1)

colors = [:skyblue3]
labels = ["NSGA2"]

for rom_name in rom_names
    exp_dirs, games = get_exp_dir(resdir, min_date=min_date, max_date=max_date,
        games=[rom_name], reducers=reducers)
    process_nsga2_results(exp_dirs, games, objectives_names, colors,
        labels, pareto_gen=pareto_gen, pareto_xlim=pareto_xlim,
        pareto_ylim=pareto_ylim)
end


text:
# This is a minimal working example for running lmlovo function

using Random
using RAFF

# Set Logging.Debug for Logging
using Logging
using Base.CoreLogging

global_logger(ConsoleLogger(stdout, Logging.Debug))

gmodel!(x, t_, g) = begin
    g[1] = exp(t_ * x[2])
    g[2] = t_ * x[1] * exp(t_ * x[2]);
end

model(x, t) = x[1] * exp(t * x[2])

n = 2

np = 100

p = 70

# Set the seed for generating the same data
Random.seed!(123456789)

data, xSol = RAFF.generateNoisyData(model, n, np, p, [2.0, -0.5])

@time status, x, iter, p_, f = lmlovo(model, data, n, p)

println("True sol: $(xSol).")
println("Found: $x.")


text:
using BrokenRecord: BrokenRecord, HTTP, playback
using Dates: DateTime, Day, UTC, now
using RegistryCI: TagBot
using SimpleMock: Mock, called_with, mock
using Test: @test, @testset, @test_logs

const TB = TagBot
const GH = TB.GH

TB.AUTH[] = GH.OAuth2(get(ENV, "GITHUB_TOKEN", "abcdef"))
TB.TAGBOT_USER[] = "JuliaTagBot"
BrokenRecord.configure!(;
    path=joinpath(@__DIR__, "cassettes"),
    ignore_headers=["Authorization"],
)

@testset "is_merged_pull_request" begin
    @test !TB.is_merged_pull_request(Dict())
    @test !TB.is_merged_pull_request(Dict("pull_request" => Dict("merged" => false)))
    @test TB.is_merged_pull_request(Dict("pull_request" => Dict("merged" => true)))
end

@testset "is_cron" begin
    withenv(() -> @test(!TB.is_cron(())), "GITHUB_EVENT_NAME" => nothing)
    withenv(() -> @test(!TB.is_cron(())), "GITHUB_EVENT_NAME" => "pull_request")
    withenv(() -> @test(TB.is_cron(())), "GITHUB_EVENT_NAME" => "schedule")
end

@testset "repo_and_version_of_pull_request" begin
    body(url) = """
        - Repository: $url
        - Version: v1.2.3
        """
    github = body("https://github.com/Foo/Bar")
    @test TB.repo_and_version_of_pull_request_body(github) == ("Foo/Bar", "v1.2.3")
    ssh = body("git@github.com:Foo/Bar.git")
    @test TB.repo_and_version_of_pull_request_body(ssh) == ("Foo/Bar", "v1.2.3")
    gitlab = body("https://gitlab.com/Foo/Bar")
    @test TB.repo_and_version_of_pull_request_body(gitlab) == (nothing, "v1.2.3")
end

@testset "tagbot_file" begin
    playback("tagbot_file.bson") do
        @test TB.tagbot_file("Repo/DoesNotExist") === nothing
        @test TB.tagbot_file("torvalds/linux") === nothing
        path, contents = TB.tagbot_file("JuliaRegistries/RegistryCI.jl")
        @test path == ".github/workflows/TagBot.yml"
        @test occursin("JuliaRegistries/TagBot", contents)
        @test TB.tagbot_file("JuliaWeb/HTTP.jl") !== nothing
        @test TB.tagbot_file("JuliaWeb/HTTP.jl"; issue_comments=true) === nothing
    end
end

@testset "get_repo_notification_issue" begin
    playback("get_repo_notification_issue.bson") do
        @test_logs match_mode=:any (:info, "Creating new notification issue") begin
            issue = TB.get_repo_notification_issue("christopher-dG/TestRepo")
            @test issue.number == 11
        end
        @test_logs match_mode=:any (:info, "Found existing notification issue") begin
            issue = TB.get_repo_notification_issue("christopher-dG/TestRepo")
            @test issue.number == 11
        end
    end
end

@testset "notification_body" begin
    base = "Triggering TagBot for merged registry pull request"
    @test TB.notification_body(Dict()) == base
    event = Dict("pull_request" => Dict("html_url" => "foo"))
    @test TB.notification_body(event) == "$base: foo"
    @test occursin("extra notification", TB.notification_body(event; cron=true))
end

@testset "notify" begin
    playback("notify.bson") do
        comment = TB.notify("christopher-dG/TestRepo", 4, "test notification")
        @test comment.body == "test notification"
    end
end

@testset "collect_pulls" begin
    PR = GH.PullRequest
    prs = [
        [PR(), PR(; merged_at=now(UTC))],
        [PR(; merged_at=now(UTC) - Day(2)), PR(; merged_at=now(UTC) - Day(4))],
    ]
    pages = [Dict("next" => "abc"), Dict()]
    pulls = mock(GH.pull_requests => Mock(collect(zip(prs, pages)))) do _prs
        TB.collect_pulls("JuliaRegistries/General")
    end
    @test pulls == [prs[1][2], prs[2][1]]
end

@testset "tag_exists" begin
    playback("tag_exists.bson") do
        @test TB.tag_exists("JuliaRegistries/RegistryCI.jl", "v0.1.0")
        @test !TB.tag_exists("JuliaRegistries/RegistryCI.jl", "v0.0.0")
    end
end

@testset "maybe_notify" begin
    @test_logs match_mode=:any (:info, r"not enabled") begin
        mock(TB.tagbot_file => Mock(nothing)) do _tf
            TB.maybe_notify((), "repo", "v")
        end
    end
    @test_logs match_mode=:any (:info, r"already exists") begin
        mock(TB.tagbot_file => Mock(true), TB.tag_exists => Mock(true)) do tf, te
            TB.maybe_notify((), "repo", "v"; cron=true)
        end
    end
    mock(
        TB.tagbot_file => Mock(("path", "contents")),
        TB.get_repo_notification_issue => Mock(1),
        TB.should_fixup => Mock(false),
        TB.notification_body => Mock("foo"),
        TB.notify,
    ) do tagbot_file, get_issue, should_fixup, body, notify
        TB.maybe_notify(Dict(), "repo", "v"; cron=true)
        @test called_with(tagbot_file, "repo")
        @test called_with(get_issue, "repo")
        @test called_with(should_fixup, "repo", 1)
        @test called_with(notify, "repo", 1, "foo")
    end
end

@testset "should_fixup" begin
    mock(
        TB.fixup_comment_exists => Mock([false, true, true, true]),
        TB.fixup_done => Mock([true, false, false]),
        TB.tagbot_file => Mock([("path", "contents"), nothing]),
    ) do fce, fd, tf
        @test !TB.should_fixup("repo", 1)
        @test !TB.should_fixup("repo", 2)
        @test !TB.should_fixup("repo", 3)
        @test TB.should_fixup("repo", 4)
    end
end

@testset "get_fork" begin
    playback("get_fork.bson") do
        mock(now => tz -> DateTime(2020, 11, 5, 19, 2)) do _now
            fork = TB.get_fork("christopher-dG/TestRepo")
            @test fork isa GH.Repo
        end
    end
end

@testset "open_fixup_pr" begin
    playback("open_fixup_pr.bson") do
        fork = GH.repo("JuliaTagBot/TestRepo"; auth=TB.AUTH[])
        pr = TB.open_fixup_pr("christopher-dG/TestRepo"; branch="abc", fork=fork)
        @test pr.number == 10
    end
end

@testset "fixup_comment_exists" begin
    playback("fixup_comment_exists.bson") do
        no = GH.issue("christopher-dG/TestRepo", 7; auth=TB.AUTH[])
        yes = GH.issue("christopher-dG/TestRepo", 8; auth=TB.AUTH[])
        @test !TB.fixup_comment_exists("christopher-dG/TestRepo",no)
        @test TB.fixup_comment_exists("christopher-dG/TestRepo", yes)
    end
end

@testset "is_fixup_trigger" begin
    comment = GH.Comment(Dict("user" => Dict("login" => "foo"), "body" => "foo"))
    @test !TB.is_fixup_trigger(comment)
    comment.body = "foo bar tagbot fix baz"
    @test TB.is_fixup_trigger(comment)
    comment.user.login = TB.TAGBOT_USER[]
    @test !TB.is_fixup_trigger(comment)
end

@testset "fixup_done" begin
    playback("fixup_done.bson") do
        @test !TB.fixup_done("JuliaWeb/HTTP.jl")
        @test TB.fixup_done("christopher-dG/TestRepo")
    end
end


text:
using Base.Threads: @threads

function collect_files!(target::String, files)
	if isfile(target)
		push!(files, target)
	else
		for file in readdir(target, join=true)
			collect_files!(file, files)
		end
	end
	files
end

"""
	collect_files(target)

Walks recursively the `target` directory, collecting all files only along the way.
"""
collect_files(target) = collect_files!(target, String[])

"""
	collect_files_th(target)

Multithreaded version of recursive file collection.
Does not have as many checks as th single threaded.
May not perform as well on some configurations.
Using @threads inside recursion may not be the best idea.
"""
function collect_files_th(target::String)
    files = readdir(target, join=true)
    if all(isfile.(files))
        println(target)
        return files
    end
    results = Vector{Vector{String}}(undef, length(files))
    @threads for i in 1:length(files)
        results[i] = collect_files_th(files[i])
    end
    reduce(vcat, results)
end

function quantile_scores(score, percentage=(0.0, 1.0))
	n = length(score)
    l, r = percentage
    if l <= 0.0
        lq = 1
    else
        lq = Int(ceil(l*n))
    end
    if r >= 1.0
        rq = n
    else
        rq = Int(ceil(r*n))
    end
    perms = sortperm(score)
    indxs = perms[lq:rq]
	return score[indxs]
end


text:
module TestReturnInf

using Test
using TreeParzen

function objective(params)
    if params[:x] < 0
        return (params[:x] - 3)^2
    end

    return Inf
end
best = fmin(objective, Dict(:x => HP.Uniform(:x, -5.0, 5.0)), 50)
@test best[:x] < 0

end
true


text:
### A Pluto.jl notebook ###
# v0.11.14

using Markdown
using InteractiveUtils

# ╔═╡ 529ca324-04da-11eb-1b29-b9169082eec9
md"# Julia Cheat Sheet: Expressions"

# ╔═╡ fe6d2b02-04d9-11eb-05c9-1f701f50c7e2
x = 1;

# ╔═╡ 29d432d6-04da-11eb-27f9-791e1f8d46a7
line = "1 + $x"

# ╔═╡ 39b21588-04da-11eb-0e21-63a8e26adb3a
expr = Meta.parse(line)

# ╔═╡ 452351c0-04da-11eb-290c-7585b09fb424
typeof(expr) == Expr

# ╔═╡ 6ac50f9e-04e0-11eb-09b7-2b7a9e4f4258
dump(expr)

# ╔═╡ 98cf2366-04e0-11eb-0b8a-c56fd9a2ece7
eval(expr) == 2

# ╔═╡ Cell order:
# ╠═529ca324-04da-11eb-1b29-b9169082eec9
# ╠═fe6d2b02-04d9-11eb-05c9-1f701f50c7e2
# ╠═29d432d6-04da-11eb-27f9-791e1f8d46a7
# ╠═39b21588-04da-11eb-0e21-63a8e26adb3a
# ╠═452351c0-04da-11eb-290c-7585b09fb424
# ╠═6ac50f9e-04e0-11eb-09b7-2b7a9e4f4258
# ╠═98cf2366-04e0-11eb-0b8a-c56fd9a2ece7

max_stars_repo_name: mahiki/Julia-Cheat-Sheet

max_issues_repo_name: mahiki/Julia-Cheat-Sheet

max_forks_repo_name: mahiki/Julia-Cheat-Sheet


text:
module PrettyTables

using Parameters
using Printf
using Reexport
using Tables

@reexport using Crayons

export Highlighter, PrettyTableFormat

################################################################################
#                                    Types
################################################################################

"""
    struct PrettyTableFormat

# Fields

* `up_right_corner`: Character in the up right corner.
* `up_left_corner`: Character in the up left corner.
* `bottom_left_corner`: Character in the bottom left corner.
* `bottom_right_corner`: Character in the bottom right corner.
* `up_intersection`: Character in the intersection of lines in the up part.
* `left_intersection`: Character in the intersection of lines in the left part.
* `right_intersection`: Character in the intersection of lines in the right
                        part.
* `middle_intersection`: Character in the intersection of lines in the middle of
                         the table.
* `bottom_intersection`: Character in the intersection of the lines in the
                         bottom part.
* `column`: Character in a vertical line.
* `row`: Character in a horizontal line.
* `top_line`: If `true`, then the top table line will be drawn.
* `bottom_line`: If `true`, then the bottom table line will be drawn.

# Pre-defined formats

The following pre-defined formats are available: `unicode` (**default**),
`mysql`, `compact`, `markdown`, `simple`, `ascii_rounded`, and `ascii_dots`.

"""
@with_kw struct PrettyTableFormat
    up_right_corner::Char     = '┐'
    up_left_corner::Char      = '┌'
    bottom_left_corner::Char  = '└'
    bottom_right_corner::Char = '┘'
    up_intersection::Char     = '┬'
    left_intersection::Char   = '├'
    right_intersection::Char  = '┤'
    middle_intersection::Char = '┼'
    bottom_intersection::Char = '┴'
    column::Char              = '│'
    row::Char                 = '─'
    top_line::Bool            = true
    bottom_line::Bool         = true
end

"""
    struct Highlighter

Defines the highlighter of a table.

# Fileds

* `f`: Function with the signature `f(data,i,j)` in which should return `true`
       if the element `(i,j)` in `data` must be highlighter, or `false`
       otherwise.
* `crayon`: Crayon with the style of a highlighted element.

"""
@with_kw struct Highlighter
    f::Function
    crayon::Crayon
end

"""
    function Highlighter(f; kwargs...)

Construct a `Highlighter` with activation function `f` and pass all the keyword
arguments `kwargs` to `Crayon`.

"""
Highlighter(f; kwargs...) = Highlighter(f = f, crayon = Crayon(;kwargs...))

################################################################################
#                                  Constants
################################################################################

# Crayon used to reset all the styling.
const _reset_crayon = Crayon(reset = true)

################################################################################
#                                  Includes
################################################################################

include("predefined_formats.jl")
include("predefined_highlighters.jl")
include("predefined_formatters.jl")
include("print.jl")

end # module


text:
using StaticArrays
using Distances
using NearestNeighbors

function generate_embeddings(n, dim)
	A = rand(n, dim)
	S = SMatrix{n, dim}(A);
	v = [rand(n) for i = 1:dim]
	sv = [S[:, i] for i = 1:dim]
	positions = [rand(1:dim) for i = 1:dim]
	lags = [i for i = 1:dim]

	# Regular arrays
	E1a = cembed(A, positions, lags)
	E1b = cembed(A)

	# Static arrays
	E2a = cembed(S, positions, lags)
	E2b = cembed(S)

	E1a, E1b, E2a, E2b
end

@testset "Embedding in $D-D" for D = 2:4

	E1a, E1b, E2a, E2b = generate_embeddings(50, D)
	@test typeof(E1a) <: Embeddings.AbstractEmbedding
	@test typeof(E1b) <: Embeddings.AbstractEmbedding
	@test typeof(E2a) <: Embeddings.AbstractEmbedding
	@test typeof(E2b) <: Embeddings.AbstractEmbedding

	#inv = invariantize(E1a, verbose = true)
	#tri = DelaunayTriangulation(E1a)
	#@test typeof(inv) <: LinearlyInvariantEmbedding
	#@test typeof(tri) <: DelaunayTriangulation
end

@testset "Alignment with and without zero-lagged vector matches" begin
    ts = [rand(12) for i = 1:3]
    E1 = cembed(ts, [1, 2, 3, 3], [1, -1, -1, 0])
    E2 = cembed(ts, [1, 2, 3], [1, -1, -1])

    @test all(E1.points[1:3, :] .== E2.points)
    @test typeof(E1) <: Embeddings.AbstractEmbedding
    @test typeof(E2) <: Embeddings.AbstractEmbedding
end

@testset "Interface with NearestNeighbors.jl" begin
	E = StateSpaceReconstruction.cembed([rand(100)], [1, 1, 1, 1], [0, -3, -4, 5])
	brutetree = BruteTree(E, Euclidean())
	balltree = BallTree(E, Euclidean())
	kdtree = KDTree(E, Minkowski(2.5))
	@test typeof(brutetree) <: NearestNeighbors.BruteTree
	@test typeof(balltree) <: NearestNeighbors.BallTree
	@test typeof(kdtree) <: NearestNeighbors.KDTree
end


text:
include("../examples/mpec/bard1.jl")
include("../examples/mpec/dempe.jl")
include("../examples/mpec/gnash1m.jl")

include("../examples/mpec/bard1_test.jl")


text:
# this assumes we have already installed LogicCircuits
using LogicCircuits
using LinearAlgebra
using Plots

# Loads our local package
# We need to "activate" our local version first
import Pkg
# This assumes you are running the file from inside the Project's folder
Pkg.activate(".")
# If this is not the case, you need to give the full path address, e.g.
# Pkg.activate("/Users/denis/ProbabilisticCircuits.jl/")
# Alternatively, we can import our packages from github (but then local changes are not included)
#Pkg.add("https://github.com/denismaua/ProbabilisticCircuits.jl")
using ProbabilisticCircuits

dataSet=dataset(twenty_datasets("nltcs"); do_shuffle=false, batch_size=-1)
dataTrain = dataSet.train

#csdd = learn_credal_circuit(WXData(dataTrain), 40.0); #using clt
csdd =learn_struct_credal_circuit(WXData(dataTrain), 40.0)[1]; #using clt and vtree

# Testing conditional inference upper and lower bounds
# 1,0 observed/evidence variables values; 2,3 query varables values for 0,1;  -1 marginalize variables.

# cond_queries X=0|e ,  X=1|e , X=1| e'
cond_queries= XData(Int8.([2 1 0 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1; 3 1 0 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1; 1 1 1 1 -1 -1 -1 1 -1 1 -1 1 -1 -1 3 1 ]))

### bissection scheme

a = zeros(Float64, num_examples(cond_queries))
b = ones(Float64, num_examples(cond_queries))
m = zeros(Float64, num_examples(cond_queries))
cond_lo = zeros(Float64, num_examples(cond_queries))

aa = zeros(Float64, num_examples(cond_queries))
bb = ones(Float64, num_examples(cond_queries))
mm = zeros(Float64, num_examples(cond_queries))
cond_up = zeros(Float64, num_examples(cond_queries))

for k=1:10
    for i=1:num_examples(cond_queries)
        if conditional_lower(csdd, cond_queries, a)[i]* conditional_lower(csdd, cond_queries, b)[i] < 0.0
            m[i] = 0.5*(a[i]+b[i])
            conditional_lower(csdd, cond_queries, a)[i]* conditional_lower(csdd, cond_queries, m)[i] < 0.0 ? b[i]=m[i] : a[i]=m[i]
        end

        if conditional_upper(csdd, cond_queries, aa)[i]* conditional_upper(csdd, cond_queries, bb)[i] < 0.0
            mm[i] = 0.5*(aa[i]+bb[i])
            conditional_upper(csdd, cond_queries, aa)[i]* conditional_upper(csdd, cond_queries, mm)[i] < 0.0 ? bb[i]=mm[i] : aa[i]=mm[i]
        end
    end
end

cond_lo = 0.5*(a+b)
cond_up = 0.5*(aa+bb)

println("conditional lower probability estimated intervals = ", hcat(a,b))
println("estimated lower conditional probabilities = ", cond_lo)

println("conditional upper probability estimated intervals = ", hcat(aa,bb))
println("estimated conditional upper probabilities = ", cond_up)

# aa = zeros(Float64, num_examples(cond_queries))
# bb = ones(Float64, num_examples(cond_queries))
# mm = zeros(Float64, num_examples(cond_queries))
# cond_up = zeros(Float64, num_examples(cond_queries))
#
# for k=1:10
#     for i=1:num_examples(cond_queries)
#         if conditional_upper(csdd, cond_queries, aa)[i]* conditional_upper(csdd, cond_queries, bb)[i] < 0.0
#             mm[i] = 0.5*(aa[i]+bb[i])
#             conditional_upper(csdd, cond_queries, aa)[i]* conditional_upper(csdd, cond_queries, mm)[i] < 0.0 ? bb[i]=mm[i] : aa[i]=mm[i]
#         end
#     end
# end
#
# cond_up = 0.5*(aa+bb)
#
#
# println("conditional upper probability estimated intervals = ", hcat(aa,bb))
# println("estimated conditional upper probabilities = ", cond_up)

# Bisection Code (Alessandro)
n_iteraz = 15
mu_left = zeros(Float64, num_examples(cond_queries))
mu_right = ones(Float64, num_examples(cond_queries))
for k in 1:n_iteraz
mu_middle .= (mu_left + mu_right) ./ 2.0
f_middle = conditional_upper(csdd, cond_queries, mu_middle)
f_left = conditional_upper(csdd, cond_queries, mu_left)
f_right = conditional_upper(csdd, cond_queries, mu_right)
mu_right[f_left .* f_middle .< 0.0] .= mu_middle[f_left .* f_middle .< 0.0]
mu_left[f_left .* f_middle .>= 0.0] .= mu_middle[f_left .* f_middle .>= 0.0]
f_left = conditional_upper(csdd, cond_queries, mu_left)
f_right = conditional_upper(csdd, cond_queries, mu_right)
end
@show mu_middle

max_stars_repo_name: IDSIA/cjuice

max_issues_repo_name: IDSIA/cjuice

max_forks_repo_name: IDSIA/cjuice


text:
using GLMakie.AbstractPlotting: backend_display, getscreen

function project_sp(scene, point)
    point_px = AbstractPlotting.project(scene, point)
    offset = Point2f0(minimum(pixelarea(scene)[]))
    return point_px .+ offset
end

@testset "unit tests" begin
    @testset "Window handling" begin
        AbstractPlotting.inline!(false)
        screen = GLMakie.global_gl_screen((100, 100), false)
        @test isopen(screen)
        fig, ax, splot = scatter(1:4);
        screen2 = display(fig)
        @test screen === screen2
        # TODO overload getscreen for figure
        @test getscreen(ax.scene) === screen
        close(screen)

        # assure we correctly close screen and remove it from plot
        @test getscreen(ax.scene) === nothing
        @test !events(ax.scene).window_open[]
        @test isempty(events(ax.scene).window_open.listeners)
    end

    @testset "Pick a plot element or plot elements inside a rectangle" begin
        N = 100000
        fig, ax, splot = scatter(1:N, 1:N)
        limits!(ax, 99990,100000, 99990,100000)
        screen = display(fig)
        yield()
        # test for pick a single data point (with idx > 65535)
        point_px = project_sp(ax.scene, Point2f0(N-1,N-1))
        plot,idx = pick(ax.scene, point_px)
        @test idx == N-1

        # test for pick a rectangle of data points (also with some indices > 65535)
        rect = FRect2D(99990.5,99990.5,8,8)
        origin_px = project_sp(ax.scene, Point(origin(rect)))
        tip_px = project_sp(ax.scene, Point(origin(rect) .+ widths(rect)))
        rect_px = IRect2D(round.(origin_px), round.(tip_px .- origin_px))
        #! there is no pick(::Scene,::IRect2D)
        plot_idx = pick(screen, rect_px)

        # objects returned in plot_idx should be either grid lines (i.e. LineSegments) or Scatter points
        @test all(pi-> pi[1] isa Union{LineSegments,Scatter, AbstractPlotting.Mesh}, plot_idx)
        # scatter points should have indices equal to those in 99991:99998
        scatter_plot_idx = filter(pi -> pi[1] isa Scatter, plot_idx)
        @test Set(last.(scatter_plot_idx)) == Set(99991:99998)
    end
end


text:
###################################################
## network/iterative/state.jl
## Different iterative procedures
###################################################

"""
    `IterativeState`
    Abstract type, represents all information of a state of path/timingscomputation
    in the iterative process
    Must contain:
    - `data::NetworkData`           timing data in the network
    - `timings::NetworkTimings`     the current timings solution
    - `trips::Vector{NetworkTrip}`  trips that we currently optimize on
    - `paths::Vector{Vector{Dict{Edge, Float64}}}` path subset for each current trip datapoint. Each trip has a vector of paths associated to it. Each path is represented as a dictionary mapping edges to weights. This ensures that the path representation is consistent for all types of methods (including graph reduction). In most cases, the weights are all ones and the representation is equivalent to a vector of edges.
    - `pathDiff::Float64`           measure of difference in paths from previous step. Full definition is in paper. The lower it is, the closer we are to convergence.
    Must implement:
    - `updateState!` updates the state when new link-times are computed
"""
abstract type IterativeState end

function Base.show(io::IO, s::IterativeState)
    typeName = split(string(typeof(s)),".")[end]
    nTrips = length(s.trips)
    nPaths = sum([length(paths) for paths in s.paths])
    println(io,"Iterative heuristic: $(typeName)")
    println(io,"Optimizing on $nTrips trips and $nPaths paths")
end

NetworkTimings(it::IterativeState) = it.timings

"""
    `doIteration!`, shortcut to update state with optimizer's output
"""
function doIteration!(it::IterativeState; method::AbstractString="lp", continuityParam::Float64 = 0.1, solverArgs...)
    if method=="lp"
        updateState!(it, lpTimes(it; solverArgs...))
    elseif method=="fraclp"
        updateState!(it, fraclpTimes(it; solverArgs...))
    elseif method=="mip"
        updateState!(it, mipTimes(it; solverArgs...))
    elseif method == "heuristic"
        updateState!(it, heuristicTimes(it))
    elseif method == "socp"
        updateState!(it, socpTimes(it; solverArgs...))
    elseif method == "roadtype"
        updateState!(it, constantSpeedTimes(it; solverArgs...), updatePaths=false)
    elseif method == "constant"
        updateState!(it, constantSpeedTimes(it; uniqueSpeed=true, solverArgs...),
                     updatePaths=false)
    elseif method == "lpCo"
        updateState!(it, lpTimes(it, continuityConstraint="simple",
                                     velocityBound=continuityParam; solverArgs...))
    elseif method == "lpCoNbhd"
        updateState!(it, lpTimes(it, continuityConstraint="neighborhoods",
                                     velocityBound=continuityParam; solverArgs...))
    elseif method == "socpCo"
        updateState!(it, socpTimes(it, continuityConstraint="simple",
                                       continuityParam=continuityParam; solverArgs...))
    elseif method == "socpCoNbhd"
        updateState!(it, socpTimes(it, continuityConstraint="neighborhoods",
                                       continuityParam=continuityParam; solverArgs...))
    elseif method == "socpCoReg"
        updateState!(it, socpTimes(it, continuityConstraint="regularized",
                                       continuityParam=continuityParam; solverArgs...))
    elseif method == "pathchoice"
        updateState!(it, pathChoice(it), updatePaths=false)
    else
        error("Unknown optimizer")
    end
    return it
end


text:
module RTools

using RCall

function load_rds(path)
    R"""
    res<-readRDS($path)
    """
    @rget res
end

function save_rds(file,path)
    @rput file
    R"""
    saveRDS($file, file = $path)
    """
end

function svyby(var,by;fun="svymean",dsgn="dsgn")
    reval(" res<-svyby(~$var, by = ~$by, FUN = $fun, design = $dsgn)")
    @rget res
    rename!(res, Symbol("$var") => :Mean)
end
function svyby(var,by1,by2;fun="svymean",dsgn="dsgn")
    reval(" res<-svyby(~$var, by = ~$by1+$by2, FUN = $fun, design = $dsgn)")
    @rget res
    rename!(res, Symbol("$var") => :Mean)
end

function initialize_survey(path,id,strata,weights)
    R"""
       library(Matrix)
       library(survival)
       library(survey)
       data = readRDS($path)
       options(survey.lonely.psu='adjust')
       """
       reval(" dsgn = svydesign(id = ~$(id),
                         strata = ~$(strata),
                         weights = ~$(weights),
                         data = data,
                         nest = TRUE)"
                         )
end

export load_rds, save_rds, initialize_survey, svyby

end # module


text:
struct JupiterBarycenter <: abstractBarycenter end

naif_id(::Type{JupiterBarycenter}) = 5
parent(::Type{JupiterBarycenter}) = SSB


text:
using Sockets

function get_ip_from_host(host::String)
    # Host is ipv4
    ipv4 = r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"
    # Host is ipv6
    ipv6 = r"(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))"
    if occursin(ipv4, host) || occursin(ipv6, host)
        return host
    end
    # Domain detected, get ip
    domain = r"^(?!:\/\/)([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,11}?$"
    if occursin(domain, host)
        return getaddrinfo(host)
    end
    throw(ErrorException("Invalid target"))
end

max_stars_repo_name: thecrypters/nis

max_issues_repo_name: thecrypters/nis

max_forks_repo_name: thecrypters/julia-host-scanner