text:
@testset "Transition order tests" begin

mpSim = ManpowerSimulation( "sim" )

# Attributes
attribute = Attribute( "Subkader" )
setPossibleAttributeValues!( attribute, ["BDL", "Beroeps"] )
addSimulationAttribute!( mpSim, attribute )

attribute = Attribute( "Categorie" )
setPossibleAttributeValues!( attribute, ["Vrijw", "OOffr", "Offr"] )
addSimulationAttribute!( mpSim, attribute )

attribute = Attribute( "Niveau" )
setPossibleAttributeValues!( attribute, ["D", "C", "B", "A"] )
addSimulationAttribute!( mpSim, attribute )

attribute = Attribute( "Geslacht" )
setInitialAttributeValues!( attribute, ("M", 65.0), ("V", 35.0) )
addSimulationAttribute!( mpSim, attribute )

attribute = Attribute( "Taalgroep" )
setInitialAttributeValues!( attribute, ("NL", 62.0), ("FR", 38.0) )
addSimulationAttribute!( mpSim, attribute )

# Base nodes
node = BaseNode( "3D-D" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["BDL", "Vrijw", "D"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "3D-B" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["Beroeps", "Vrijw", "D"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "2C-D" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["BDL", "OOffr", "C"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "2C-B" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["Beroeps", "OOffr", "C"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "2B-D" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["BDL", "OOffr", "B"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "2B-B" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["Beroeps", "OOffr", "B"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "1B-D" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["BDL", "Offr", "B"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "1B-B" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["Beroeps", "Offr", "B"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "1A-D" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["BDL", "Offr", "A"] )
addSimulationBaseNode!( mpSim, node )

node = BaseNode( "1A-B" )
setNodeRequirements!( node, ["Subkader", "Categorie", "Niveau"],
    ["Beroeps", "Offr", "A"] )
addSimulationBaseNode!( mpSim, node )

# Compound nodes
node = CompoundNode( "BDL" )
setCompoundNodeComponents!( node, "3D-D", "2C-D", "2B-D", "1B-D", "1A-D" )
addSimulationCompoundNode!( mpSim, node )

node = CompoundNode( "Beroeps" )
setCompoundNodeComponents!( node, "3D-B", "2C-B", "2B-B", "1B-B", "1A-B" )
addSimulationCompoundNode!( mpSim, node )

node = CompoundNode( "Vrijw" )
setCompoundNodeComponents!( node, "3D-D", "3D-B" )
addSimulationCompoundNode!( mpSim, node )

node = CompoundNode( "OOffr" )
setCompoundNodeComponents!( node, "2C-D", "2C-B", "2B-D", "2B-B" )
addSimulationCompoundNode!( mpSim, node )

node = CompoundNode( "Offr" )
setCompoundNodeComponents!( node, "1B-D", "1B-B", "1A-D", "1A-B" )
addSimulationCompoundNode!( mpSim, node )

node = CompoundNode( "Niveau D" )
setCompoundNodeComponents!( node, "3D-D", "3D-B" )
addSimulationCompoundNode!( mpSim, node )

node = CompoundNode( "Niveau C" )
setCompoundNodeComponents!( node, "2C-D", "2C-B" )
addSimulationCompoundNode!( mpSim, node )

node = CompoundNode( "Niveau B" )
setCompoundNodeComponents!( node, "2B-D", "2B-B", "1B-D", "1B-B" )
addSimulationCompoundNode!( mpSim, node )

node = CompoundNode( "Niveau A" )
setCompoundNodeComponents!( node, "1A-D", "1A-B" )
addSimulationCompoundNode!( mpSim, node )

# Recruitment
recruitment = Recruitment( "EW" )
setRecruitmentSchedule!( recruitment, 12 )
setRecruitmentTarget!( recruitment, "3D-D" )
setRecruitmentAdaptiveRange!( recruitment, 408, 815 )
setRecruitmentAgeFixed!( recruitment, 18 * 12 )
addSimulationRecruitment!( mpSim, recruitment )

recruitment = Recruitment( "EW" )
setRecruitmentSchedule!( recruitment, 12 )
setRecruitmentTarget!( recruitment, "2C-D" )
setRecruitmentAdaptiveRange!( recruitment, 487, 974 )
setRecruitmentAgeFixed!( recruitment, 18 * 12 )
addSimulationRecruitment!( mpSim, recruitment )

recruitment = Recruitment( "EW" )
setRecruitmentSchedule!( recruitment, 12 )
setRecruitmentTarget!( recruitment, "2B-D" )
setRecruitmentAdaptiveRange!( recruitment, 31, 61 )
setRecruitmentAgeFixed!( recruitment, 18 * 12 )
addSimulationRecruitment!( mpSim, recruitment )

recruitment = Recruitment( "EW" )
setRecruitmentSchedule!( recruitment, 12 )
setRecruitmentTarget!( recruitment, "1B-D" )
setRecruitmentAdaptiveRange!( recruitment, 67, 134 )
setRecruitmentAgeFixed!( recruitment, 18 * 12 )
addSimulationRecruitment!( mpSim, recruitment )

recruitment = Recruitment( "EW" )
setRecruitmentSchedule!( recruitment, 12 )
setRecruitmentTarget!( recruitment, "1A-D" )
setRecruitmentAdaptiveRange!( recruitment, 136, 271 )
setRecruitmentAgeFixed!( recruitment, 18 * 12 )
addSimulationRecruitment!( mpSim, recruitment )

# Transitions
transition = Transition( "B+", "3D-D", "3D-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 12 * 12 ) )
setTransitionProbabilities!( transition, [0.22] )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B+", "2C-D", "2C-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 12 * 12 ) )
setTransitionProbabilities!( transition, [0.64] )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B+", "2B-D", "2B-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 12 * 12 ) )
setTransitionProbabilities!( transition, [0.67] )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B+", "1B-D", "1B-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 12 * 12 ) )
setTransitionProbabilities!( transition, [0.90] )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B+", "1A-D", "1A-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 16 * 12 ) )
setTransitionProbabilities!( transition, [0.62] )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B-", "3D-D" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 12 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B-", "2C-D" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 12 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B-", "2B-D" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 12 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B-", "1B-D" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 12 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "B-", "1A-D" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 16 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "DI", "3D-D", "2C-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 4 * 12 ) )
setTransitionFluxLimits!( transition, 0, 20 )
addSimulationTransition!( mpSim, transition )

transition = Transition( "DI", "2C-D", "2B-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "tenure", >=, 4 * 12 ) )
setTransitionFluxLimits!( transition, 0, 10 )
addSimulationTransition!( mpSim, transition )

transition = Transition( "DI", "2C-B", "2B-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "age", >=, 40 * 12 ) )
setTransitionFluxLimits!( transition, 0, 5 )
addSimulationTransition!( mpSim, transition )

transition = Transition( "OV", "1B-B", "1A-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "age", >=, 40 * 12 ) )
setTransitionFluxLimits!( transition, 0, 3 )
addSimulationTransition!( mpSim, transition )

transition = Transition( "SP", "3D-B", "2C-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "age", >=, 40 * 12 ) )
setTransitionFluxLimits!( transition, 0, 10 )
addSimulationTransition!( mpSim, transition )

transition = Transition( "SP", "2C-B", "1B-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "age", >=, 42 * 12 ) )
setTransitionFluxLimits!( transition, 0, 3 )
addSimulationTransition!( mpSim, transition )

transition = Transition( "SP", "2C-B", "1A-B" )
setTransitionSchedule!( transition, 12 )
addTransitionCondition!( transition, MPcondition( "age", >=, 42 * 12 ) )
setTransitionFluxLimits!( transition, 0, 1 )
addSimulationTransition!( mpSim, transition )

transition = Transition( "PE", "3D-B" )
setTransitionSchedule!( transition, 1 )
addTransitionCondition!( transition, MPcondition( "age", >=, 58 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "PE", "2C-B" )
setTransitionSchedule!( transition, 1 )
addTransitionCondition!( transition, MPcondition( "age", >=, 60 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "PE", "2B-B" )
setTransitionSchedule!( transition, 1 )
addTransitionCondition!( transition, MPcondition( "age", >=, 60 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "PE", "1B-B" )
setTransitionSchedule!( transition, 1 )
addTransitionCondition!( transition, MPcondition( "age", >=, 63 * 12 ) )
addSimulationTransition!( mpSim, transition )

transition = Transition( "PE", "1A-B" )
setTransitionSchedule!( transition, 1 )
addTransitionCondition!( transition, MPcondition( "age", >=, 63 * 12 ) )
addSimulationTransition!( mpSim, transition )

# Misc
setSimulationLength!( mpSim, 120.0 )

@testset "function addSimulationTransitionTypeOrder!" begin
    addSimulationTransitionTypeOrder!( mpSim, Dict( "DI" => 3, "B+" => 1 ) )
    @test ( length( mpSim.transitionTypeOrder ) == 2 ) &&
        all( haskey.( Ref( mpSim.transitionTypeOrder ), ["DI", "B+"] ) ) &&
        ( mpSim.transitionTypeOrder["DI"] == 3 ) &&
        ( mpSim.transitionTypeOrder["B+"] == 1 )
    addSimulationTransitionTypeOrder!( mpSim, ( "DI", 4 ), ( "B-", 5 ) )
    @test ( length( mpSim.transitionTypeOrder ) == 3 ) &&
        all( haskey.( Ref( mpSim.transitionTypeOrder ),
        ["DI", "B+", "B-"] ) ) &&
        ( mpSim.transitionTypeOrder["DI"] == 4 ) &&
        ( mpSim.transitionTypeOrder["B+"] == 1 ) &&
        ( mpSim.transitionTypeOrder["B-"] == 5 )
        addSimulationTransitionTypeOrder!( mpSim, "OV", 3 )
    @test ( length( mpSim.transitionTypeOrder ) == 4 ) &&
        all( haskey.( Ref( mpSim.transitionTypeOrder ),
        ["DI", "B+", "B-", "OV"] ) ) &&
        ( mpSim.transitionTypeOrder["OV"] == 3 )
    @test !addSimulationTransitionTypeOrder!( mpSim, Dict{String, Int}() )
    @test !addSimulationTransitionTypeOrder!( mpSim, ( "EW", 3 ), ( "EW", 2 ) )
end  # @testset "function addSimulationTransitionTypeOrder!"

@testset "function removeSimulationTransitionTypeOrder!" begin
    removeSimulationTransitionTypeOrder!( mpSim, "B+", "B-" )
    @test ( length( mpSim.transitionTypeOrder ) == 2 ) &&
        !any( haskey.( Ref( mpSim.transitionTypeOrder ), ["B+", "B-"] ) )
    @test !removeSimulationTransitionTypeOrder!( mpSim, "EW" )
end  # @testset "function removeSimulationTransitionTypeOrder!"

@testset "function clearSimulationTransitionTypeOrder!" begin
    @test clearSimulationTransitionTypeOrder!( mpSim )
    @test isempty( mpSim.transitionTypeOrder )
end  # @testset "function clearSimulationTransitionTypeOrder!"

@testset "function setSimulationTransitionTypeOrder!" begin
    setSimulationTransitionTypeOrder!( mpSim, Dict( "B+" => 4, "B-" => 8 ) )
    @test ( length( mpSim.transitionTypeOrder ) == 2 ) &&
        all( haskey.( Ref( mpSim.transitionTypeOrder ), ["B+", "B-"] ) ) &&
        ( mpSim.transitionTypeOrder["B-"] == 8 ) &&
        ( mpSim.transitionTypeOrder["B+"] == 4 )
    setSimulationTransitionTypeOrder!( mpSim, ( "OV", 3 ), ( "DI", 4 ) )
    @test ( length( mpSim.transitionTypeOrder ) == 2 ) &&
        all( haskey.( Ref( mpSim.transitionTypeOrder ), ["OV", "DI"] ) ) &&
        ( mpSim.transitionTypeOrder["OV"] == 3 ) &&
        ( mpSim.transitionTypeOrder["DI"] == 4 )
    setSimulationTransitionTypeOrder!( mpSim, ["PE", "EW"], [3, 2] )
    @test ( length( mpSim.transitionTypeOrder ) == 2 ) &&
        all( haskey.( Ref( mpSim.transitionTypeOrder ), ["PE", "EW"] ) ) &&
        ( mpSim.transitionTypeOrder["PE"] == 3 ) &&
        ( mpSim.transitionTypeOrder["EW"] == 2 )

    @test !setSimulationTransitionTypeOrder!( mpSim, ( "B+", 5 ), ( "B+", 2 ) )
    @test !setSimulationTransitionTypeOrder!( mpSim, ["B-"], [5, 2] )
    @test !setSimulationTransitionTypeOrder!( mpSim, ["B-", "B-"], [5, 2] )
end  # @testset "function setSimulationTransitionTypeOrder!"

setSimulationTransitionTypeOrder!( mpSim, Dict( "B+" => 1, "B-" => 4, "PE" => 4,
    "DI" => 3, "SP" => 3, "OV" => 3, "EW" => 2 ) )

@testset "function addSimulationBaseNodeOrder!" begin
    addSimulationBaseNodeOrder!( mpSim, Dict( "3D-D" => 3, "2C-D" => 1 ) )
    @test ( length( mpSim.baseNodeOrder ) == 2 ) &&
        all( haskey.( Ref( mpSim.baseNodeOrder ), ["3D-D", "2C-D"] ) ) &&
        ( mpSim.baseNodeOrder["3D-D"] == 3 ) &&
        ( mpSim.baseNodeOrder["2C-D"] == 1 )
        addSimulationBaseNodeOrder!( mpSim, ( "2B-B", 4 ), ( "2C-D", 5 ) )
    @test ( length( mpSim.baseNodeOrder ) == 3 ) &&
        all( haskey.( Ref( mpSim.baseNodeOrder ),
        ["3D-D", "2C-D", "2B-B"] ) ) &&
        ( mpSim.baseNodeOrder["3D-D"] == 3 ) &&
        ( mpSim.baseNodeOrder["2C-D"] == 5 ) &&
        ( mpSim.baseNodeOrder["2B-B"] == 4 )
        addSimulationBaseNodeOrder!( mpSim, "1A-B", 1 )
    @test ( length( mpSim.baseNodeOrder ) == 4 ) &&
        all( haskey.( Ref( mpSim.baseNodeOrder ),
        ["3D-D", "2C-D", "2B-B", "1A-B"] ) ) &&
        ( mpSim.baseNodeOrder["1A-B"] == 1 )
    @test !addSimulationBaseNodeOrder!( mpSim, Dict{String, Int}() )
    @test !addSimulationBaseNodeOrder!( mpSim, ( "1B-B", 3 ), ( "1B-B", 2 ) )
end  # @testset "function addSimulationBaseNodeOrder!"

@testset "function removeSimulationBaseNodeOrder!" begin
    removeSimulationBaseNodeOrder!( mpSim, "1A-B", "2C-D" )
    @test ( length( mpSim.baseNodeOrder ) == 2 ) &&
        !any( haskey.( Ref( mpSim.baseNodeOrder ), ["1A-B", "2C-D"] ) )
    @test !removeSimulationBaseNodeOrder!( mpSim, "2B-D" )
end  # @testset "function removeSimulationBaseNodeOrder!"

@testset "function clearSimulationBaseNodeOrder!" begin
    @test clearSimulationBaseNodeOrder!( mpSim )
    @test isempty( mpSim.baseNodeOrder )
end  # @testset "function clearSimulationBaseNodeOrder!"

@testset "function setSimulationBaseNodeOrder!" begin
    setSimulationBaseNodeOrder!( mpSim, Dict( "3D-B" => 4, "2B-D" => 8 ) )
    @test ( length( mpSim.baseNodeOrder ) == 2 ) &&
        all( haskey.( Ref( mpSim.baseNodeOrder ), ["3D-B", "2B-D"] ) ) &&
        ( mpSim.baseNodeOrder["2B-D"] == 8 ) &&
        ( mpSim.baseNodeOrder["3D-B"] == 4 )
    setSimulationBaseNodeOrder!( mpSim, ( "1A-D", 3 ), ( "2B-B", 4 ) )
    @test ( length( mpSim.baseNodeOrder ) == 2 ) &&
        all( haskey.( Ref( mpSim.baseNodeOrder ), ["1A-D", "2B-B"] ) ) &&
        ( mpSim.baseNodeOrder["1A-D"] == 3 ) &&
        ( mpSim.baseNodeOrder["2B-B"] == 4 )
    setSimulationBaseNodeOrder!( mpSim, ["2C-D", "2B-D"], [3, 2] )
    @test ( length( mpSim.baseNodeOrder ) == 2 ) &&
        all( haskey.( Ref( mpSim.baseNodeOrder ), ["2C-D", "2B-D"] ) ) &&
        ( mpSim.baseNodeOrder["2C-D"] == 3 ) &&
        ( mpSim.baseNodeOrder["2B-D"] == 2 )

    @test !setSimulationBaseNodeOrder!( mpSim, ( "3D-B", 5 ), ( "3D-B", 2 ) )
    @test !setSimulationBaseNodeOrder!( mpSim, ["3D-B"], [5, 2] )
    @test !setSimulationBaseNodeOrder!( mpSim, ["3D-B", "3D-B"], [5, 2] )
end  # @testset "function setSimulationBaseNodeOrder!"

@test verifySimulation!( mpSim )

end  # @testset "Transition order tests"


text:
# [SOREN] TRUST REGION MODIFICATION OF NEWTON'S METHOD
# [N&W] Numerical optimization
# [Yuan] A review of trust region algorithms for optimization
abstract type TRSPSolver end
abstract type NearlyExactTRSP <: TRSPSolver end

include("solvers/NWI.jl")
include("solvers/dogleg.jl")
include("solvers/CGT.jl")
#include("subproblemsolvers/TRS.jl") just make an example instead of relying onTRS.jl

ext: jl


text:
@testset "MOI Tests" begin
@testset "Supports and SolverName" begin
    optimizer = CS.Optimizer()
    @test MOI.get(optimizer, MOI.SolverName()) == "ConstraintSolver"
    @test MOI.supports_constraint(optimizer, MOI.VectorOfVariables, CS.AllDifferentSet)
    @test MOI.supports_constraint(optimizer, MOI.SingleVariable, MOI.ZeroOne)
    @test MOI.supports_constraint(optimizer, MOI.SingleVariable, MOI.Integer)
    @test MOI.supports_constraint(optimizer, MOI.SingleVariable, MOI.LessThan{Float64})
    @test MOI.supports_constraint(optimizer, MOI.SingleVariable, MOI.GreaterThan{Float64})
    @test MOI.supports_constraint(optimizer, MOI.SingleVariable, MOI.EqualTo{Float64})
    @test MOI.supports_constraint(optimizer, MOI.SingleVariable, MOI.Interval{Float64})

    @test MOI.supports_constraint(optimizer, MOI.ScalarAffineFunction{Float64}, MOI.EqualTo{Float64})
    @test MOI.supports_constraint(optimizer, MOI.ScalarAffineFunction{Float64}, MOI.LessThan{Float64})
    @test MOI.supports_constraint(optimizer, MOI.ScalarAffineFunction{Float64}, CS.NotEqualSet{Float64})

    # objective
    @test MOI.supports(optimizer, MOI.ObjectiveSense())
    @test MOI.supports(optimizer, MOI.ObjectiveFunction{MOI.SingleVariable}())

    @test MOI.get(optimizer, MOI.ObjectiveSense()) == MOI.FEASIBILITY_SENSE
end

@testset "Small MOI tests" begin
    optimizer = CS.Optimizer()
    @assert MOI.supports_constraint(optimizer, MOI.VectorOfVariables, CS.AllDifferentSet)

    x1 = MOI.add_constrained_variable(optimizer, MOI.ZeroOne())
    x2 = MOI.add_constrained_variable(optimizer, MOI.Interval(1.0, 2.0))
    x3 = MOI.add_constrained_variable(optimizer, MOI.Interval(2.0, 3.0))

    # [1] to get the index
    MOI.add_constraint(optimizer, x2[1], MOI.Integer())
    MOI.add_constraint(optimizer, x3[1], MOI.Integer())

    affine_terms = Vector{MOI.ScalarAffineTerm{Float64}}()
    push!(affine_terms,  MOI.ScalarAffineTerm{Float64}(1,MOI.VariableIndex(1)))
    push!(affine_terms,  MOI.ScalarAffineTerm{Float64}(1,MOI.VariableIndex(2)))
    MOI.add_constraint(optimizer, MOI.ScalarAffineFunction(affine_terms,0.0), MOI.EqualTo(3.0))
    MOI.add_constraint(optimizer, MOI.VectorOfVariables([x1[1], x2[1], x3[1]]), CS.AllDifferentSet(3))

    MOI.optimize!(optimizer)
    @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL
    @test MOI.get(optimizer, MOI.VariablePrimal(), x1[1]) == 1
    @test MOI.get(optimizer, MOI.VariablePrimal(), x2[1]) == 2
    @test MOI.get(optimizer, MOI.VariablePrimal(), x3[1]) == 3
end

@testset "ErrorHandling" begin
    optimizer = CS.Optimizer()
    @test_throws ErrorException MOI.add_constrained_variable(optimizer, MOI.Interval(NaN, 2.0))
    @test_throws ErrorException MOI.add_constrained_variable(optimizer, MOI.Interval(1.0, NaN))

    optimizer = CS.Optimizer()
    x = MOI.add_constrained_variable(optimizer, MOI.Interval(1.0, 2.0))
    @test_logs (:error, r"Upper bound .* exists") MOI.add_constraint(optimizer, MOI.SingleVariable(MOI.VariableIndex(1)), MOI.LessThan(2.0))
    @test_logs (:error, r"Lower bound .* exists") MOI.add_constraint(optimizer, MOI.SingleVariable(MOI.VariableIndex(1)), MOI.GreaterThan(1.0))

    optimizer = CS.Optimizer()
    x1 = MOI.add_constrained_variable(optimizer, MOI.Interval(1.0, 2.0))
    x2 = MOI.add_constrained_variable(optimizer, MOI.Interval(1.0, 2.0))
    # All should be integer
    @test_throws ErrorException MOI.optimize!(optimizer)

    # non existing option
    @test_logs (:warn, r"Option abc is not available") Model(with_optimizer(CS.Optimizer, abc=1))
end

end


text:
module TestSearching
using Test

using Catlab.Graphs.BasicGraphs, Catlab.Graphs.Searching
import Catlab.Graphs.Searching: tree

# Tests stolen from Graphs.jl

# BFS
#----

g = Graph(4)
add_edges!(g, [1,2,1,3], [2,3,3,4])
z = @inferred(bfs_tree(g, 1))
t = bfs_parents(g, 1)
@test t == [1,1,1,3]
@test nv(z) == 4 && ne(z) == 3 && !has_edge(z,2,3)

g = Graph(5) # house graph
add_edges!(g, [1,1,2,3,3,4], [2,3,4,4,5,5])
n = nv(g)
parents = bfs_parents(g, 1)
@test length(parents) == n
t1 = @inferred(bfs_tree(g, 1))
t2 = tree(parents)
@test t1 == t2
@test is_directed(t2)
@test typeof(t2) <: AbstractGraph
@test ne(t2) < nv(t2)

# DFS
#----

g = Graph(4)
add_edges!(g, [1,2,1,3], [2,3,3,4])
z = @inferred(dfs_tree(g, 1))
@test ne(z) == 3 && nv(z) == 4
@test !has_edge(z, 1, 3)
@test !is_cyclic(g)

end

max_forks_repo_name: epatters/CompCat


text:
using LightDarkLPDM
using Base.Test
using POMDPs
using POMDPToolbox
using StaticArrays
using Plots
using ParticleFilters

#Removed test code from here since it was for LightDarkPOMDPs.

max_stars_repo_name: ebalaban/LightDarkLPDM

max_issues_repo_name: tomerarnon/LightDarkLPDM

max_forks_repo_name: tomerarnon/LightDarkLPDM


text:
#-------------------------------------------------------------------
#* EMSO Model Library (EML) Copyright (C) 2004 - 2007 ALSOC.
#*
#* This LIBRARY is free software; you can distribute it and/or modify
#* it under the therms of the ALSOC FREE LICENSE as available at
#* http://www.enq.ufrgs.br/alsoc.
#*
#* EMSO Copyright (C) 2004 - 2007 ALSOC, original code
#* from http://www.rps.eng.br Copyright (C) 2002-2004.
#* All rights reserved.
#*
#* EMSO is distributed under the therms of the ALSOC LICENSE as
#* available at http://www.enq.ufrgs.br/alsoc.
#*--------------------------------------------------------------------
#* Author: Gerson Balbueno Bicca
#* $Id$
#*--------------------------------------------------------------------
type Baffles_Main
	Baffles_Main()=begin
		new(
			DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Baffle Cut",
				:Default=>25,
				:Lower=>25
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Number of Baffles",
				:Symbol=>"N_{baffles}",
				:Lower=>1
			)),
			length(Dict{Symbol,Any}(
				:Brief=>"Inlet Baffle Spacing",
				:Lower=>1e-8,
				:Symbol=>"L_{si}",
				:DisplayUnit=>"mm"
			)),
			length(Dict{Symbol,Any}(
				:Brief=>"Central Baffle Spacing",
				:Lower=>1e-8,
				:Symbol=>"L_s",
				:DisplayUnit=>"mm"
			)),
			length(Dict{Symbol,Any}(
				:Brief=>"Outlet Baffle Spacing",
				:Lower=>1e-8,
				:Symbol=>"L_{so}",
				:DisplayUnit=>"mm"
			)),
			[:BaffleCut,:NumberOfBaffles,],
			[:Inlet_Spacing,:Central_Spacing,:Outlet_Spacing,]
		)
	end
	BaffleCut::DanaInteger
	NumberOfBaffles::DanaReal
	Inlet_Spacing::length
	Central_Spacing::length
	Outlet_Spacing::length
	parameters::Array{Symbol,1}
	variables::Array{Symbol,1}
	attributes::Dict{Symbol,Any}
end
export Baffles_Main
function atributes(in::Baffles_Main,_::Dict{Symbol,Any})
	fields::Dict{Symbol,Any}=Dict{Symbol,Any}()
	fields[:Pallete]=false
	fields[:Brief]="Main variables in the Baffle section of a shell and tube heat exchanger."
	drive!(fields,_)
	return fields
end
Baffles_Main(_::Dict{Symbol,Any})=begin
	newModel=Baffles_Main()
	newModel.attributes=atributes(newModel,_)
	newModel
end


text:
register(DataDep(
    "pudl-raw-censusdp1tract",
    """
    Dataset: PUDL Raw Census DP1 Tract GeoDatabase
    Website: https://zenodo.org/record/4127049
    Author: Gosnell, Christina, Selvans, Zane
    Date of Publication: October 24, 2020
    License:

    Raw US Census Demographic Profile 1 (DP1) County and Tract GeoDatabase, archived from https://www2.census.gov/geo/tiger/TIGER2010DP1/Profile-County_Tract.zip

    $PUDL_DESCRIPTION
    """,
    [
        "https://zenodo.org/api/files/b1191224-6364-49e8-a4bc-f9956c365209/censusdp1tract-2010.zip",
        "https://zenodo.org/api/files/b1191224-6364-49e8-a4bc-f9956c365209/datapackage.json",
    ],
    "aacac46b6ac23928bafec00cade97031da662ccb6b24f5f42fb84fc327246654",
))


text:
using LogDensity
using Documenter

makedocs(;
    modules=[LogDensity],
    authors="Joris Pinkse <joris@psu.edu> and Karl Schurter",
    sitename="LogDensity.jl",
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    repo = "github.com/NittanyLion/LogDensity.jl",
    target = "build"
)


text:
# Unlike other LP implementations, this one is not totally unimodular, and
# thus requires an ILP solver.
mutable struct SpanningTreeLPSolver <: SpanningTreeSolver
  graph::SimpleDiGraph
  weights_matrix::Matrix{Float64}

  solver

  # Optimisation model (reused by solve_linear).
  model # ::Model
  x # ::Vector{Variable}: index is edge
  flow # ::Vector{Variable}: index is edge

  function SpanningTreeLPSolver(solver)
    return new(DiGraph(0), zeros(0, 0), solver, nothing, nothing)
  end
end

has_lp_formulation(::SpanningTreeLPSolver) = true
approximation_ratio(::SpanningTreeLPSolver) = 1.0
approximation_term(::SpanningTreeLPSolver) = 0.0
approximation_ratio_budgeted(::SpanningTreeLPSolver) = 1.0
approximation_term_budgeted(::SpanningTreeLPSolver) = 0.0
supports_solve_budgeted_linear(::SpanningTreeLPSolver) = true
supports_solve_all_budgeted_linear(::SpanningTreeLPSolver) = false

Base.copy(solver::SpanningTreeLPSolver) = SpanningTreeLPSolver(solver.solver)

function build!(solver::SpanningTreeLPSolver, graph::SimpleGraph)
  # Input graph supposed to be undirected.
  n = nv(graph)
  solver.graph = DiGraph(n)
  solver.weights_matrix = zeros(n, n)

  # Build the equivalent directed graph.
  for e in edges(graph)
    add_edge!(solver.graph, src(e), dst(e))
    add_edge!(solver.graph, dst(e), src(e))
  end

  # Helper methods.
  inedges(g, v) = (edgetype(g)(x, v) for x in inneighbors(g, v))
  outedges(g, v) = (edgetype(g)(v, x) for x in outneighbors(g, v))

  # Build the optimisation model behind solve_linear.
  # Based on Magnanti, T.L.; Wolsey, L. Optimal Trees, section Flow formulation (p. 38).
  solver.model = Model(solver.solver)
  solver.x = @variable(solver.model, [e in edges(solver.graph)], binary=true)
  solver.flow = @variable(solver.model, [e in edges(solver.graph)], lower_bound=0)

  for e in edges(solver.graph)
    set_name(solver.x[e], "x_$(src(e))_$(dst(e))")
    set_name(solver.flow[e], "flow_$(src(e))_$(dst(e))")
  end

  # Choose a source arbitrarily.
  source = first(vertices(solver.graph))
  other_nodes = filter(v -> v != source, vertices(solver.graph))

  @constraint(solver.model, sum(solver.flow[e] for e in inedges(solver.graph, source)) == 0)
  @constraint(solver.model, sum(solver.flow[e] for e in outedges(solver.graph, source)) == n - 1)
  for v in other_nodes
    @constraint(solver.model, sum(solver.flow[e] for e in inedges(solver.graph, v)) - sum(solver.flow[e] for e in outedges(solver.graph, v)) == 1)
  end

  @constraint(solver.model, sum(solver.x) == n - 1)
  for e in edges(solver.graph)
    @constraint(solver.model, solver.flow[e] <= (n - 1) * solver.x[e])
  end

  for e in edges(graph)
    @constraint(solver.model, solver.x[e] + solver.x[reverse(e)] <= 1)
  end
end

function get_lp_formulation(solver::SpanningTreeLPSolver, reward::Dict{Tuple{Int, Int}, Float64})
  obj = sum(reward[i, j] * (solver.x[Edge(i, j)] + solver.x[Edge(j, i)]) for (i, j) in keys(reward))
  vars_forw = Dict{Tuple{Int, Int}, JuMP.VariableRef}((i, j) => solver.x[Edge(i, j)] for (i, j) in keys(reward))
  vars_back = Dict{Tuple{Int, Int}, JuMP.VariableRef}((j, i) => solver.x[Edge(j, i)] for (i, j) in keys(reward))
  vars = merge(vars_forw, vars_back)

  return solver.model, obj, vars
end

# TODO: allow _lp_generic.jl's functions to be overridden in part (here, just to retrieve the solution).

function solve_linear(solver::SpanningTreeLPSolver, reward::Dict{Tuple{Int, Int}, Float64})
  # Generic implementation that should work for all solvers following the same conventions:
  #  - `has_lp_formulation` returns `true` for the solver
  #  - `supports_solve_budgeted_linear` returns `true` for the solver
  #  - `get_lp_formulation` returns a LP-like formulation (may even be a MIP)
  # Lazy formulations are allowed.
  @assert has_lp_formulation(solver)
  @assert supports_solve_budgeted_linear(solver)

  key = Symbol(string(typeof(solver)))

  m, obj, vars = get_lp_formulation(solver, reward)
  @objective(m, Max, obj)

  # Maybe solve_budgeted_linear has already been called on this model.
  if key in keys(m.ext)
    budget_constraint = m.ext[key][:budget_constraint]
    set_normalized_rhs(budget_constraint, 0)
  end

  set_silent(m)
  optimize!(m)

  if termination_status(m) != MOI.OPTIMAL
    return Tuple{Int, Int}[]
  end

  return Tuple{Int, Int}[(i, j) for (i, j) in keys(reward) if value(vars[i, j]) > 0.5 || value(vars[j, i]) > 0.5]
end

function solve_budgeted_linear(solver::SpanningTreeLPSolver,
                               reward::Dict{Tuple{Int, Int}, Float64},
                               weight::Dict{Tuple{Int, Int}, T},
                               budget::Int) where {T<:Number} # Handle both Int and Float64
  # Generic implementation that should work for all solvers following the same conventions:
  #  - `has_lp_formulation` returns `true` for the solver
  #  - `supports_solve_budgeted_linear` returns `true` for the solver
  #  - `get_lp_formulation` returns a LP-like formulation (may even be a MIP)
  #    whose variables are alse used for the budget constraint
  # Lazy formulations are allowed.
  @assert has_lp_formulation(solver)
  @assert supports_solve_budgeted_linear(solver)

  key = Symbol(string(typeof(solver)))

  m, obj, vars = get_lp_formulation(solver, reward)
  @objective(m, Max, obj)

  # Add the budget constraint (or change the existing constraint).
  if key in keys(m.ext)
    budget_constraint = m.ext[key][:budget_constraint]
    set_normalized_rhs(budget_constraint, budget)
  else
    budget_constraint = @constraint(m, sum(weight[i] * vars[i] for i in keys(reward)) >= budget)
    m.ext[key] = Dict(:budget_constraint => budget_constraint)
  end

  set_silent(m)
  optimize!(m)

  if termination_status(m) != MOI.OPTIMAL
    return Tuple{Int, Int}[]
  end
  return Tuple{Int, Int}[(i, j) for (i, j) in keys(reward) if value(vars[i, j]) > 0.5 || value(vars[j, i]) > 0.5]
end


text:
# generate ramps for hasak
# ramps are 257 point arrays which are interpolated
cosine_series1(size, k, a0,  a1) =
    a0 - a1 * cos((2π * k) / (size-1))
cosine_series2( size, k, a0, a1, a2) =
    cosine_series1(size, k, a0, a1) + a2 * cos((2 * 2π * k) / (size-1))
cosine_series3(size, k, a0, a1, a2, a3) =
    cosine_series2(size, k, a0, a1, a2) - a3 * cos((3 * 2π * k) / (size-1))
# hann ramp element
hann(k, size) =
    Integer(round(32767 * cosine_series1(size, k, 0.50, 0.50)))
# blackman harris ramp element
blackman_harris(k, size) =
    Integer(round(32767 * cosine_series3(size, k, 0.3587500, 0.4882900, 0.1412800, 0.0116800)))
# linear ramp element
triangular(k, size) =
    Integer(round(32767 * (1.0 - abs( (k - ((size-1)/2.0)) / ((size-1)/2.0) ))))
# sine table element
sine(k, size) =
    Integer(round(32767 * sin(2π * k / size)))

# format tables
using Printf
format_table(t) = join([@sprintf("%s%6d", i>1 && (i%8)==1 ? "\n" : "", t[i]) for i in 1:length(t)], ",")
@printf("const int16_t hann_ramp[257] = {\n%s\n};\n", format_table([hann(k,512) for k in 0:256]))
@printf("const int16_t blackman_harris_ramp[257] = {\n%s\n};\n", format_table([blackman_harris(k,512) for k in 0:256]))
@printf("const int16_t linear_ramp[257] = {\n%s\n};\n", format_table([triangular(k,512) for k in 0:256]))
@printf("const int16_t sine_table[257] = {\n%s\n};\n", format_table([sine(k,256) for k in 0:256]))

max_stars_repo_name: recri/hasak

max_issues_repo_name: recri/hasak

max_forks_repo_name: recri/hasak


text:
export statcast_search

# all=true
# hfPT=
# hfAB=
# hfBBT=
# hfPR=
# hfZ=
# stadium=
# hfBBL=
# hfNewZones=
# hfGT=R|
# hfC=
# hfSea=
# hfSit=
# player_type=pitcher
# hfOuts=
# opponent=
# pitcher_throws=
# batter_stands=
# hfSA=
# game_date_gt=
# game_date_lt=
# hfInfield=
# team=
# position=
# hfOutfield=
# hfRO=
# home_road=
# hfFlag=
# hfPull=
# metric_1=
# hfInn=
# min_pitches=0
# min_results=0
# group_by=name
# sort_col=pitches
# player_event_sort=h_launch_speed
# sort_order=desc
# min_pas=0
# type=details

const q_base = HTTP.URIs.queryparams("all=true&hfPT=&hfAB=&hfBBT=&hfPR=&hfZ=&stadium=&hfBBL=&hfNewZones=&hfGT=R%7C&hfC=&hfSea=&hfSit=&player_type=&hfOuts=&opponent=&pitcher_throws=&batter_stands=&hfSA=&game_date_gt=&game_date_lt=&hfInfield=&team=&position=&hfOutfield=&hfRO=&home_road=&hfFlag=&hfPull=&metric_1=&hfInn=&min_pitches=0&min_results=0&group_by=&sort_col=&player_event_sort=&sort_order=desc&min_pas=0&type=details&")

function fetch_statcast_search(query::AbstractDict)
    query_req = merge(q_base, query)
    req = HTTP.get("https://baseballsavant.mlb.com/statcast_search/csv", query = query_req, status_exception = true, verbose = 0)
    IOBuffer(req.body)
end

statcast_search(pairs::Pair...) = statcast_search(Dict(pairs...))

function statcast_search(query::AbstractDict)
    io = fetch_statcast_search(query)

    data = CSV.read(
        io,
        missingstrings = ["", "null"],
        types = savant_types,
        silencewarnings = false
    )

    if :error ∈ names(data)
        error(data[1, :error])
    end

    # Delete deprecated columns? Are they always empty?
    # deletecols!(data, [:spin_dir, :spin_rate_deprecated, :break_angle_deprecated, :break_length_deprecated, :tfs_deprecated, :tfs_zulu_deprecated])

    # Baseball Savant's Statcast Search seems to truncate at 40000 rows. Better warn the user.
    if size(data, 1) === 40000
        @warn "Baseball Savant Statcast Search returned 40000 rows. Data might be truncated, check extents."
    end

    data
end

savant_types = Dict(
    :pitch_type => Union{String, Missing},
    :game_date => Date,
    :release_speed => Union{Float64, Missing},
    :release_pos_x => Union{Float64, Missing},
    :release_pos_y => Union{Float64, Missing},
    :release_pos_z => Union{Float64, Missing},
    :player_name => Union{String, Missing},
    :batter => Int64,
    :pitcher => Int64,
    :events => Union{String, Missing},
    :description => Union{String, Missing},
    :spin_dir => Union{Float64, Missing},
    :spin_rate_deprecated => Union{Float64, Missing},
    :break_angle_deprecated => Union{Float64, Missing},
    :break_length_deprecated => Union{Float64, Missing},
    :zone => Union{Int64, Missing},
    :des => Union{String, Missing},
    :game_type => Union{String, Missing},
    :stand => String,
    :p_throws => String,
    :home_team => String,
    :away_team => String,
    :type => String,
    :hit_location => Union{Int64, Missing},
    :bb_type => Union{String, Missing},
    :balls => Int64,
    :strikes => Int64,
    :game_year => Int64,
    :pfx_x => Union{Float64, Missing},
    :pfx_z => Union{Float64, Missing},
    :plate_x => Union{Float64, Missing},
    :plate_z => Union{Float64, Missing},
    :on_3b => Union{Int64, Missing},
    :on_2b => Union{Int64, Missing},
    :on_1b => Union{Int64, Missing},
    :outs_when_up => Int64,
    :inning => Union{Int64, Missing},
    :inning_topbot => Union{String, Missing},
    :hc_x => Union{Float64, Missing},
    :hc_y => Union{Float64, Missing},
    :tfs_deprecated => Union{String, Missing},
    :tfs_zulu_deprecated => Union{String, Missing},
    :fielder_2 => Union{Int64, Missing},
    :umpire => Union{Int64, Missing},
    :sv_id => Union{String, Missing},
    :vx0 => Union{Float64, Missing},
    :vy0 => Union{Float64, Missing},
    :vz0 => Union{Float64, Missing},
    :ax => Union{Float64, Missing},
    :ay => Union{Float64, Missing},
    :az => Union{Float64, Missing},
    :sz_top => Union{Float64, Missing},
    :sz_bot => Union{Float64, Missing},
    :hit_distance_sc => Union{Float64, Missing},
    :launch_speed => Union{Float64, Missing},
    :launch_angle => Union{Float64, Missing},
    :effective_speed => Union{Float64, Missing},
    :release_spin_rate => Union{Float64, Missing},
    :release_extension => Union{Float64, Missing},
    :game_pk => Int64,
    :pitcher_1 => Int64,
    :fielder_2_1 => Union{Int64, Missing},
    :fielder_3 => Union{Int64, Missing},
    :fielder_4 => Union{Int64, Missing},
    :fielder_5 => Union{Int64, Missing},
    :fielder_6 => Union{Int64, Missing},
    :fielder_7 => Union{Int64, Missing},
    :fielder_8 => Union{Int64, Missing},
    :fielder_9 => Union{Int64, Missing},
    :estimated_ba_using_speedangle => Union{Float64, Missing},
    :estimated_woba_using_speedangle => Union{Float64, Missing},
    :woba_value => Union{Float64, Missing},
    :woba_denom => Union{Float64, Missing},
    :babip_value => Union{Float64, Missing},
    :iso_value => Union{Float64, Missing},
    :launch_speed_angle => Union{Float64, Missing},
    :at_bat_number => Int64,
    :pitch_number => Int64,
    :pitch_name => Union{String, Missing},
    :home_score => Int64,
    :away_score => Int64,
    :bat_score => Int64,
    :fld_score => Int64,
    :post_away_score => Int64,
    :post_home_score => Int64,
    :post_bat_score => Int64,
    :post_fld_score => Int64,
    :if_fielding_alignment => Union{String, Missing},
    :of_fielding_alignment => Union{String, Missing}
)


text:
module Joy

include("base.jl")
include("string_utils.jl")
include("utils.jl")
include("words.jl")
include("syntax.jl")

include("modes/movements.jl")
include("modes/normal.jl")
include("modes/insert.jl")
include("modes/calls.jl")
include("modes/command.jl")
include("modes/search.jl")

include("config.jl")
include("spelling.jl")
isfile("$(homedir())/.joyrc.jl") && include("$(homedir())/.joyrc.jl")

include("editor.jl")

end


text:
"""
	histogram(cmd0::String="", arg1=nothing; kwargs...)

Reads file and examines the first data column to calculate histogram parameters based on the bin-width provided.

Full option list at [`pshistogram`]($(GMTdoc)histogram.html)

Parameters
----------

- $(GMT.opt_J)
- **W** | **bin** | **width** :: [Type => Number | Str]

    Sets the bin width used for histogram calculations.
    ($(GMTdoc)histogram.html#w)
- **A** | **horizontal** :: [Type => Bool]

    Plot the histogram horizontally from x = 0 [Default is vertically from y = 0].
    ($(GMTdoc)histogram.html#a)
- $(GMT.opt_B)
- **C** | **color** :: [Type => Str | GMTcpt]

    Give a CPT. The mid x-value for each bar is used to look-up the bar color.
    ($(GMTdoc)histogram.html#c)
- **D** | **annot** | **annotate** :: [Type => Str | []]

    Annotate each bar with the count it represents.
    ($(GMTdoc)histogram.html#d)
- **F** | **center** :: [Type => Bool or []]

    Center bin on each value. [Default is left edge].
    ($(GMTdoc)histogram.html#f)
- **G** | **fill** :: [Type => Number | Str]

    Select filling of bars [if no G, L or C set G=100].
    ($(GMTdoc)histogram.html#g)
- **I** | **inquire** :: [Type => Bool]

    Inquire about min/max x and y after binning.
    ($(GMTdoc)histogram.html#i)
- **L** | **labels** :: [Type => Str | []]

    Draw bar outline using the specified pen thickness [if no G, L or C set L=0.5].
    ($(GMTdoc)histogram.html#l)
- **N** | **normal** :: [Type => Str]

    Draw the equivalent normal distribution; append desired pen [0.5p,black].
    ($(GMTdoc)histogram.html#n)
- $(GMT.opt_P)
- **Q** | **alpha** :: [Type => Number | []]

    Sets the confidence level used to determine if the mean resultant is significant.
    ($(GMTdoc)histogram.html#q)
- **R** | **region** :: [Type => Str]

    Specifies the ‘region’ of interest in (r,azimuth) space. r0 is 0, r1 is max length in units.
    ($(GMTdoc)histogram.html#r)
- **S** | **stairs** :: [Type => Str | number]

    Draws a stairs-step diagram which does not include the internal bars of the default histogram.
    ($(GMTdoc)histogram.html#s)
- **Z** | **kind** :: [Type => Number | Str]

    Choose between 6 types of histograms.
    ($(GMTdoc)histogram.html#z)
- $(GMT.opt_U)
- $(GMT.opt_V)
- $(GMT.opt_X)
- $(GMT.opt_Y)
- $(GMT.opt_bi)
- $(GMT.opt_di)
- $(GMT.opt_e)
- $(GMT.opt_h)
- $(GMT.opt_i)
- $(GMT.opt_p)
- $(GMT.opt_t)
- $(GMT.opt_swap_xy)
"""
function histogram(cmd0::String="", arg1=nothing; first=true, kwargs...)

	arg2 = nothing		# May be needed if GMTcpt type is sent in via C
	N_args = isempty_(arg1) ? 0 : 1

	length(kwargs) == 0 && return monolitic("pshistogram", cmd0, arg1, arg2)

	d = KW(kwargs)

	# If inquire, no plotting so do it and return
	cmd = add_opt("", 'I', d, [:I :inquire])
	if (cmd != "")
		cmd = add_opt(cmd, 'W', d, [:W :bin :width])
		(haskey(d, :Vd)) && println(@sprintf("\tpshistogram %s", cmd))
		return gmt("pshistogram " * cmd, arg1)
	end

    K, O = set_KO(first)		# Set the K O dance

	cmd, opt_B, opt_J, opt_R = parse_BJR(d, "", "histogram", O, " -JX12c/12c")
	cmd = parse_common_opts(d, cmd, [:UVXY :JZ :c :e :p :t :yx :params], first)
	cmd = parse_these_opts(cmd, d, [[:A :horizontal], [:D :annot :annotate], [:F :center],
				[:Q :cumulative], [:S :stairs]])
	cmd = add_opt_fill(cmd, d, [:G :fill], 'G')
	cmd = add_opt(cmd, 'Z', d, [:Z :kind],
		(counts="0", freq="1", log_count="2", log_freq="3", log10_count="4", log10_freq="5", weights="+w"))

	# If file name sent in, read it and compute a tight -R if this was not provided
	if (opt_R == "")  opt_R = " "  end		# So it doesn't try to find the -R in next call
	cmd, arg1, opt_R, = read_data(d, cmd0, cmd, arg1, opt_R)
	cmd, arg1, arg2, = add_opt_cpt(d, cmd, [:C :color :cmap], 'C', N_args, arg1, arg2)

	if (GMTver >= 6)
		cmd   = add_opt(cmd, 'T', d, [:T :bin :width])
		cmd   = add_opt(cmd, 'L', d, [:L :out_range])
		cmd  *= add_opt_pen(d, [:W :pen], "W")
		if (!occursin("-G", cmd) && !occursin("-C", cmd) && !occursin("-I", cmd))
			cmd *= " -L0.5p -G150"		# If no -L, -G, -I or -C set these defaults
		end
	else
		cmd = add_opt(cmd, 'W', d, [:W :bin :width]) * add_opt_pen(d, [:L :pen], "L")
		if (!occursin("-G", cmd) && !occursin("-C", cmd) && !occursin("-L", cmd) && !occursin("-I", cmd))
			cmd *= " -L0.5p -G150"		# If no -L, -G, -I or -C set these defaults
		end
	end

	if ((val = find_in_dict(d, [:N :normal])[1]) !== nothing)
		if (isa(val, Number) || isa(val, String))  cmd  = string(cmd, " -N", val)
		elseif (isa(val, Tuple))                   cmd *= " -N" * parse_arg_and_pen(val)
		end
	end

	return finish_PS_module(d, "pshistogram " * cmd, "", K, O, true, arg1, arg2)
end

# ---------------------------------------------------------------------------------------------------
histogram!(cmd0::String="", arg1=nothing; first=false, kw...) = histogram(cmd0, arg1; first=first, kw...)

histogram(arg1; first=true, kw...) = histogram("", arg1; first=first, kw...)
histogram!(arg1; first=false, kw...) = histogram("", arg1; first=first, kw...)

const pshistogram  = histogram			# Alias
const pshistogram! = histogram!			# Alias


text:
export Member

"""
A [`Guild`](@ref) member.
More details [here](https://discordapp.com/developers/docs/resources/guild#guild-member-object).
"""
mutable struct Member <: DiscordObject
    user::Optional{User}
    nick::OptionalNullable{String}  # Not supposed to be nullable.
    roles::Vector{Snowflake}
    joined_at::DateTime
    premium_since::OptionalNullable{DateTime}
    deaf::Optional{Bool}
    mute::Optional{Bool}
end
@boilerplate Member :constructors :docs :lower :merge :mock


text:
using Base.Test
using Records

include("test_listrecords.jl")
include("test_queuerecords.jl")
include("test_conversions.jl")


text:
using ForwardDiff

function check_derivatives(g, gx, gy)
    p = rand(2)
    display(ForwardDiff.jacobian(g, p))
    display([gx(p) gy(p)])
    return ForwardDiff.jacobian(g, p) ≈ [gx(p) gy(p)]
end

function check_second_derivatives(f, fx, fy, fxx, fxy, fyy)
    p = rand(2)
    display([fxx(p) fxy(p) fyy(p)])
    display(ForwardDiff.jacobian(fx, p))
    display(ForwardDiff.jacobian(fy, p))
end


text:
using FiniteDifferences
using LinearAlgebra: I
using StatsBase: AbstractWeights, pweights
using ManifoldsBase: TraitList
import ManifoldsBase: default_retraction_method
import Manifolds: solve_exp_ode
using Manifolds:
    FiniteDifferencesBackend,
    InducedBasis,
    connection,
    get_chart_index,
    induced_basis,
    mean!,
    median!
include("utils.jl")

struct TestEuclidean{N} <: AbstractManifold{ℝ} end
struct TestEuclideanMetric <: AbstractMetric end
struct TestScaledEuclideanMetric <: AbstractMetric end
struct TestRetraction <: AbstractRetractionMethod end
struct TestConnection <: AbstractAffineConnection end

ManifoldsBase.default_retraction_method(::TestEuclidean) = TestRetraction()
function ManifoldsBase.default_retraction_method(
    ::MetricManifold{ℝ,<:TestEuclidean,<:TestEuclideanMetric},
)
    return TestRetraction()
end

Manifolds.manifold_dimension(::TestEuclidean{N}) where {N} = N
function Manifolds.local_metric(
    ::TraitList{<:IsMetricManifold},
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestEuclideanMetric},
    ::Any,
    ::InducedBasis,
)
    return Diagonal(1.0:manifold_dimension(M))
end
function Manifolds.local_metric(
    ::TraitList{IsMetricManifold},
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestEuclideanMetric},
    ::Any,
    ::T,
) where {T<:ManifoldsBase.AbstractOrthogonalBasis}
    return Diagonal(1.0:manifold_dimension(M))
end
function Manifolds.local_metric(
    ::TraitList{IsMetricManifold},
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestScaledEuclideanMetric},
    ::Any,
    ::T,
) where {T<:ManifoldsBase.AbstractOrthogonalBasis}
    return 2 .* Diagonal(1.0:manifold_dimension(M))
end
function Manifolds.get_coordinates_orthogonal(
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestEuclideanMetric},
    ::Any,
    X,
    ::ManifoldsBase.AbstractNumbers,
)
    return 1 ./ [1.0:manifold_dimension(M)...] .* X
end
function Manifolds.get_coordinates_orthogonal!(
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestEuclideanMetric},
    c,
    ::Any,
    X,
    ::ManifoldsBase.AbstractNumbers,
)
    c .= 1 ./ [1.0:manifold_dimension(M)...] .* X
    return c
end
function Manifolds.get_vector_orthonormal!(
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestEuclideanMetric},
    X,
    ::Any,
    c,
    ::ManifoldsBase.AbstractNumbers,
)
    X .= [1.0:manifold_dimension(M)...] .* c
    return X
end
function Manifolds.get_coordinates_orthogonal!(
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestScaledEuclideanMetric},
    c,
    ::Any,
    X,
)
    c .= 1 ./ (2 .* [1.0:manifold_dimension(M)...]) .* X
    return c
end
function Manifolds.get_vector_orthogonal!(
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestScaledEuclideanMetric},
    ::Any,
    c,
    ::ManifoldsBase.AbstractNumbers,
)
    return 2 .* [1.0:manifold_dimension(M)...] .* c
end
function Manifolds.get_vector_orthogonal!(
    M::MetricManifold{ℝ,<:TestEuclidean,<:TestScaledEuclideanMetric},
    X,
    ::Any,
    c,
    ::ManifoldsBase.AbstractNumbers,
)
    X .= 2 .* [1.0:manifold_dimension(M)...] .* c
    return X
end
struct TestSphere{N,T} <: AbstractManifold{ℝ}
    r::T
end

struct TestSphericalMetric <: AbstractMetric end

Manifolds.manifold_dimension(::TestSphere{N}) where {N} = N
function Manifolds.local_metric(
    M::MetricManifold{ℝ,<:TestSphere,<:TestSphericalMetric},
    p,
    ::InducedBasis,
)
    r = base_manifold(M).r
    d = allocate(p)
    d[1] = r^2
    d[2] = d[1] * sin(p[1])^2
    return Diagonal(d)
end
sph_to_cart(θ, ϕ) = [cos(ϕ) * sin(θ), sin(ϕ) * sin(θ), cos(θ)]

struct BaseManifold{N} <: AbstractManifold{ℝ} end
struct BaseManifoldMetric{M} <: AbstractMetric end
struct DefaultBaseManifoldMetric <: AbstractMetric end
struct NotImplementedMetric <: AbstractMetric end

Manifolds.manifold_dimension(::BaseManifold{N}) where {N} = N
Manifolds.inner(::BaseManifold, p, X, Y) = 2 * dot(X, Y)
Manifolds.exp!(::BaseManifold, q, p, X) = q .= p + 2 * X
Manifolds.log!(::BaseManifold, Y, p, q) = Y .= (q - p) / 2
Manifolds.project!(::BaseManifold, Y, p, X) = Y .= 2 .* X
Manifolds.project!(::BaseManifold, q, p) = (q .= p)
Manifolds.injectivity_radius(::BaseManifold) = Inf
Manifolds.injectivity_radius(::BaseManifold, ::Any) = Inf
Manifolds.injectivity_radius(::BaseManifold, ::AbstractRetractionMethod) = Inf
Manifolds._injectivity_radius(::BaseManifold, ::ExponentialRetraction) = Inf
Manifolds.injectivity_radius(::BaseManifold, ::Any, ::AbstractRetractionMethod) = Inf
Manifolds._injectivity_radius(::BaseManifold, ::Any, ::ExponentialRetraction) = Inf
function Manifolds.local_metric(
    ::TraitList{<:IsMetricManifold},
    ::MetricManifold{ℝ,BaseManifold{N},BaseManifoldMetric{N}},
    p,
    ::InducedBasis,
) where {N}
    return 2 * one(p * p')
end
function Manifolds.exp!(
    M::MetricManifold{ℝ,BaseManifold{N},BaseManifoldMetric{N}},
    q,
    p,
    X,
) where {N}
    return exp!(base_manifold(M), q, p, X)
end
function Manifolds.parallel_transport_to!(::BaseManifold, Y, p, X, q)
    return (Y .= X)
end
function Manifolds.get_basis(
    ::BaseManifold{N},
    p,
    B::DefaultOrthonormalBasis{<:Any,ManifoldsBase.TangentSpaceType},
) where {N}
    return CachedBasis(B, [(Matrix{eltype(p)}(I, N, N)[:, i]) for i in 1:N])
end
function Manifolds.get_coordinates_orthonormal!(
    ::BaseManifold,
    Y,
    p,
    X,
    ::ManifoldsBase.AbstractNumbers,
)
    return Y .= X
end
function Manifolds.get_vector_orthonormal!(
    ::BaseManifold,
    Y,
    p,
    X,
    ::ManifoldsBase.AbstractNumbers,
)
    return Y .= X
end
Manifolds.is_default_metric(::BaseManifold, ::DefaultBaseManifoldMetric) = true
function Manifolds.projected_distribution(M::BaseManifold, d)
    return ProjectedPointDistribution(M, d, project!, rand(d))
end
function Manifolds.projected_distribution(M::BaseManifold, d, p)
    return ProjectedPointDistribution(M, d, project!, p)
end

function Manifolds.flat!(
    ::BaseManifold,
    v::FVector{Manifolds.CotangentSpaceType},
    x,
    w::FVector{Manifolds.TangentSpaceType},
)
    v.data .= 2 .* w.data
    return v
end
function Manifolds.sharp!(
    ::BaseManifold,
    v::FVector{Manifolds.TangentSpaceType},
    x,
    w::FVector{Manifolds.CotangentSpaceType},
)
    v.data .= w.data ./ 2
    return v
end
function solve_exp_ode(
    ::ConnectionManifold{ℝ,TestEuclidean{N},TestConnection},
    p,
    X;
    kwargs...,
) where {N}
    return X
end
function Manifolds.vector_transport_along!(
    M::BaseManifold,
    Y,
    p,
    X,
    c::AbstractVector,
    m::AbstractVectorTransportMethod=default_vector_transport_method(M),
)
    Y .= c
    return Y
end
@testset "Metrics" begin
    # some tests failed due to insufficient accuracy for a particularly bad RNG state
    Random.seed!(42)
    @testset "Metric Basics" begin
        @test repr(MetricManifold(Euclidean(3), EuclideanMetric())) ===
              "MetricManifold(Euclidean(3; field = ℝ), EuclideanMetric())"
        @test repr(IsDefaultMetric(EuclideanMetric())) ===
              "IsDefaultMetric(EuclideanMetric())"
    end
    @testset "Connection Trait" begin
        M = ConnectionManifold(Euclidean(3), LeviCivitaConnection())
        @test is_default_connection(M)
        @test decorated_manifold(M) == Euclidean(3)
        @test is_default_connection(Euclidean(3), LeviCivitaConnection())
        @test !is_default_connection(TestEuclidean{3}(), LeviCivitaConnection())
        c = IsDefaultConnection(LeviCivitaConnection())
        @test ManifoldsBase.parent_trait(c) == Manifolds.IsConnectionManifold()
    end

    @testset "solve_exp_ode error message" begin
        E = TestEuclidean{3}()
        g = TestEuclideanMetric()
        M = MetricManifold(E, g)
        default_retraction_method(::TestEuclidean) = TestRetraction()
        p = [1.0, 2.0, 3.0]
        X = [2.0, 3.0, 4.0]
        q = similar(X)
        @test_throws ErrorException exp(M, p, X)
        @test_throws ErrorException exp!(M, q, p, X)

        N = ConnectionManifold(E, LeviCivitaConnection())
        @test_throws ErrorException exp(N, p, X)
        @test_throws ErrorException exp!(N, q, p, X)

        using OrdinaryDiffEq
        @test is_point(M, exp(M, p, X))

        # a small trick to check that retract_exp_ode! returns the right value on ConnectionManifolds
        N2 = ConnectionManifold(E, TestConnection())
        @test exp(N2, p, X) == X
    end
    @testset "Local Metric Error message" begin
        M = MetricManifold(BaseManifold{2}(), NotImplementedMetric())
        A = Manifolds.get_default_atlas(M)
        p = [3, 4]
        i = get_chart_index(M, A, p)

        B = induced_basis(M, A, i, TangentSpace)
        @test_throws MethodError local_metric(M, p, B)
    end
    @testset "scaled Euclidean metric" begin
        n = 3
        E = TestEuclidean{n}()
        g = TestEuclideanMetric()
        M = MetricManifold(E, g)
        A = Manifolds.get_default_atlas(M)
        @test repr(M) == "MetricManifold(TestEuclidean{3}(), TestEuclideanMetric())"

        @test TestEuclideanMetric()(E) === M
        @test TestEuclideanMetric(E) === M
        @test connection(M) === Manifolds.LeviCivitaConnection()

        G = Diagonal(1.0:n)
        invG = inv(G)
        @test manifold_dimension(M) == n
        @test base_manifold(M) === E
        @test metric(M) === g

        i_zeros = get_chart_index(M, A, zeros(3))
        B_i_zeros = induced_basis(M, A, i_zeros, TangentSpace)
        @test_throws MethodError local_metric_jacobian(E, zeros(3), B_i_zeros)
        @test_throws MethodError christoffel_symbols_second_jacobian(E, zeros(3), B_i_zeros)

        for vtype in (Vector, MVector{n})
            p, X, Y = vtype(randn(n)), vtype(randn(n)), vtype(randn(n))

            chart_p = get_chart_index(M, A, p)
            B_chart_p = induced_basis(M, A, chart_p, TangentSpace)

            @test check_point(M, p) == check_point(E, p)
            @test check_vector(M, p, X) == check_vector(E, p, X)

            @test local_metric(M, p, B_chart_p) ≈ G
            @test inverse_local_metric(M, p, B_chart_p) ≈ invG
            @test det_local_metric(M, p, B_chart_p) ≈ *(1.0:n...)
            @test log_local_metric_density(M, p, B_chart_p) ≈ sum(log.(1.0:n)) / 2

            fX = ManifoldsBase.TFVector(X, B_chart_p)
            fY = ManifoldsBase.TFVector(Y, B_chart_p)
            @test inner(M, p, fX, fY) ≈ dot(X, G * Y) atol = 1e-6
            @test norm(M, p, fX) ≈ sqrt(dot(X, G * X)) atol = 1e-6

            @test christoffel_symbols_first(M, p, B_chart_p) ≈ zeros(n, n, n) atol = 1e-6
            @test christoffel_symbols_second(M, p, B_chart_p) ≈ zeros(n, n, n) atol = 1e-6
            @test riemann_tensor(M, p, B_chart_p) ≈ zeros(n, n, n, n) atol = 1e-6
            @test ricci_tensor(M, p, B_chart_p) ≈ zeros(n, n) atol = 1e-6
            @test ricci_curvature(M, p, B_chart_p) ≈ 0 atol = 1e-6
            @test gaussian_curvature(M, p, B_chart_p) ≈ 0 atol = 1e-6
            @test einstein_tensor(M, p, B_chart_p) ≈ zeros(n, n) atol = 1e-6

            fdm = FiniteDifferencesBackend(forward_fdm(2, 1))
            @test christoffel_symbols_first(M, p, B_chart_p; backend=fdm) ≈ zeros(n, n, n) atol =
                1e-6
            @test christoffel_symbols_second(M, p, B_chart_p; backend=fdm) ≈ zeros(n, n, n) atol =
                1e-6
            @test riemann_tensor(M, p, B_chart_p; backend=fdm) ≈ zeros(n, n, n, n) atol =
                1e-6
            @test ricci_tensor(M, p, B_chart_p; backend=fdm) ≈ zeros(n, n) atol = 1e-6
            @test ricci_curvature(M, p, B_chart_p; backend=fdm) ≈ 0 atol = 1e-6
            @test gaussian_curvature(M, p, B_chart_p; backend=fdm) ≈ 0 atol = 1e-6
            @test einstein_tensor(M, p, B_chart_p; backend=fdm) ≈ zeros(n, n) atol = 1e-6

            fd_diff = Manifolds.FiniteDifferencesBackend()
            @test christoffel_symbols_first(M, p, B_chart_p; backend=fd_diff) ≈
                  zeros(n, n, n) atol = 1e-6
            @test christoffel_symbols_second(M, p, B_chart_p; backend=fd_diff) ≈
                  zeros(n, n, n) atol = 1e-6
            @test riemann_tensor(M, p, B_chart_p; backend=fd_diff) ≈ zeros(n, n, n, n) atol =
                1e-6
            @test ricci_tensor(M, p, B_chart_p; backend=fd_diff) ≈ zeros(n, n) atol = 1e-6
            @test ricci_curvature(M, p, B_chart_p; backend=fd_diff) ≈ 0 atol = 1e-6
            @test gaussian_curvature(M, p, B_chart_p; backend=fd_diff) ≈ 0 atol = 1e-6
            @test einstein_tensor(M, p, B_chart_p; backend=fd_diff) ≈ zeros(n, n) atol =
                1e-6
        end
    end

    @testset "scaled Sphere metric" begin
        n = 2
        r = 10 * rand()
        θ, ϕ = π * rand(), 2π * rand()
        Sr = TestSphere{n,Float64}(r)
        S = Manifolds.Sphere(n)
        g = TestSphericalMetric()
        M = MetricManifold(Sr, g)
        A = Manifolds.get_default_atlas(M)

        @test manifold_dimension(M) == n
        @test base_manifold(M) === Sr
        @test metric(M) === g

        for vtype in (Vector, MVector{n})
            p = vtype([θ, ϕ])
            chart_p = get_chart_index(M, A, p)
            B_p = induced_basis(M, A, chart_p, TangentSpace)
            G = Diagonal(vtype([1, sin(θ)^2])) .* r^2
            invG = Diagonal(vtype([1, 1 / sin(θ)^2])) ./ r^2
            X, Y = normalize(randn(n)), normalize(randn(n))

            @test local_metric(M, p, B_p) ≈ G atol = 1e-6
            @test inverse_local_metric(M, p, B_p) ≈ invG atol = 1e-6
            @test det_local_metric(M, p, B_p) ≈ r^4 * sin(θ)^2 atol = 1e-6
            @test log_local_metric_density(M, p, B_p) ≈ 2 * log(r) + log(sin(θ)) atol = 1e-6
            fX = ManifoldsBase.TFVector(X, B_p)
            fY = ManifoldsBase.TFVector(Y, B_p)
            @test inner(M, p, fX, fY) ≈ dot(X, G * Y) atol = 1e-6
            @test norm(M, p, fX) ≈ sqrt(dot(X, G * X)) atol = 1e-6

            pcart = sph_to_cart(θ, ϕ)
            Xcart = [
                cos(ϕ)*cos(θ) -sin(ϕ)*sin(θ)
                sin(ϕ)*cos(θ) cos(ϕ)*sin(θ)
                -sin(θ) 0
            ] * X

            Γ₁ = christoffel_symbols_first(M, p, B_p)
            for i in 1:n, j in 1:n, k in 1:n
                if (i, j, k) == (1, 2, 2) || (i, j, k) == (2, 1, 2)
                    @test Γ₁[i, j, k] ≈ r^2 * cos(θ) * sin(θ) atol = 1e-6
                elseif (i, j, k) == (2, 2, 1)
                    @test Γ₁[i, j, k] ≈ -r^2 * cos(θ) * sin(θ) atol = 1e-6
                else
                    @test Γ₁[i, j, k] ≈ 0 atol = 1e-6
                end
            end

            Γ₂ = christoffel_symbols_second(M, p, B_p)
            for l in 1:n, i in 1:n, j in 1:n
                if (l, i, j) == (1, 2, 2)
                    @test Γ₂[l, i, j] ≈ -cos(θ) * sin(θ) atol = 1e-6
                elseif (l, i, j) == (2, 1, 2) || (l, i, j) == (2, 2, 1)
                    @test Γ₂[l, i, j] ≈ cot(θ) atol = 1e-6
                else
                    @test Γ₂[l, i, j] ≈ 0 atol = 1e-6
                end
            end

            R = riemann_tensor(M, p, B_p)
            for l in 1:n, i in 1:n, j in 1:n, k in 1:n
                if (l, i, j, k) == (2, 1, 1, 2)
                    @test R[l, i, j, k] ≈ -1 atol = 2e-6
                elseif (l, i, j, k) == (2, 1, 2, 1)
                    @test R[l, i, j, k] ≈ 1 atol = 2e-6
                elseif (l, i, j, k) == (1, 2, 1, 2)
                    @test R[l, i, j, k] ≈ sin(θ)^2 atol = 1e-6
                elseif (l, i, j, k) == (1, 2, 2, 1)
                    @test R[l, i, j, k] ≈ -sin(θ)^2 atol = 1e-6
                else
                    @test R[l, i, j, k] ≈ 0 atol = 1e-6
                end
            end

            @test ricci_tensor(M, p, B_p) ≈ G ./ r^2 atol = 2e-6
            @test ricci_curvature(M, p, B_p) ≈ 2 / r^2 atol = 2e-6
            @test gaussian_curvature(M, p, B_p) ≈ 1 / r^2 atol = 2e-6
            @test einstein_tensor(M, p, B_p) ≈
                  ricci_tensor(M, p, B_p) - gaussian_curvature(M, p, B_p) .* G atol = 1e-6
        end
    end

    @testset "Metric decorator" begin
        M = BaseManifold{3}()
        g = BaseManifoldMetric{3}()
        MM = MetricManifold(M, g)

        @test DefaultBaseManifoldMetric(BaseManifold{3}()) ===
              MetricManifold(BaseManifold{3}(), DefaultBaseManifoldMetric())
        MT = DefaultBaseManifoldMetric()
        @test MT(BaseManifold{3}()) ===
              MetricManifold(BaseManifold{3}(), DefaultBaseManifoldMetric())

        g2 = DefaultBaseManifoldMetric()
        MM2 = MetricManifold(M, g2)
        A = Manifolds.get_default_atlas(M)

        @test is_default_metric(MM) == is_default_metric(base_manifold(MM), metric(MM))
        @test is_default_metric(MM2) == is_default_metric(base_manifold(MM2), metric(MM2))
        @test is_default_metric(MM2)

        @test convert(typeof(MM2), M) == MM2
        @test_throws ErrorException convert(typeof(MM), M)
        p = [0.1, 0.2, 0.4]
        X = [0.5, 0.7, 0.11]
        Y = [0.13, 0.17, 0.19]
        q = allocate(p)

        p2 = allocate(p)
        copyto!(MM, p2, p)
        p3 = allocate(p)
        copyto!(M, p3, p)
        @test p2 == p3
        X = zero_vector(MM, p)
        Y = allocate(X)
        copyto!(MM, Y, p, X)
        Y2 = allocate(X)
        copyto!(M, Y2, p, X)
        @test Y == Y2

        chart_p = get_chart_index(M, A, p)
        B_p = induced_basis(M, A, chart_p, TangentSpace)
        fX = ManifoldsBase.TFVector(X, B_p)
        fY = ManifoldsBase.TFVector(Y, B_p)

        @test inner(M, p, X, Y) == 2 * dot(X, Y)
        @test inner(MM, p, fX, fY) === inner(M, p, X, Y)
        @test norm(MM, p, fX) === norm(M, p, X)
        @test exp(M, p, X) == p + 2 * X
        @test exp(MM2, p, X) == exp(M, p, X)
        @test exp!(MM, q, p, X) === exp!(M, q, p, X)
        @test retract!(MM, q, p, X) === retract!(M, q, p, X)
        @test retract!(MM, q, p, X, 1) === retract!(M, q, p, X, 1)
        @test project!(MM, Y, p, X) === project!(M, Y, p, X)
        @test project!(MM, q, p) === project!(M, q, p)
        # without a definition for the metric from the embedding, no projection possible
        @test_throws MethodError log!(MM, Y, p, q) === project!(M, Y, p, q)
        @test_throws MethodError vector_transport_to!(MM, Y, p, X, q) ===
                                 vector_transport_to!(M, Y, p, X, q)
        # without DiffEq, these error
        @test_throws MethodError exp(MM, p, X, 1:3)
        # these always fall back anyways.
        @test zero_vector!(MM, X, p) === zero_vector!(M, X, p)

        @test injectivity_radius(MM, p) === injectivity_radius(M, p)
        @test injectivity_radius(MM) === injectivity_radius(M)
        @test injectivity_radius(MM, ProjectionRetraction()) ===
              injectivity_radius(M, ProjectionRetraction())
        @test injectivity_radius(MM, ExponentialRetraction()) ===
              injectivity_radius(M, ExponentialRetraction())
        @test injectivity_radius(MM) === injectivity_radius(M)

        @test is_point(MM, p) === is_point(M, p)
        @test is_vector(MM, p, X) === is_vector(M, p, X)

        A = Manifolds.get_default_atlas(MM2)
        chart_p = get_chart_index(MM2, A, p)
        B_p = induced_basis(MM2, A, chart_p, TangentSpace)
        @test_throws MethodError local_metric(MM2, p, B_p)
        @test_throws MethodError local_metric_jacobian(MM2, p, B_p)
        @test_throws MethodError christoffel_symbols_second_jacobian(MM2, p, B_p)
        # MM falls back to nondefault error
        @test_throws MethodError projected_distribution(MM, 1, p)
        @test_throws MethodError projected_distribution(MM, 1)

        @test inner(MM2, p, X, Y) === inner(M, p, X, Y)
        @test norm(MM2, p, X) === norm(M, p, X)
        @test distance(MM2, p, q) === distance(M, p, q)
        @test exp!(MM2, q, p, X) === exp!(M, q, p, X)
        @test exp(MM2, p, X) == exp(M, p, X)
        @test log!(MM2, X, p, q) === log!(M, X, p, q)
        @test log(MM2, p, q) == log(M, p, q)
        @test retract!(MM2, q, p, X) === retract!(M, q, p, X)
        @test retract!(MM2, q, p, X, 1) === retract!(M, q, p, X, 1)

        @test project!(MM2, q, p) === project!(M, q, p)
        @test project!(MM2, Y, p, X) === project!(M, Y, p, X)
        @test parallel_transport_to(MM2, p, X, q) == parallel_transport_to(M, q, X, p)
        @test parallel_transport_to!(MM2, Y, p, X, q) ==
              parallel_transport_to!(M, Y, q, X, p)
        @test project!(MM2, Y, p, X) === project!(M, Y, p, X)
        @test vector_transport_to!(MM2, Y, p, X, q) == vector_transport_to!(M, Y, p, X, q)
        c = 2 * ones(3)
        m = ParallelTransport()
        @test vector_transport_along(MM2, p, X, c, m) ==
              vector_transport_along(M, p, X, c, m)
        @test vector_transport_along!(MM2, Y, p, X, c, m) ==
              vector_transport_along!(M, Y, p, X, c, m)
        @test zero_vector!(MM2, X, p) === zero_vector!(M, X, p)
        @test injectivity_radius(MM2, p) === injectivity_radius(M, p)
        @test injectivity_radius(MM2) === injectivity_radius(M)
        @test injectivity_radius(MM2, p, ExponentialRetraction()) ===
              injectivity_radius(M, p, ExponentialRetraction())
        @test injectivity_radius(MM2, ExponentialRetraction()) ===
              injectivity_radius(M, ExponentialRetraction())
        @test injectivity_radius(MM2, p, ProjectionRetraction()) ===
              injectivity_radius(M, p, ProjectionRetraction())
        @test injectivity_radius(MM2, ProjectionRetraction()) ===
              injectivity_radius(M, ProjectionRetraction())
        @test is_point(MM2, p) === is_point(M, p)
        @test is_vector(MM2, p, X) === is_vector(M, p, X)

        a = Manifolds.projected_distribution(M, Distributions.MvNormal(zero(zeros(3)), 1.0))
        b = Manifolds.projected_distribution(
            MM2,
            Distributions.MvNormal(zero(zeros(3)), 1.0),
        )
        @test isapprox(Matrix(a.distribution.Σ), Matrix(b.distribution.Σ))
        @test isapprox(a.distribution.μ, b.distribution.μ)
        @test get_basis(M, p, DefaultOrthonormalBasis()).data ==
              get_basis(MM2, p, DefaultOrthonormalBasis()).data
        @test_throws MethodError get_basis(MM, p, DefaultOrthonormalBasis())

        fX = ManifoldsBase.TFVector(X, B_p)
        fY = ManifoldsBase.TFVector(Y, B_p)
        coX = flat(M, p, X)
        coY = flat(M, p, Y)
        cofX = flat(M, p, fX)
        cofY = flat(M, p, fY)
        @test coX(X) ≈ norm(M, p, X)^2
        @test coY(X) ≈ inner(M, p, X, Y)
        cotspace = CotangentBundleFibers(M)
        cotspace2 = CotangentBundleFibers(MM)
        @test coX.X ≈ X
        @test inner(M, p, X, Y) ≈ inner(cotspace, p, coX, coY)
        @test inner(MM, p, fX, fY) ≈ inner(cotspace, p, coX, coY)

        @test inner(MM, p, fX, fY) ≈ inner(cotspace2, p, cofX, cofY)
        @test sharp(M, p, coX) ≈ X

        coMMfX = flat(MM, p, fX)
        coMMfY = flat(MM, p, fY)
        @test inner(MM, p, fX, fY) ≈ inner(cotspace2, p, coMMfX, coMMfY)
        @test isapprox(sharp(MM, p, coMMfX).data, fX.data)

        @testset "Mutating flat/sharp" begin
            cofX2 = allocate(cofX)
            flat!(M, cofX2, p, fX)
            @test isapprox(cofX2.data, cofX.data)

            fX2 = allocate(fX)
            sharp!(M, fX2, p, cofX2)
            @test isapprox(fX2.data, fX.data)

            cofX2 = allocate(cofX)
            flat!(MM, cofX2, p, fX)
            @test isapprox(cofX2.data, cofX.data)

            fX2 = allocate(fX)
            sharp!(MM, fX2, p, cofX2)
            @test isapprox(fX2.data, fX.data)

            cofX3a = flat(MM2, p, fX)
            cofX3b = allocate(cofX3a)
            flat!(MM2, cofX3b, p, fX)
            @test isapprox(cofX3a.data, cofX3b.data)

            fX3a = sharp(MM2, p, cofX)
            fX3b = allocate(fX3a)
            sharp!(MM2, fX3b, p, cofX)
            @test isapprox(fX3a.data, fX3b.data)
        end
    end

    @testset "change metric and representer" begin
        M = MetricManifold(TestEuclidean{2}(), TestEuclideanMetric())
        G = TestScaledEuclideanMetric()
        M2 = TestScaledEuclideanMetric(M)
        @test M2.manifold === M.manifold
        @test M2.metric == G
        p = ones(2)
        X = 2 * ones(2)
        @test change_metric(M, TestEuclideanMetric(), p, X) == X
        Y = change_metric(M, G, p, X)
        @test Y ≈ sqrt(2) .* X #scaled metric has a factor 2, removing introduces this factor
        @test change_representer(M, TestEuclideanMetric(), p, X) == X
        Y2 = change_representer(M, G, p, X)
        @test Y2 ≈ 2 .* X #scaled metric has a factor 2, removing introduces this factor
    end
end


text:
# create an exception
x = -9
try
    println(sqrt(x))
catch ex
    println("==============")
    println(ex)
    println("==============")
finally
    println("This code always runs ....")
end

max_stars_repo_name: rpillar/JuliaExamples

max_issues_repo_name: rpillar/JuliaExamples

max_forks_repo_name: rpillar/JuliaExamples


text:
function brig(f::Function, types::ANY)
    t = to_tuple_type(types)
    brig_ptr = ccall(:jl_get_brigf, Ptr{BrigModuleHeader}, (Any, Any), f, t)

    return brig_ptr
end

import .ExtFinalization: Program, program_finalize, program_add_module

function finalize_brig(brig_ptr::Ptr{BrigModuleHeader}, isa)
    program = Program()

    program_add_module(program, brig_ptr)

    code_object = program_finalize(program, isa, 0)

    finalize(program)

    return code_object
end


text:
using InteractiveDynamics, GLMakie

A = rand(5, 5)
A[1,1] = 0
A[5,5] = 1
A[3,3] = 0.5

fig = Figure(resolution=(2000, 1000))
display(fig)

ax, hm = heatmap(fig[1,1], A; colormap = JULIADYNAMICS_CMAP, colorrange=(0,1))
Colorbar(fig[1, 2], hm)
ax, hm = heatmap(fig[1,3], A; colormap = JULIADYNAMICS_CMAP_DIVERGING, colorrange=(0,1))
Colorbar(fig[1, 4], hm)


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

import LinearAlgebra: BlasInt
using Logging

# A convenient shortcut to show unexpected behavior from libarpack
const ERR_UNEXPECTED_BEHAVIOR = -999

struct XYAUPD_Exception <: Exception
    info::BlasInt
end

const AUPD_ERRORS = [
    (3, "No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration. One possibility is to increase the size of NCV relative to NEV. "),
    (2, "No longer an informational error. Deprecated starting with release 2 of ARPACK."),
    (1, """Maximum number of iterations taken. All possible eigenvalues of OP has been found.
          IPARAM(5) returns the number of wanted converged Ritz values."""),
    (0, "Normal exit."),
    (-1, "N must be positive."),
    (-2, "NEV must be positive."),
    (-3, "NCV-NEV >= 2 and less than or equal to N."),
    (-4, "The maximum number of Arnoldi update iterations allowed must be greater than zero."),
    (-5, " WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'"),
    (-6, "BMAT must be one of 'I' or 'G'."),
    (-7, "Length of private work array WORKL is not sufficient."),
    (-8, "Error return from LAPACK eigenvalue calculation."),
    (-9, "Starting vector is zero."),
    (-10, "IPARAM(7) must be 1,2,3,4."),
    (-11, "IPARAM(7) = 1 and BMAT = 'G' are incompatible."),
    (-12, "IPARAM(1) must be equal to 0 or 1."),
    (-13, "NEV and WHICH = 'BE' are incompatible."),
    (-9999, """Could not build an Arnoldi factorization.
           IPARAM(5) returns the size of the current Arnoldi factorization.
           The user is advised to check that enough workspace and array storage has been allocated.""")
]

function Base.showerror(io::IO, ex::XYAUPD_Exception)
    info = ex.info

    if info == ERR_UNEXPECTED_BEHAVIOR
        @error "XYAUPD_Exception: Undefined error"
    else
      idx = searchsorted(AUPD_ERRORS, info, by=first, rev=true)
      if isempty(idx)
          @error "XYAUPD_Exception: Please check XYAUPD error codes in the ARPACK manual." info
      else
          @error "XYAUPD_Exception: $(last(AUPD_ERRORS[first(idx)]))" info
      end
    end
end

struct XYEUPD_Exception <: Exception
    info::BlasInt
end

const EUPD_ERRORS = [
    (1, """The Schur form computed by LAPACK routine lahqr could not be reordered by LAPACK routine trsen.
       Re-enter subroutine neupd with IPARAM(5)NCV and increase the size of the arrays DR and DI to have dimension at least dimension NCV and allocate at least NCV columns for Z.
       NOTE: Not necessary if Z and V share the same space. Please notify the authors if this error occurs."""),
    (0, "Normal exit."),
    (-1, "N must be positive."),
    (-2, "NEV must be positive."),
    (-3, "NCV-NEV >= 2 and less than or equal to N."),
    (-5, "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'"),
    (-6, "BMAT must be one of 'I' or 'G'."),
    (-7, "Length of private work WORKL array is not sufficient."),
    (-8, """Error return from calculation of a real Schur form.
        "Informational error from LAPACK routine lahqr ."""),
    (-9, """Error return from calculation of eigenvectors.
        "Informational error from LAPACK routine dtrevc."""),
    (-10, "IPARAM(7) must be 1,2,3,4."),
    (-11, "IPARAM(7) = 1 and BMAT = 'G' are incompatible."),
    (-12, "HOWMNY = 'S' not yet implemented"),
    (-13, "HOWMNY must be one of 'A' or 'P' if RVEC = .true."),
    (-14, "DNAUPD  did not find any eigenvalues to sufficient accuracy."),
    (-15, """DNEUPD got a different count of the number of converged Ritz values than NAUPD got.
          This indicates the user probably made an error in passing data from NAUPD to NEUPD or that the data was modified before entering NEUPD""")
]

function Base.showerror(io::IO, ex::XYEUPD_Exception)
    info = ex.info
    if info == ERR_UNEXPECTED_BEHAVIOR
        @error "XYEUPD_Exception: Undefined error"
    else
      idx = searchsorted(EUPD_ERRORS, info, by=first, rev=true)
      if isempty(idx)
          @error "XYEUPD_Exception: Please check XYEUPD error codes in the ARPACK manual." info
      else
          @error "XYEUPD_Exception: $(last(EUPD_ERRORS[first(idx)]))" info
      end
    end
end

## aupd and eupd wrappers

function aupd_wrapper(T, matvecA!::Function, matvecB::Function, solveSI::Function, n::Integer,
                      sym::Bool, cmplx::Bool, bmat,
                      nev::Integer, ncv::Integer, which,
                      tol::Real, maxiter::Integer, mode::Integer, v0::Vector, check::Integer)
    lworkl = cmplx ? ncv * (3*ncv + 5) : (sym ? ncv * (ncv + 8) :  ncv * (3*ncv + 6) )
    TR = cmplx ? T.types[1] : T
    TOL = Ref{TR}(tol)

    v     = Matrix{T}(undef, n, ncv)
    workd = Vector{T}(undef, 3*n)
    workl = Vector{T}(undef, lworkl)
    rwork = cmplx ? Vector{TR}(undef, ncv) : Vector{TR}()

    if isempty(v0)
        resid = Vector{T}(undef, n)
        info  = Ref{BlasInt}(0)
    else
        resid = deepcopy(v0)
        info  = Ref{BlasInt}(1)
    end
    iparam = zeros(BlasInt, 11)
    ipntr  = zeros(BlasInt, (sym && !cmplx) ? 11 : 14)
    ido    = Ref{BlasInt}(0)

    iparam[1] = BlasInt(1)       # ishifts
    iparam[3] = BlasInt(maxiter) # maxiter
    iparam[7] = BlasInt(mode)    # mode

    zernm1 = 0:(n-1)

    while true
        if cmplx
            naupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n,
                  iparam, ipntr, workd, workl, lworkl, rwork, info)
        elseif sym
            saupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n,
                  iparam, ipntr, workd, workl, lworkl, info)
        else
            naupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n,
                  iparam, ipntr, workd, workl, lworkl, info)
        end
        if info[] != 0
            if info[] == 1 && check != 0
                return (resid, v, n, iparam, ipntr, workd, workl, lworkl, rwork, TOL)
            end
            throw(XYAUPD_Exception(info[]))
        end

        x = view(workd, ipntr[1] .+ zernm1)
        y = view(workd, ipntr[2] .+ zernm1)
        if mode == 1  # corresponds to dsdrv1, dndrv1 or zndrv1
            if ido[] == -1 || ido[] == 1
                matvecA!(y, x)
            elseif ido[] == 99
                break
            else
                throw(XYAUPD_Exception(ERR_UNEXPECTED_BEHAVIOR))
            end
        elseif mode == 3 && bmat == "I" # corresponds to dsdrv2, dndrv2 or zndrv2
            if ido[] == -1 || ido[] == 1
                y[:] = solveSI(x)
            elseif ido[] == 99
                break
            else
                throw(XYAUPD_Exception(ERR_UNEXPECTED_BEHAVIOR))
            end
        elseif mode == 2 # corresponds to dsdrv3, dndrv3 or zndrv3
            if ido[] == -1 || ido[] == 1
                matvecA!(y, x)
                if sym
                    x[:] = y    # overwrite as per Remark 5 in dsaupd.f
                end
                y[:] = solveSI(y)
            elseif ido[] == 2
                y[:] = matvecB(x)
            elseif ido[] == 99
                break
            else
                throw(XYAUPD_Exception(ERR_UNEXPECTED_BEHAVIOR))
            end
        elseif mode == 3 && bmat == "G" # corresponds to dsdrv4, dndrv4 or zndrv4
            if ido[] == -1
                y[:] = solveSI(matvecB(x))
            elseif  ido[] == 1
                y[:] = solveSI(view(workd,ipntr[3] .+ zernm1))
            elseif ido[] == 2
                y[:] = matvecB(x)
            elseif ido[] == 99
                break
            else
                throw(XYAUPD_Exception(ERR_UNEXPECTED_BEHAVIOR))
            end
        else
            throw(ArgumentError("ARPACK mode ($mode) not yet supported"))
        end
    end

    return (resid, v, n, iparam, ipntr, workd, workl, lworkl, rwork, TOL)
end

function eupd_wrapper(T, n::Integer, sym::Bool, cmplx::Bool, bmat,
                      nev::Integer, which, ritzvec::Bool,
                      TOL::Ref, resid, ncv::Integer, v, ldv, sigma, iparam, ipntr,
                      workd, workl, lworkl, rwork)
    howmny = "A"
    select = Vector{BlasInt}(undef, ncv)
    info   = Ref{BlasInt}(0)

    dmap = x -> abs.(x)
    if iparam[7] == 3 # shift-and-invert
        dmap = x -> abs.(1 ./ (x .- sigma))
    elseif which == "LR" || which == "LA" || which == "BE"
        dmap = real
    elseif which == "SR" || which == "SA"
        dmap = x -> -real(x)
    elseif which == "LI"
        dmap = imag
    elseif which == "SI"
        dmap = x -> -imag(x)
    end

    if cmplx
        d = Vector{T}(undef, nev+1)
        sigmar = Ref{T}(sigma)
        workev = Vector{T}(undef, 2ncv)
        neupd(ritzvec, howmny, select, d, v, ldv, sigmar, workev,
              bmat, n, which, nev, TOL, resid, ncv, v, ldv,
              iparam, ipntr, workd, workl, lworkl, rwork, info)
        if info[] != 0
            throw(XYEUPD_Exception(info[]))
        end

        p = sortperm(dmap(d[1:nev]), rev=true)
        return ritzvec ? (d[p], v[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d[p],iparam[5],iparam[3],iparam[9],resid)
    elseif sym
        d = Vector{T}(undef, nev)
        sigmar = Ref{T}(sigma)
        seupd(ritzvec, howmny, select, d, v, ldv, sigmar,
              bmat, n, which, nev, TOL, resid, ncv, v, ldv,
              iparam, ipntr, workd, workl, lworkl, info)
        if info[] != 0
            throw(XYEUPD_Exception(info[]))
        end

        p = sortperm(dmap(d), rev=true)
        return ritzvec ? (d[p], v[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d[p],iparam[5],iparam[3],iparam[9],resid)
    else
        dr = Vector{T}(undef, nev+1)
        di = Vector{T}(undef, nev+1)
        fill!(dr,NaN)
        fill!(di,NaN)
        sigmar = Ref{T}(real(sigma))
        sigmai = Ref{T}(imag(sigma))
        workev = Vector{T}(undef, 3*ncv)
        neupd(ritzvec, howmny, select, dr, di, v, ldv, sigmar, sigmai,
              workev, bmat, n, which, nev, TOL, resid, ncv, v, ldv,
              iparam, ipntr, workd, workl, lworkl, info)
        if info[] != 0
            throw(XYEUPD_Exception(info[]))
        end
        evec = complex.(Matrix{T}(undef, n, nev+1), Matrix{T}(undef, n, nev+1))

        j = 1
        while j <= nev
            if di[j] == 0
                evec[:,j] = v[:,j]
            else # For complex conjugate pairs
                evec[:,j]   = v[:,j] + im*v[:,j+1]
                evec[:,j+1] = v[:,j] - im*v[:,j+1]
                j += 1
            end
            j += 1
        end
        if j == nev+1 && !isnan(di[j])
            if di[j] == 0
                evec[:,j] = v[:,j]
                j += 1
            else
                throw(XYEUPD_Exception(ERR_UNEXPECTED_BEHAVIOR))
            end
        end

        d = complex.(dr, di)

        if j == nev+1
            p = sortperm(dmap(d[1:nev]), rev=true)
        else
            p = sortperm(dmap(d), rev=true)
            p = p[1:nev]
        end

        return ritzvec ? (d[p], evec[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d[p],iparam[5],iparam[3],iparam[9],resid)
    end
end

for (T, saupd_name, seupd_name, naupd_name, neupd_name) in
    ((:Float64, :dsaupd_, :dseupd_, :dnaupd_, :dneupd_),
     (:Float32, :ssaupd_, :sseupd_, :snaupd_, :sneupd_))
    @eval begin
        function naupd(ido, bmat, n, evtype, nev, TOL::Ref{$T}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,
                       iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl, info)
            ccall(($(string(naupd_name)), libarpack), Cvoid,
                  (Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},
                   Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},
                   Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ref{BlasInt}, Clong, Clong),
                  ido, bmat, n, evtype, nev,
                  TOL, resid, ncv, v, ldv,
                  iparam, ipntr, workd, workl, lworkl, info, 1, 2)
        end

        function neupd(rvec, howmny, select, dr, di, z, ldz, sigmar, sigmai,
                  workev::Vector{$T}, bmat, n, evtype, nev, TOL::Ref{$T}, resid::Vector{$T}, ncv, v, ldv,
                  iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl, info)
            ccall(($(string(neupd_name)), libarpack), Cvoid,
                  (Ref{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{$T}, Ref{BlasInt},
                   Ref{$T}, Ref{$T}, Ptr{$T}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},
                   Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},
                   Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ref{BlasInt}, Clong, Clong, Clong),
                  rvec, howmny, select, dr, di, z, ldz,
                  sigmar, sigmai, workev, bmat, n, evtype, nev,
                  TOL, resid, ncv, v, ldv,
                  iparam, ipntr, workd, workl, lworkl, info, 1, 1, 2)
        end

        function saupd(ido, bmat, n, which, nev, TOL::Ref{$T}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,
                       iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl, info)
            ccall(($(string(saupd_name)), libarpack), Cvoid,
                  (Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},
                   Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},
                   Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ref{BlasInt}, Clong, Clong),
                  ido, bmat, n, which, nev,
                  TOL, resid, ncv, v, ldv,
                  iparam, ipntr, workd, workl, lworkl, info, 1, 2)
        end

        function seupd(rvec, howmny, select, d, z, ldz, sigma,
                       bmat, n, evtype, nev, TOL::Ref{$T}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,
                       iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl, info)
            ccall(($(string(seupd_name)), libarpack), Cvoid,
                  (Ref{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt},
                   Ptr{$T}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},
                   Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},
                   Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ref{BlasInt}, Clong, Clong, Clong),
                  rvec, howmny, select, d, z, ldz,
                  sigma, bmat, n, evtype, nev,
                  TOL, resid, ncv, v, ldv,
                  iparam, ipntr, workd, workl, lworkl, info, 1, 1, 2)
        end
    end
end

for (T, TR, naupd_name, neupd_name) in
    ((:ComplexF64, :Float64, :znaupd_, :zneupd_),
     (:ComplexF32, :Float32, :cnaupd_, :cneupd_))
    @eval begin
        function naupd(ido, bmat, n, evtype, nev, TOL::Ref{$TR}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,
                       iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl,
                       rwork::Vector{$TR}, info)
            ccall(($(string(naupd_name)), libarpack), Cvoid,
                  (Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},
                   Ptr{$TR}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},
                   Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$TR}, Ref{BlasInt}, Clong, Clong),
                  ido, bmat, n, evtype, nev,
                  TOL, resid, ncv, v, ldv,
                  iparam, ipntr, workd, workl, lworkl, rwork, info, 1, 2)
        end

        function neupd(rvec, howmny, select, d, z, ldz, sigma, workev::Vector{$T},
                       bmat, n, evtype, nev, TOL::Ref{$TR}, resid::Vector{$T}, ncv, v::Matrix{$T}, ldv,
                       iparam, ipntr, workd::Vector{$T}, workl::Vector{$T}, lworkl,
                       rwork::Vector{$TR}, info)
            ccall(($(string(neupd_name)), libarpack), Cvoid,
                  (Ref{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt},
                   Ptr{$T}, Ptr{$T}, Ptr{UInt8}, Ref{BlasInt}, Ptr{UInt8}, Ref{BlasInt},
                   Ptr{$TR}, Ptr{$T}, Ref{BlasInt}, Ptr{$T}, Ref{BlasInt},
                   Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ref{BlasInt}, Ptr{$TR}, Ref{BlasInt}, Clong, Clong, Clong),
                  rvec, howmny, select, d, z, ldz,
                  sigma, workev, bmat, n, evtype, nev,
                  TOL, resid, ncv, v, ldv,
                  iparam, ipntr, workd, workl, lworkl, rwork, info, 1, 1, 2)
        end
    end
end