text:
# RUN: julia -e "import Brutus; Brutus.lit(:emit_optimized)" --startup-file=no %s 2>&1 | FileCheck %s

function calls()
    f = rand(Bool) ? (+) : (-)
    return f(1, 1)
end
emit(calls)

# CHECK: Core.MethodMatch(Tuple{typeof(Main.Main.calls)}, svec(), calls() in Main.Main at /home/mccoy/Dev/brutus/test/Codegen/canonicalize/calls.jl:3, true)after translating to MLIR in JLIR dialect:module  {
# CHECK-NEXT:   func nested @"Tuple{typeof(Main.calls)}"(%arg0: !jlir<"typeof(Main.calls)">) -> !jlir.Int64 attributes {llvm.emit_c_interface} {
# CHECK-NEXT:     "jlir.goto"()[^bb1] : () -> ()
# CHECK-NEXT:   ^bb1:  // pred: ^bb0
# CHECK-NEXT:     %0 = "jlir.unimplemented"() : () -> !jlir.Int16
# CHECK-NEXT:     %1 = "jlir.constant"() {value = #jlir<"#<intrinsic #52 sext_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %2 = "jlir.constant"() {value = #jlir.Int64} : () -> !jlir.DataType
# CHECK-NEXT:     %3 = "jlir.call"(%1, %2, %0) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.DataType, !jlir.Int16) -> !jlir.Int64
# CHECK-NEXT:     %4 = "jlir.constant"() {value = #jlir<"#<intrinsic #2 add_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %5 = "jlir.constant"() {value = #jlir<"1">} : () -> !jlir.Int64
# CHECK-NEXT:     %6 = "jlir.call"(%4, %3, %5) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.Int64, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     %7 = "jlir.constant"() {value = #jlir.Random.default_rng} : () -> !jlir<"typeof(Random.default_rng)">
# CHECK-NEXT:     %8 = "jlir.invoke"(%7, %6) {methodInstance = #jlir<"default_rng(Int64) from default_rng(Int64)">} : (!jlir<"typeof(Random.default_rng)">, !jlir.Int64) -> !jlir.Random.MersenneTwister
# CHECK-NEXT:     %9 = "jlir.constant"() {value = #jlir.getfield} : () -> !jlir<"typeof(getfield)">
# CHECK-NEXT:     %10 = "jlir.constant"() {value = #jlir<":idxF">} : () -> !jlir.Symbol
# CHECK-NEXT:     %11 = "jlir.call"(%9, %8, %10) : (!jlir<"typeof(getfield)">, !jlir.Random.MersenneTwister, !jlir.Symbol) -> !jlir.Int64
# CHECK-NEXT:     %12 = "jlir.constant"() {value = #jlir<"1002">} : () -> !jlir.Int64
# CHECK-NEXT:     %13 = "jlir.constant"() {value = #jlir<"===">} : () -> !jlir<"typeof(===)">
# CHECK-NEXT:     %14 = "jlir.call"(%13, %11, %12) : (!jlir<"typeof(===)">, !jlir.Int64, !jlir.Int64) -> !jlir.Bool
# CHECK-NEXT:     "jlir.gotoifnot"(%14)[^bb3, ^bb2] {operand_segment_sizes = dense<[1, 0, 0]> : vector<3xi32>} : (!jlir.Bool) -> ()
# CHECK-NEXT:   ^bb2:  // pred: ^bb1
# CHECK-NEXT:     %15 = "jlir.constant"() {value = #jlir.Random.gen_rand} : () -> !jlir<"typeof(Random.gen_rand)">
# CHECK-NEXT:     %16 = "jlir.invoke"(%15, %8) {methodInstance = #jlir<"gen_rand(Random.MersenneTwister) from gen_rand(Random.MersenneTwister)">} : (!jlir<"typeof(Random.gen_rand)">, !jlir.Random.MersenneTwister) -> !jlir.Any
# CHECK-NEXT:     "jlir.goto"()[^bb3] : () -> ()
# CHECK-NEXT:   ^bb3:  // 2 preds: ^bb1, ^bb2
# CHECK-NEXT:     "jlir.goto"()[^bb4] : () -> ()
# CHECK-NEXT:   ^bb4:  // pred: ^bb3
# CHECK-NEXT:     %17 = "jlir.constant"() {value = #jlir.getfield} : () -> !jlir<"typeof(getfield)">
# CHECK-NEXT:     %18 = "jlir.constant"() {value = #jlir<":vals">} : () -> !jlir.Symbol
# CHECK-NEXT:     %19 = "jlir.call"(%17, %8, %18) : (!jlir<"typeof(getfield)">, !jlir.Random.MersenneTwister, !jlir.Symbol) -> !jlir<"Array{Float64, 1}">
# CHECK-NEXT:     %20 = "jlir.constant"() {value = #jlir.getfield} : () -> !jlir<"typeof(getfield)">
# CHECK-NEXT:     %21 = "jlir.constant"() {value = #jlir<":idxF">} : () -> !jlir.Symbol
# CHECK-NEXT:     %22 = "jlir.call"(%20, %8, %21) : (!jlir<"typeof(getfield)">, !jlir.Random.MersenneTwister, !jlir.Symbol) -> !jlir.Int64
# CHECK-NEXT:     %23 = "jlir.constant"() {value = #jlir<"#<intrinsic #2 add_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %24 = "jlir.constant"() {value = #jlir<"1">} : () -> !jlir.Int64
# CHECK-NEXT:     %25 = "jlir.call"(%23, %22, %24) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.Int64, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     %26 = "jlir.constant"() {value = #jlir<"setfield!">} : () -> !jlir<"typeof(setfield!)">
# CHECK-NEXT:     %27 = "jlir.constant"() {value = #jlir<":idxF">} : () -> !jlir.Symbol
# CHECK-NEXT:     %28 = "jlir.call"(%26, %8, %27, %25) : (!jlir<"typeof(setfield!)">, !jlir.Random.MersenneTwister, !jlir.Symbol, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     %29 = "jlir.constant"() {value = #jlir.Core.arrayref} : () -> !jlir<"typeof(Core.arrayref)">
# CHECK-NEXT:     %30 = "jlir.constant"() {value = #jlir.false} : () -> !jlir.Bool
# CHECK-NEXT:     %31 = "jlir.call"(%29, %30, %19, %25) : (!jlir<"typeof(Core.arrayref)">, !jlir.Bool, !jlir<"Array{Float64, 1}">, !jlir.Int64) -> !jlir.Float64
# CHECK-NEXT:     %32 = "jlir.constant"() {value = #jlir<"#<intrinsic #0 bitcast>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %33 = "jlir.constant"() {value = #jlir.UInt64} : () -> !jlir.DataType
# CHECK-NEXT:     %34 = "jlir.call"(%32, %33, %31) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.DataType, !jlir.Float64) -> !jlir.UInt64
# CHECK-NEXT:     "jlir.goto"()[^bb5] : () -> ()
# CHECK-NEXT:   ^bb5:  // pred: ^bb4
# CHECK-NEXT:     "jlir.goto"()[^bb6] : () -> ()
# CHECK-NEXT:   ^bb6:  // pred: ^bb5
# CHECK-NEXT:     %35 = "jlir.constant"() {value = #jlir<"#<intrinsic #41 and_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %36 = "jlir.constant"() {value = #jlir<"0x0000000000000001">} : () -> !jlir.UInt64
# CHECK-NEXT:     %37 = "jlir.call"(%35, %34, %36) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.UInt64, !jlir.UInt64) -> !jlir.UInt64
# CHECK-NEXT:     %38 = "jlir.constant"() {value = #jlir<"#<intrinsic #29 sle_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %39 = "jlir.constant"() {value = #jlir<"0">} : () -> !jlir.Int64
# CHECK-NEXT:     %40 = "jlir.constant"() {value = #jlir<"0">} : () -> !jlir.Int64
# CHECK-NEXT:     %41 = "jlir.call"(%38, %39, %40) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.Int64, !jlir.Int64) -> !jlir.Bool
# CHECK-NEXT:     %42 = "jlir.constant"() {value = #jlir<"#<intrinsic #0 bitcast>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %43 = "jlir.constant"() {value = #jlir.UInt64} : () -> !jlir.DataType
# CHECK-NEXT:     %44 = "jlir.constant"() {value = #jlir<"0">} : () -> !jlir.Int64
# CHECK-NEXT:     %45 = "jlir.call"(%42, %43, %44) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.DataType, !jlir.Int64) -> !jlir.UInt64
# CHECK-NEXT:     %46 = "jlir.constant"() {value = #jlir<"===">} : () -> !jlir<"typeof(===)">
# CHECK-NEXT:     %47 = "jlir.call"(%46, %37, %45) : (!jlir<"typeof(===)">, !jlir.UInt64, !jlir.UInt64) -> !jlir.Bool
# CHECK-NEXT:     %48 = "jlir.constant"() {value = #jlir<"#<intrinsic #41 and_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %49 = "jlir.call"(%48, %41, %47) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.Bool, !jlir.Bool) -> !jlir.Bool
# CHECK-NEXT:     %50 = "jlir.constant"() {value = #jlir<"#<intrinsic #44 not_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %51 = "jlir.call"(%50, %49) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.Bool) -> !jlir.Bool
# CHECK-NEXT:     "jlir.goto"()[^bb7] : () -> ()
# CHECK-NEXT:   ^bb7:  // pred: ^bb6
# CHECK-NEXT:     "jlir.goto"()[^bb8] : () -> ()
# CHECK-NEXT:   ^bb8:  // pred: ^bb7
# CHECK-NEXT:     "jlir.goto"()[^bb9] : () -> ()
# CHECK-NEXT:   ^bb9:  // pred: ^bb8
# CHECK-NEXT:     "jlir.gotoifnot"(%51)[^bb11, ^bb10] {operand_segment_sizes = dense<[1, 0, 0]> : vector<3xi32>} : (!jlir.Bool) -> ()
# CHECK-NEXT:   ^bb10:  // pred: ^bb9
# CHECK-NEXT:     %52 = "jlir.constant"() {value = #jlir<"Base.:(+)">} : () -> !jlir<"typeof(Base.:(+))">
# CHECK-NEXT:     %53 = "jlir.pi"(%52) : (!jlir<"typeof(Base.:(+))">) -> !jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">
# CHECK-NEXT:     "jlir.goto"(%53)[^bb12] : (!jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">) -> ()
# CHECK-NEXT:   ^bb11:  // pred: ^bb9
# CHECK-NEXT:     %54 = "jlir.constant"() {value = #jlir<"Base.:(-)">} : () -> !jlir<"typeof(Base.:(-))">
# CHECK-NEXT:     %55 = "jlir.pi"(%54) : (!jlir<"typeof(Base.:(-))">) -> !jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">
# CHECK-NEXT:     "jlir.goto"(%55)[^bb12] : (!jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">) -> ()
# CHECK-NEXT:   ^bb12(%56: !jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">):  // 2 preds: ^bb10, ^bb11
# CHECK-NEXT:     %57 = "jlir.constant"() {value = #jlir.isa} : () -> !jlir<"typeof(isa)">
# CHECK-NEXT:     %58 = "jlir.constant"() {value = #jlir<"typeof(Base.:(+))">} : () -> !jlir.DataType
# CHECK-NEXT:     %59 = "jlir.call"(%57, %56, %58) : (!jlir<"typeof(isa)">, !jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">, !jlir.DataType) -> !jlir.Bool
# CHECK-NEXT:     "jlir.gotoifnot"(%59)[^bb14, ^bb13] {operand_segment_sizes = dense<[1, 0, 0]> : vector<3xi32>} : (!jlir.Bool) -> ()
# CHECK-NEXT:   ^bb13:  // pred: ^bb12
# CHECK-NEXT:     %60 = "jlir.constant"() {value = #jlir<"#<intrinsic #2 add_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %61 = "jlir.constant"() {value = #jlir<"1">} : () -> !jlir.Int64
# CHECK-NEXT:     %62 = "jlir.constant"() {value = #jlir<"1">} : () -> !jlir.Int64
# CHECK-NEXT:     %63 = "jlir.call"(%60, %61, %62) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.Int64, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     "jlir.goto"(%63)[^bb17] : (!jlir.Int64) -> ()
# CHECK-NEXT:   ^bb14:  // pred: ^bb12
# CHECK-NEXT:     %64 = "jlir.constant"() {value = #jlir.isa} : () -> !jlir<"typeof(isa)">
# CHECK-NEXT:     %65 = "jlir.constant"() {value = #jlir<"typeof(Base.:(-))">} : () -> !jlir.DataType
# CHECK-NEXT:     %66 = "jlir.call"(%64, %56, %65) : (!jlir<"typeof(isa)">, !jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">, !jlir.DataType) -> !jlir.Bool
# CHECK-NEXT:     "jlir.gotoifnot"(%66)[^bb16, ^bb15] {operand_segment_sizes = dense<[1, 0, 0]> : vector<3xi32>} : (!jlir.Bool) -> ()
# CHECK-NEXT:   ^bb15:  // pred: ^bb14
# CHECK-NEXT:     %67 = "jlir.constant"() {value = #jlir<"#<intrinsic #3 sub_int>">} : () -> !jlir<"typeof(Core.IntrinsicFunction)">
# CHECK-NEXT:     %68 = "jlir.constant"() {value = #jlir<"1">} : () -> !jlir.Int64
# CHECK-NEXT:     %69 = "jlir.constant"() {value = #jlir<"1">} : () -> !jlir.Int64
# CHECK-NEXT:     %70 = "jlir.call"(%67, %68, %69) : (!jlir<"typeof(Core.IntrinsicFunction)">, !jlir.Int64, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     "jlir.goto"(%70)[^bb17] : (!jlir.Int64) -> ()
# CHECK-NEXT:   ^bb16:  // pred: ^bb14
# CHECK-NEXT:     %71 = "jlir.constant"() {value = #jlir.throw} : () -> !jlir<"typeof(throw)">
# CHECK-NEXT:     %72 = "jlir.constant"() {value = #jlir<"ErrorException("fatal error in type inference (type bound)")">} : () -> !jlir.ErrorException
# CHECK-NEXT:     %73 = "jlir.call"(%71, %72) : (!jlir<"typeof(throw)">, !jlir.ErrorException) -> !jlir<"Union{}">
# CHECK-NEXT:     %74 = "jlir.undef"() : () -> !jlir.Int64
# CHECK-NEXT:     "jlir.return"(%74) : (!jlir.Int64) -> ()
# CHECK-NEXT:   ^bb17(%75: !jlir.Int64):  // 2 preds: ^bb13, ^bb15
# CHECK-NEXT:     "jlir.return"(%75) : (!jlir.Int64) -> ()
# CHECK-NEXT:   }
# CHECK-NEXT: }

# CHECK:   func nested @"Tuple{typeof(Main.calls)}"(%arg0: !jlir<"typeof(Main.calls)">) -> !jlir.Int64 attributes {llvm.emit_c_interface} {
# CHECK-NEXT:     "jlir.goto"()[^bb1] : () -> ()
# CHECK-NEXT:   ^bb1:  // pred: ^bb0
# CHECK-NEXT:     %0 = "jlir.unimplemented"() : () -> !jlir.Int16
# CHECK-NEXT:     %1 = "jlir.constant"() {value = #jlir.Int64} : () -> !jlir.DataType
# CHECK-NEXT:     %2 = "jlir.sext_int"(%1, %0) : (!jlir.DataType, !jlir.Int16) -> !jlir.Int64
# CHECK-NEXT:     %3 = "jlir.constant"() {value = #jlir<"1">} : () -> !jlir.Int64
# CHECK-NEXT:     %4 = "jlir.add_int"(%2, %3) : (!jlir.Int64, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     %5 = "jlir.constant"() {value = #jlir.Random.default_rng} : () -> !jlir<"typeof(Random.default_rng)">
# CHECK-NEXT:     %6 = "jlir.invoke"(%5, %4) {methodInstance = #jlir<"default_rng(Int64) from default_rng(Int64)">} : (!jlir<"typeof(Random.default_rng)">, !jlir.Int64) -> !jlir.Random.MersenneTwister
# CHECK-NEXT:     %7 = "jlir.constant"() {value = #jlir<":idxF">} : () -> !jlir.Symbol
# CHECK-NEXT:     %8 = "jlir.getfield"(%6, %7) : (!jlir.Random.MersenneTwister, !jlir.Symbol) -> !jlir.Int64
# CHECK-NEXT:     %9 = "jlir.constant"() {value = #jlir<"1002">} : () -> !jlir.Int64
# CHECK-NEXT:     %10 = "jlir.==="(%8, %9) : (!jlir.Int64, !jlir.Int64) -> !jlir.Bool
# CHECK-NEXT:     "jlir.gotoifnot"(%10)[^bb3, ^bb2] {operand_segment_sizes = dense<[1, 0, 0]> : vector<3xi32>} : (!jlir.Bool) -> ()
# CHECK-NEXT:   ^bb2:  // pred: ^bb1
# CHECK-NEXT:     %11 = "jlir.constant"() {value = #jlir.Random.gen_rand} : () -> !jlir<"typeof(Random.gen_rand)">
# CHECK-NEXT:     %12 = "jlir.invoke"(%11, %6) {methodInstance = #jlir<"gen_rand(Random.MersenneTwister) from gen_rand(Random.MersenneTwister)">} : (!jlir<"typeof(Random.gen_rand)">, !jlir.Random.MersenneTwister) -> !jlir.Any
# CHECK-NEXT:     "jlir.goto"()[^bb3] : () -> ()
# CHECK-NEXT:   ^bb3:  // 2 preds: ^bb1, ^bb2
# CHECK-NEXT:     "jlir.goto"()[^bb4] : () -> ()
# CHECK-NEXT:   ^bb4:  // pred: ^bb3
# CHECK-NEXT:     %13 = "jlir.constant"() {value = #jlir<":vals">} : () -> !jlir.Symbol
# CHECK-NEXT:     %14 = "jlir.getfield"(%6, %13) : (!jlir.Random.MersenneTwister, !jlir.Symbol) -> !jlir<"Array{Float64, 1}">
# CHECK-NEXT:     %15 = "jlir.getfield"(%6, %7) : (!jlir.Random.MersenneTwister, !jlir.Symbol) -> !jlir.Int64
# CHECK-NEXT:     %16 = "jlir.add_int"(%15, %3) : (!jlir.Int64, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     %17 = "jlir.setfield!"(%6, %7, %16) : (!jlir.Random.MersenneTwister, !jlir.Symbol, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     %18 = "jlir.constant"() {value = #jlir.false} : () -> !jlir.Bool
# CHECK-NEXT:     %19 = "jlir.arrayref"(%18, %14, %16) : (!jlir.Bool, !jlir<"Array{Float64, 1}">, !jlir.Int64) -> !jlir.Float64
# CHECK-NEXT:     %20 = "jlir.constant"() {value = #jlir.UInt64} : () -> !jlir.DataType
# CHECK-NEXT:     %21 = "jlir.bitcast"(%20, %19) : (!jlir.DataType, !jlir.Float64) -> !jlir.UInt64
# CHECK-NEXT:     "jlir.goto"()[^bb5] : () -> ()
# CHECK-NEXT:   ^bb5:  // pred: ^bb4
# CHECK-NEXT:     "jlir.goto"()[^bb6] : () -> ()
# CHECK-NEXT:   ^bb6:  // pred: ^bb5
# CHECK-NEXT:     %22 = "jlir.constant"() {value = #jlir<"0x0000000000000001">} : () -> !jlir.UInt64
# CHECK-NEXT:     %23 = "jlir.and_int"(%21, %22) : (!jlir.UInt64, !jlir.UInt64) -> !jlir.UInt64
# CHECK-NEXT:     %24 = "jlir.constant"() {value = #jlir<"0">} : () -> !jlir.Int64
# CHECK-NEXT:     %25 = "jlir.sle_int"(%24, %24) : (!jlir.Int64, !jlir.Int64) -> !jlir.Bool
# CHECK-NEXT:     %26 = "jlir.bitcast"(%20, %24) : (!jlir.DataType, !jlir.Int64) -> !jlir.UInt64
# CHECK-NEXT:     %27 = "jlir.==="(%23, %26) : (!jlir.UInt64, !jlir.UInt64) -> !jlir.Bool
# CHECK-NEXT:     %28 = "jlir.and_int"(%25, %27) : (!jlir.Bool, !jlir.Bool) -> !jlir.Bool
# CHECK-NEXT:     %29 = "jlir.not_int"(%28) : (!jlir.Bool) -> !jlir.Bool
# CHECK-NEXT:     "jlir.goto"()[^bb7] : () -> ()
# CHECK-NEXT:   ^bb7:  // pred: ^bb6
# CHECK-NEXT:     "jlir.goto"()[^bb8] : () -> ()
# CHECK-NEXT:   ^bb8:  // pred: ^bb7
# CHECK-NEXT:     "jlir.goto"()[^bb9] : () -> ()
# CHECK-NEXT:   ^bb9:  // pred: ^bb8
# CHECK-NEXT:     "jlir.gotoifnot"(%29)[^bb11, ^bb10] {operand_segment_sizes = dense<[1, 0, 0]> : vector<3xi32>} : (!jlir.Bool) -> ()
# CHECK-NEXT:   ^bb10:  // pred: ^bb9
# CHECK-NEXT:     %30 = "jlir.constant"() {value = #jlir<"Base.:(+)">} : () -> !jlir<"typeof(Base.:(+))">
# CHECK-NEXT:     %31 = "jlir.pi"(%30) : (!jlir<"typeof(Base.:(+))">) -> !jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">
# CHECK-NEXT:     "jlir.goto"(%31)[^bb12] : (!jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">) -> ()
# CHECK-NEXT:   ^bb11:  // pred: ^bb9
# CHECK-NEXT:     %32 = "jlir.constant"() {value = #jlir<"Base.:(-)">} : () -> !jlir<"typeof(Base.:(-))">
# CHECK-NEXT:     %33 = "jlir.pi"(%32) : (!jlir<"typeof(Base.:(-))">) -> !jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">
# CHECK-NEXT:     "jlir.goto"(%33)[^bb12] : (!jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">) -> ()
# CHECK-NEXT:   ^bb12(%34: !jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">):  // 2 preds: ^bb10, ^bb11
# CHECK-NEXT:     %35 = "jlir.constant"() {value = #jlir<"typeof(Base.:(+))">} : () -> !jlir.DataType
# CHECK-NEXT:     %36 = "jlir.isa"(%34, %35) : (!jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">, !jlir.DataType) -> !jlir.Bool
# CHECK-NEXT:     "jlir.gotoifnot"(%36)[^bb14, ^bb13] {operand_segment_sizes = dense<[1, 0, 0]> : vector<3xi32>} : (!jlir.Bool) -> ()
# CHECK-NEXT:   ^bb13:  // pred: ^bb12
# CHECK-NEXT:     %37 = "jlir.add_int"(%3, %3) : (!jlir.Int64, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     "jlir.goto"(%37)[^bb17] : (!jlir.Int64) -> ()
# CHECK-NEXT:   ^bb14:  // pred: ^bb12
# CHECK-NEXT:     %38 = "jlir.constant"() {value = #jlir<"typeof(Base.:(-))">} : () -> !jlir.DataType
# CHECK-NEXT:     %39 = "jlir.isa"(%34, %38) : (!jlir<"Union{typeof(Base.:(+)), typeof(Base.:(-))}">, !jlir.DataType) -> !jlir.Bool
# CHECK-NEXT:     "jlir.gotoifnot"(%39)[^bb16, ^bb15] {operand_segment_sizes = dense<[1, 0, 0]> : vector<3xi32>} : (!jlir.Bool) -> ()
# CHECK-NEXT:   ^bb15:  // pred: ^bb14
# CHECK-NEXT:     %40 = "jlir.sub_int"(%3, %3) : (!jlir.Int64, !jlir.Int64) -> !jlir.Int64
# CHECK-NEXT:     "jlir.goto"(%40)[^bb17] : (!jlir.Int64) -> ()
# CHECK-NEXT:   ^bb16:  // pred: ^bb14
# CHECK-NEXT:     %41 = "jlir.constant"() {value = #jlir<"ErrorException("fatal error in type inference (type bound)")">} : () -> !jlir.ErrorException
# CHECK-NEXT:     %42 = "jlir.throw"(%41) : (!jlir.ErrorException) -> !jlir<"Union{}">
# CHECK-NEXT:     %43 = "jlir.undef"() : () -> !jlir.Int64
# CHECK-NEXT:     "jlir.return"(%43) : (!jlir.Int64) -> ()
# CHECK-NEXT:   ^bb17(%44: !jlir.Int64):  // 2 preds: ^bb13, ^bb15
# CHECK-NEXT:     "jlir.return"(%44) : (!jlir.Int64) -> ()
# CHECK-NEXT:   }
# CHECK-NEXT: }

# CHECK: error: lowering to Standard dialect failed

# CHECK: error: lowering to LLVM dialect failed
# CHECK-NEXT: error: module verification failed

max_stars_repo_name: JuliaLabs/brutus

max_issues_repo_name: JuliaLabs/brutus

max_forks_repo_name: JuliaLabs/brutus


text:
using Documenter, DocumenterTools

push!(LOAD_PATH,"../src/")
using NumNN

makedocs(
    sitename = "NumNN.jl",
    authors = "Mohammad Hizzani",
    # doctest   = false,
    # clean     = true,
    # linkcheck = false,
    format = Documenter.HTML(
        prettyurls = get(ENV, "CI", nothing) == "true"
    ),
    modules = [NumNN],
    pages = Any[
        "Home" => "index.md",
        "Docstrings" => "docstrings.md",
        "Tutorials" => "tutorials.md"
    ],
)

# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
#=deploydocs(
    repo = "<repository url>"
)=#

deploydocs(
    repo = "github.com/MohHizzani/NumNN.jl.git",
    target = "build",
    # push_preview = true,
    branch = "gh-pages",
    devurl = "dev",
    versions = ["stable" => "v^", "v#.#.#", "dev" => "dev"],
    # make = nothing,
    # forcepush = true,
)

ext: jl


text:
# Autogenerated wrapper script for GEOS_jll for x86_64-w64-mingw32-cxx03
export libgeos, libgeos_cpp

JLLWrappers.@generate_wrapper_header("GEOS")
JLLWrappers.@declare_library_product(libgeos, "libgeos_c.dll")
JLLWrappers.@declare_library_product(libgeos_cpp, "libgeos.dll")
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_library_product(
        libgeos,
        "bin\\libgeos_c.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libgeos_cpp,
        "bin\\libgeos.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
const ROOT3OVER3 = 0.577350269189626
const FALLBACK_ROTATE3 = 2.0 / 3.0
const ROTATE3_ORTHOGONALIZER = UNSKEW_2D

const RSQUARED_3D = 3.0f0 / 4.0f0

export ImproveXY, ImproveXZ

struct ImproveXY <: NoiseType end
struct ImproveXZ <: NoiseType end

"""
3D OpenSimplex2S/SuperSimplex noise, with better visual isotropy in (X, Y).
Recommended for 3D terrain and time-varied animations.
The Z coordinate should always be the "different" coordinate in whatever your use case is.
If Y is vertical in world coordinates, call `noise(ImproveXZ, seed, x, z, Y)`.
If Z is vertical in world coordinates, call `noise(ImproveXZ, seed, x, y, Z)`.
For a time varied animation, call `noise(ImproveXY, seed, x, y, T)`.
"""
function noise(::Type{ImproveXY}, seed::Int64, x, y, z)
    # Re-orient the cubic lattices without skewing, so Z points up the main lattice diagonal,
    # and the planes formed by XY are moved far out of alignment with the cube faces.
    # Orthonormal rotation. Not a skew transform.
    xy = x + y
    s2 = xy * ROTATE3_ORTHOGONALIZER
    zz = z * ROOT3OVER3

    # Evaluate both lattices to form a BCC lattice.
    return _noise(seed, x + s2 + zz, y + s2 + zz, xy * -ROOT3OVER3 + zz)
end

"""
3D OpenSimplex2S/SuperSimplex noise, with better visual isotropy in (X, Z).
Recommended for 3D terrain and time-varied animations.
The Y coordinate should always be the "different" coordinate in whatever your use case is.
If Y is vertical in world coordinates, call `noise(ImproveXZ, seed, x, Y, z)`.
If Z is vertical in world coordinates, call `noise(ImproveXZ, seed, x, Z, y)`
or use `noise(ImproveXY, ...)`
For a time varied animation, call `noise(ImproveXZ, seed, x, T, y)`
or use `noise(ImproveXY, ...)`
"""
function noise(::Type{ImproveXZ}, seed::Int64, x, y, z)
    # Re-orient the cubic lattices without skewing, so Y points up the main lattice diagonal,
    # and the planes formed by XZ are moved far out of alignment with the cube faces.
    # Orthonormal rotation. Not a skew transform.
    xz = x + z
    s2 = xz * -0.211324865405187
    yy = y * ROOT3OVER3
    # Evaluate both lattices to form a BCC lattice.
    return _noise(seed, x + s2 + yy, xz * -ROOT3OVER3 + yy, z + s2 + yy)
end

"""
3D OpenSimplex2S/SuperSimplex noise, fallback rotation option
Use `noise(ImproveXY,...)` or `noise(ImproveXZ,...)` instead, wherever appropriate.
They have less diagonal bias. This function's best use is as a fallback.
"""
function noise(seed::Int64, x, y, z)
    # Re-orient the cubic lattices via rotation, to produce a familiar look.
    # Orthonormal rotation. Not a skew transform.
    r = FALLBACK_ROTATE3 * (x + y + z)
    # Evaluate both lattices to form a BCC lattice.
    return _noise(seed, r - x, r - y, r - z)
end

toint(x) = trunc(Int, -0.5f0 - x)

"""
Generate overlapping cubic lattices for 3D Re-oriented BCC noise.
Lookup table implementation inspired by DigitalShadow.
It was actually faster to narrow down the points in the loop itself,
than to build up the index with enough info to isolate 8 points.
"""
function _noise(seed::Int64, xr, yr, zr)
    # Get base points and offsets.
    xrb, yrb, zrb = fastFloor(xr), fastFloor(yr), fastFloor(zr)
    xi, yi, zi = Float32(xr - xrb), Float32(yr - yrb), Float32(zr - zrb)

    # Prime pre-multiplication for hash. Also flip seed for second lattice copy.
    xrbp, yrbp, zrbp = (xrb * PRIME_X)%Int64, (yrb * PRIME_Y)%Int64, (zrb * PRIME_Z)%Int64
    seed2 = xor(seed, -0x52D547B2E96ED629)

    # -1 if positive, 0 if negative.
    xNMask, yNMask, zNMask = toint(xi), toint(yi), toint(zi)

    # First vertex.
    x0, y0, z0 = xi + xNMask, yi + yNMask, zi + zNMask
    a0 = RSQUARED_3D - x0 * x0 - y0 * y0 - z0 * z0
    value = grad(a0, seed,
                 xrbp + (xNMask & PRIME_X), yrbp + (yNMask & PRIME_Y), zrbp + (zNMask & PRIME_Z),
                 x0, y0, z0)

    # Second vertex.
    x1, y1, z1 = xi - 0.5f0, yi - 0.5f0, zi - 0.5f0
    a1 = RSQUARED_3D - x1 * x1 - y1 * y1 - z1 * z1
    value += grad(a1, seed2, xrbp + PRIME_X, yrbp + PRIME_Y, zrbp + PRIME_Z, x1, y1, z1)

    # Shortcuts for building the remaining falloffs.
    # Derived by subtracting the polynomials with the offsets plugged in.
    xAFlipMask0 = ((xNMask | 1) << 1) * x1
    yAFlipMask0 = ((yNMask | 1) << 1) * y1
    zAFlipMask0 = ((zNMask | 1) << 1) * z1
    xAFlipMask1 = (-2 - (xNMask << 2)) * x1 - 1.0f0
    yAFlipMask1 = (-2 - (yNMask << 2)) * y1 - 1.0f0
    zAFlipMask1 = (-2 - (zNMask << 2)) * z1 - 1.0f0

    skip5 = false
    a = xAFlipMask0 + a0
    if a > 0
        value += grad(a, seed,
                      xrbp + (~xNMask & PRIME_X),
                      yrbp + (yNMask & PRIME_Y),
                      zrbp + (zNMask & PRIME_Z),
                      x0 - (xNMask | 1), y0, z0)
    else
        a = yAFlipMask0 + zAFlipMask0 + a0
        if a > 0
            value += grad(a, seed,
                          xrbp + (xNMask & PRIME_X),
                          yrbp + (~yNMask & PRIME_Y),
                          zrbp + (~zNMask & PRIME_Z),
                          x0, y0 - (yNMask | 1), z0 - (zNMask | 1))
        end

        a = xAFlipMask1 + a1
        if a > 0
            value += grad(a, seed2,
                          xrbp + (xNMask & (PRIME_X * 2)),
                          yrbp + PRIME_Y,
                          zrbp + PRIME_Z,
                          (xNMask | 1) + x1, y1, z1)
            skip5 = true
        end
    end

    skip9 = false
    a = yAFlipMask0 + a0
    if a > 0
        value += grad(a, seed,
                      xrbp + (xNMask & PRIME_X),
                      yrbp + (~yNMask & PRIME_Y),
                      zrbp + (zNMask & PRIME_Z),
                      x0, y0 - (yNMask | 1), z0)
    else
        a = xAFlipMask0 + zAFlipMask0 + a0
        if a > 0
            value += grad(a, seed,
                          xrbp + (~xNMask & PRIME_X),
                          yrbp + (yNMask & PRIME_Y),
                          zrbp + (~zNMask & PRIME_Z),
                          x0 - (xNMask | 1), y0, z0 - (zNMask | 1))
        end

        a = yAFlipMask1 + a1
        if a > 0
            value += grad(a, seed2,
                          xrbp + PRIME_X,
                          yrbp + (yNMask & (PRIME_Y << 1)),
                          zrbp + PRIME_Z,
                          x1, (yNMask | 1) + y1, z1)
            skip9 = true
        end
    end

    skipD = false
    a = zAFlipMask0 + a0
    if a > 0
        value += grad(a, seed,
                      xrbp + (xNMask & PRIME_X),
                      yrbp + (yNMask & PRIME_Y),
                      zrbp + (~zNMask & PRIME_Z),
                      x0, y0, z0 - (zNMask | 1))
    else
        a = xAFlipMask0 + yAFlipMask0 + a0
        if a > 0
            value += grad(a, seed,
                          xrbp + (~xNMask & PRIME_X),
                          yrbp + (~yNMask & PRIME_Y),
                          zrbp + (zNMask & PRIME_Z),
                          x0 - (xNMask | 1), y0 - (yNMask | 1), z0)
        end

        a = zAFlipMask1 + a1
        if a > 0
            value += grad(a, seed2,
                          xrbp + PRIME_X,
                          yrbp + PRIME_Y,
                          zrbp + (zNMask & (PRIME_Z << 1)),
                          x1, y1, (zNMask | 1) + z1)
            skipD = true
        end
    end

    if !skip5
        a = yAFlipMask1 + zAFlipMask1 + a1
        if a > 0
            value += grad(a, seed2,
                          xrbp + PRIME_X,
                          yrbp + (yNMask & (PRIME_Y << 1)),
                          zrbp + (zNMask & (PRIME_Z << 1)),
                          x1, (yNMask | 1) + y1, (zNMask | 1) + z1)
        end
    end

    if !skip9
        a = xAFlipMask1 + zAFlipMask1 + a1
        if a > 0
            value += grad(a, seed2,
                          xrbp + (xNMask & (PRIME_X * 2)),
                          yrbp + PRIME_Y,
                          zrbp + (zNMask & (PRIME_Z << 1)),
                          (xNMask | 1) + x1, y1, (zNMask | 1) + z1)
        end
    end

    if !skipD
        a = xAFlipMask1 + yAFlipMask1 + a1
        if a > 0
            value += grad(a, seed2,
                          xrbp + (xNMask & (PRIME_X << 1)),
                          yrbp + (yNMask & (PRIME_Y << 1)),
                          zrbp + PRIME_Z,
                          (xNMask | 1) + x1, (yNMask | 1) + y1, z1)
        end
    end

    return Float32(value)
end


text:
"""
    Commutative

Declare a reduction operator to be commutative in its arguments.
No check is performed to ascertain if the operator is indeed commutative.
"""
struct Commutative{F} <: Function
    f :: F
end

(c::Commutative)(x, y) = c.f(x, y)

"""
    BroadcastFunction(f)

Construct a binary function that evaluates `f.(x, y)` given the arguments `x` and `y`.

!!! note
    The function `BroadcastFunction(f)` is equivalent to `Base.BroadcastFunction(f)` on Julia versions
    1.6 and above.

# Examples
```jldoctest
julia> ParallelUtilities.BroadcastFunction(+)(ones(3), ones(3))
3-element $(Vector{Float64}):
 2.0
 2.0
 2.0
```
"""
struct BroadcastFunction{V, F} <: Function
    f :: F
end

BroadcastFunction{V}(f) where {V} = BroadcastFunction{V, typeof(f)}(f)
BroadcastFunction(f::Function) = BroadcastFunction{Nothing, typeof(f)}(f)

(o::BroadcastFunction{Nothing})(x, y) = o.f.(x, y)

(o::BroadcastFunction{1})(x, y) = broadcast!(o.f, x, x, y)
(o::BroadcastFunction{2})(x, y) = broadcast!(o.f, y, x, y)

"""
    broadcastinplace(f, ::Val{N}) where {N}

Construct a binary operator that evaluates `f.(x, y)` and overwrites the `N`th argument with the result.
For `N == 1` this evaluates `x .= f.(x, y)`, whereas for `N == 2` this evaluates `y .= f.(x, y)`.

# Examples

```jldoctest
julia> op = ParallelUtilities.broadcastinplace(+, Val(1));

julia> x = ones(3); y = ones(3);

julia> op(x, y)
3-element $(Vector{Float64}):
 2.0
 2.0
 2.0

julia> x # overwritten
3-element $(Vector{Float64}):
 2.0
 2.0
 2.0
```
"""
function broadcastinplace(f, v::Val{N}) where {N}
    BroadcastFunction{N}(f)
end

"""
    elementwisesum!(x, y)

Binary reduction operator that performs an elementwise product and stores the result inplace in `x`.
The value of `x` is overwritten in the process.

Functionally `elementwisesum!(x, y)` is equivalent to `x .= x .+ y`.

!!! note
    The operator is assumed to be commutative.
"""
const elementwisesum! = Commutative(broadcastinplace(+, Val(1)))

"""
    elementwiseproduct!(x, y)

Binary reduction operator that performs an elementwise product and stores the result inplace in `x`.
The value of `x` is overwritten in the process.

Functionally `elementwiseproduct!(x, y)` is equivalent to `x .= x .* y`.

!!! note
    The operator is assumed to be commutative.
"""
const elementwiseproduct! = Commutative(broadcastinplace(*, Val(1)))

"""
    elementwisemin!(x, y)

Binary reduction operator that performs an elementwise `min` and stores the result inplace in `x`.
The value of `x` is overwritten in the process.

Functionally `elementwisemin!(x, y)` is equivalent to `x .= min.(x, y)`.

!!! note
    The operator is assumed to be commutative.
"""
const elementwisemin! = Commutative(broadcastinplace(min, Val(1)))

"""
    elementwisemax!(x, y)

Binary reduction operator that performs an elementwise `max` and stores the result inplace in `x`.
The value of `x` is overwritten in the process.

Functionally `elementwisemax!(x, y)` is equivalent to `x .= max.(x, y)`.

!!! note
    The operator is assumed to be commutative.
"""
const elementwisemax! = Commutative(broadcastinplace(max, Val(1)))

"""
    BroadcastStack(f, dims)(x::AbstractArray, y::AbstractArray)

Construct a binary function that stacks its arguments along `dims`, with overlapping indices `I` being replaced by
`f(x[I], y[I])`. The arguments `x` and `y` must both be `n`-dimensional arrays that have identical axes along all dimensions
aside from those specified by `dims`. The axes of the result along each dimensions `d`
in `dims` would be `union(axes(x, d), axes(y, d))`.
Along the other dimensions the result has the same axes as `x` and `y`.

!!! note
    If the resulting axes along the concatenated dimensions are not 1-based, one might require an offset array package
    such as [`OffsetArrays.jl`](https://github.com/JuliaArrays/OffsetArrays.jl).

# Examples
```jldoctest
julia> A = ones(2)*2
2-element $(Vector{Float64}):
 2.0
 2.0

julia> B = ones(3)*3
3-element $(Vector{Float64}):
 3.0
 3.0
 3.0

julia> ParallelUtilities.BroadcastStack(min, 1)(A, B)
3-element $(Vector{Float64}):
 2.0
 2.0
 3.0

julia> A = ones(2,2)*2
2×2 $(Matrix{Float64}):
 2.0  2.0
 2.0  2.0

julia> B = ones(2,3)*3
2×3 $(Matrix{Float64}):
 3.0  3.0  3.0
 3.0  3.0  3.0

julia> ParallelUtilities.BroadcastStack(+, 2)(A, B)
2×3 $(Matrix{Float64}):
 5.0  5.0  3.0
 5.0  5.0  3.0
```
"""
struct BroadcastStack{F, D} <: Function
    f :: F
    dims :: D
end

(s::BroadcastStack)(x, y) = broadcaststack(x, y, s.f, s.dims)

function _union(axes_x_dim::AbstractUnitRange, axes_y_dim::AbstractUnitRange)
    axes_dim_min = min(minimum(axes_x_dim), minimum(axes_y_dim))
    axes_dim_max = max(maximum(axes_x_dim), maximum(axes_y_dim))
    axes_dim = axes_dim_min:axes_dim_max
end
_union(axes_x_dim::Base.OneTo, axes_y_dim::Base.OneTo) = axes_x_dim ∪ axes_y_dim

_maybeUnitRange(ax::AbstractUnitRange) = UnitRange(ax)
_maybeUnitRange(ax::Base.OneTo) = ax

function _subsetaxes(f, axes_x, axes_y, dims)
    ax = collect(_maybeUnitRange.(axes_x))
    for dim in dims
        ax[dim] = f(axes_x[dim], axes_y[dim])
    end
    ntuple(i -> ax[i], length(axes_x))
end

function broadcaststack(x::AbstractArray, y::AbstractArray, f, dims)
    ndims(x) == ndims(y) || throw(DimensionMismatch("arrays must have the same number of dimensions"))

    for dim in 1:ndims(x)
        if dim ∈ dims
            if dim > ndims(x)
                throw(ArgumentError("dim must lie in 1 <= dim <= ndims(x)"))
            end
        else
            axes(x, dim) == axes(y, dim) || throw(DimensionMismatch("non-concatenated axes must be identical"))
        end
    end

    axes_cat = _subsetaxes(_union, axes(x), axes(y), dims)

    xy_cat = similar(x, promote_type(eltype(x), eltype(y)), axes_cat)
    eltype(xy_cat) <: Number && fill!(xy_cat, zero(eltype(xy_cat)))

    common_ax = CartesianIndices(_subsetaxes(intersect, axes(x), axes(y), dims))

    for arr in (x, y)
        @inbounds for I in CartesianIndices(arr)
            I in  common_ax && continue
            xy_cat[I] = arr[I]
        end
    end

    @inbounds for I in common_ax
        xy_cat[I] = f(x[I], y[I])
    end

    xy_cat
end

"""
    Flip(f)

Flip the arguments of a binary function `f`, so that `Flip(f)(x, y) == f(y,x)`.

# Examples
```jldoctest flip
julia> flip1 = ParallelUtilities.Flip(vcat);

julia> flip1(2, 3)
2-element $(Vector{Int}):
 3
 2
```

Two flips pop the original function back:

```jldoctest flip
julia> flip2 = ParallelUtilities.Flip(flip1);

julia> flip2(2, 3)
2-element $(Vector{Int}):
 2
 3
```
"""
struct Flip{F} <: Function
    f :: F
end

(o::Flip)(x, y) = o.f(y, x)

Flip(o::Flip) = o.f

# Perserve the commutative tag
Flip(c::Commutative) = Commutative(Flip(c.f))
Flip(b::BroadcastFunction{1}) = BroadcastFunction{2}(Flip(b.f))
Flip(b::BroadcastFunction{2}) = BroadcastFunction{1}(Flip(b.f))


text:
module DiscriminantAnalysis

    import Base:
        LinAlg.BlasReal,
        show,
        AbstractArray,
        size,
        linearindexing,
        getindex,
        length,
        convert

    export
        lda,
        cda,
        qda,
        discriminants,
        classify

    include("common.jl")
    include("lda.jl")
    include("qda.jl")

end # module


text:
using Test
using BenchmarkInputDataGen
using DelimitedFiles
using LinearAlgebra
using RigidBodyDynamics
using ForwardDiff
using Random

using InteractiveUtils: subtypes
using Statistics: mean

function ranges(header::Vector{<:AbstractString})
    nq = count(x -> startswith(x, "q_"), header)
    nv = count(x -> startswith(x, "v_"), header)
    @assert length(header) == nq + 3 * nv
    start = 1
    qrange = start : (start += nq) - 1
    vrange = start : (start += nv) - 1
    v̇range = start : (start += nv) - 1
    τrange = start : (start += nv) - 1
    qrange, vrange, v̇range, τrange
end

@testset "write_csv_files" begin
    mktempdir() do csvdir
        num_samples = 3
        urdfdir = BenchmarkInputDataGen.URDF_DIR
        write_csv_files(urdfdir=urdfdir, csvdir=csvdir, num_samples=num_samples)

        for config in BenchmarkInputDataGen.URDF_CONFIGS
            mechanism = BenchmarkInputDataGen.create_mechanism(joinpath(urdfdir, config.basename), floating=config.floating)
            robotname, _ = splitext(config.basename)
            @test length(readdir(csvdir)) == length(subtypes(BenchmarkInputDataGen.CSVWriter))
            powers = Dict{String, Float64}()
            for libdir in readdir(csvdir)
                inputs_csv = joinpath(csvdir, libdir, "$(robotname)_inputs.csv")
                data, headerdata = open(inputs_csv, "r") do io
                    readdlm(io, ',', Float64, '\n'; header=true)
                end
                header = collect(String, vec(headerdata))

                @test size(data, 1) == num_samples
                @test length(header) > 0

                qrange, vrange, v̇range, τrange = ranges(header)

                @test all(x -> startswith(x, "q_"), header[qrange])
                @test all(x -> startswith(x, "v_"), header[vrange])
                @test all(x -> startswith(x, "vd_"), header[v̇range])
                @test all(x -> startswith(x, "tau_"), header[τrange])

                @test !any(isnan, data)
                for i = 1 : size(data, 1)
                    sampledata = data[i, :]
                    v = view(sampledata, vrange)
                    τ = view(sampledata, τrange)
                    powers[libdir] = v ⋅ τ
                end
            end
            @test all(x -> isapprox(x, mean(values(powers)); atol=1e-10), values(powers))
        end
    end
end

@testset "v / v̇: $(config.basename)" for config in BenchmarkInputDataGen.URDF_CONFIGS
    robotname, _ = splitext(config.basename)
    mechanism = BenchmarkInputDataGen.create_mechanism(joinpath(BenchmarkInputDataGen.URDF_DIR, config.basename), floating=config.floating)
    state = MechanismState(mechanism)
    Random.seed!(1)
    rand!(state)

    q = configuration(state)
    q̇ = configuration_derivative(state)
    v = velocity(state)
    v̇ = rand!(similar(velocity(state)))
    v̈ = zero(velocity(state))
    τ = rand!(similar(velocity(state)))
    τ̇ = zero(velocity(state))

    Tag = Nothing
    Dual = ForwardDiff.Dual{Tag, Float64, 1}
    q_dual = similar(configuration(state), Dual)
    v_dual = similar(velocity(state), Dual)
    v̇_dual = similar(velocity(state), Dual)
    τ_dual = similar(velocity(state), Dual)

    q_dual .= ForwardDiff.Dual.(q, q̇)
    v_dual .= ForwardDiff.Dual.(v, v̇)
    v̇_dual .= ForwardDiff.Dual.(v̇, v̈)
    τ_dual .= ForwardDiff.Dual.(τ, τ̇)
    sample = BenchmarkInputDataGen.Sample(q_dual, v_dual, v̇_dual, τ_dual)

    for Writer in subtypes(BenchmarkInputDataGen.CSVWriter)
        writer = Writer(mechanism, robotname)
        q_writer_dual, v_writer_dual, v̇_writer_dual, τ_writer_dual = BenchmarkInputDataGen.make_sample_data(writer, sample)
        v̇_writer_forwarddiff = ForwardDiff.extract_derivative(Tag, v_writer_dual)
        v̇_writer_direct = ForwardDiff.value.(v̇_writer_dual)
        @test v̇_writer_forwarddiff ≈ v̇_writer_direct
    end
end

max_stars_repo_name: CobbledSteel/rbd-benchmarks-riscv

max_issues_repo_name: CobbledSteel/rbd-benchmarks-riscv

max_forks_repo_name: CobbledSteel/rbd-benchmarks-riscv


text:
# ---
# title: 532. K-diff Pairs in an Array
# id: problem532
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Array, Two Pointers
# link: <https://leetcode.com/problems/k-diff-pairs-in-an-array/description/>
# hidden: true
# ---
#
# Given an array of integers `nums` and an integer `k`, return _the number of
# **unique** k-diff pairs in the array_.
#
# A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following
# are true:
#
#   * `0 <= i, j < nums.length`
#   * `i != j`
#   * `|nums[i] - nums[j]| == k`
#
# **Notice**  that `|val|` denotes the absolute value of `val`.
#
#
#
# **Example 1:**
#
#
#
#     Input: nums = [3,1,4,1,5], k = 2
#     Output: 2
#     Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
#     Although we have two 1s in the input, we should only return the number of **unique** pairs.
#
#
# **Example 2:**
#
#
#
#     Input: nums = [1,2,3,4,5], k = 1
#     Output: 4
#     Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
#
#
# **Example 3:**
#
#
#
#     Input: nums = [1,3,1,5,4], k = 0
#     Output: 1
#     Explanation: There is one 0-diff pair in the array, (1, 1).
#
#
# **Example 4:**
#
#
#
#     Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3
#     Output: 2
#
#
# **Example 5:**
#
#
#
#     Input: nums = [-1,-2,-3], k = 1
#     Output: 2
#
#
#
#
# **Constraints:**
#
#   * `1 <= nums.length <= 104`
#   * `-107 <= nums[i] <= 107`
#   * `0 <= k <= 107`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
function unet3D(in_chs, lbl_chs)
    # Contracting layers
    l1 = Chain(conv1(in_chs, 4))
    l2 = Chain(l1, conv1(4, 4), conv2(4, 16))
    l3 = Chain(l2, conv1(16, 16), conv2(16, 32))
    l4 = Chain(l3, conv1(32, 32), conv2(32, 64))
    l5 = Chain(l4, conv1(64, 64), conv2(64, 128))

    # Expanding layers
    l6 = Chain(l5, tran2(128, 64), conv1(64, 64))
    l7 = Chain(Parallel(+, l6, l4), tran2(64, 32), conv1(32, 32))       # Residual connection between l6 & l4
    l8 = Chain(Parallel(+, l7, l3), tran2(32, 16), conv1(16, 16))       # Residual connection between l7 & l3
    l9 = Chain(Parallel(+, l8, l2), tran2(16, 4), conv1(4, 4))          # Residual connection between l8 & l2
    l10 = Chain(l9, conv1(4, lbl_chs))
end


text:
module ParSpMatVec

const spmatveclib  = abspath(joinpath(splitdir(Base.source_path())[1],"..","deps","builds","ParSpMatVec"))

include("A_mul_B.jl")
include("Ac_mul_B.jl")

end  # module ParSpMatVec


text:
function find_number_of_assemblies(adapters)
    adapters = Set(adapters)
    push!(adapters, 0)
    device = maximum(adapters) + 3
    push!(adapters, device)

    assemblies = zeros(Int64, device + 1)
    assemblies[1] = 1
    assemblies[2] = 1 in adapters ? 1 : 0
    t = 0
    if 2 in adapters
        t += assemblies[1]
    end
    if 1 in adapters
        t += assemblies[2]
    end
    assemblies[3] = t

    for n in 3:device
        foreach(k -> begin
                        if n - k in adapters
                            assemblies[n + 1] += assemblies[n - k + 1]
                        end
                    end, 1:3)
    end
    assemblies[device + 1]
end

function main()
    adapters = map(x -> parse(Int64, x), readlines("../resources/input_10.txt"))
    result = find_number_of_assemblies(adapters)
    println(result)
end

main()


text:
@testset "MVector" begin
    @testset "Inner Constructors" begin
        @test MVector{1,Int}((1,)).data === (1,)
        @test MVector{1,Float64}((1,)).data === (1.0,)
        @test MVector{2,Float64}((1,1.0)).data === (1.0,1.0)
        @test isa(MVector{1,Int}(), MVector{1,Int})

        @test_throws Exception MVector{2,Int}((1,))
        @test_throws Exception MVector{1,Int}(())
        @test_throws Exception MVector{Int,1}((1,))
    end

    @testset "Outer constructors and macro" begin
        @test MVector{1}((1,)).data === (1,)
        @test MVector{1}((1.0,)).data === (1.0,)
        @test MVector((1,)).data === (1,)
        @test MVector((1.0,)).data === (1.0,)

        @test ((@MVector [1.0])::MVector{1}).data === (1.0,)
        @test ((@MVector [1, 2, 3])::MVector{3}).data === (1, 2, 3)
        @test ((@MVector Float64[1,2,3])::MVector{3}).data === (1.0, 2.0, 3.0)
        @test ((@MVector [i for i = 1:3])::MVector{3}).data === (1, 2, 3)
        @test ((@MVector Float64[i for i = 1:3])::MVector{3}).data === (1.0, 2.0, 3.0)

        @test ((@MVector zeros(2))::MVector{2, Float64}).data === (0.0, 0.0)
        @test ((@MVector ones(2))::MVector{2, Float64}).data === (1.0, 1.0)
        @test isa(@MVector(rand(2)), MVector{2, Float64})
        @test isa(@MVector(randn(2)), MVector{2, Float64})

        @test ((@MVector zeros(Float32, 2))::MVector{2,Float32}).data === (0.0f0, 0.0f0)
        @test ((@MVector ones(Float32, 2))::MVector{2,Float32}).data === (1.0f0, 1.0f0)
        @test isa(@MVector(rand(Float32, 2)), MVector{2, Float32})
        @test isa(@MVector(randn(Float32, 2)), MVector{2, Float32})
    end

    @testset "Methods" begin
        v = @MVector [11, 12, 13]

        @test isimmutable(v) == false

        @test v[1] === 11
        @test v[2] === 12
        @test v[3] === 13

        @test Tuple(v) === (11, 12, 13)

        @test size(v) === (3,)
        @test size(typeof(v)) === (3,)
        @test size(MVector{3}) === (3,)

        @test size(v, 1) === 3
        @test size(v, 2) === 1
        @test size(typeof(v), 1) === 3
        @test size(typeof(v), 2) === 1

        @test length(v) === 3
    end

    @testset "setindex!" begin
        v = @MVector [1,2,3]
        v[1] = 11
        v[2] = 12
        v[3] = 13
        @test v.data === (11, 12, 13)
    end
end


text:
# struct WiderFactor{S<:Unsigned, T<:Unsigned} <: AbstractFactor{T}
#     basefactor::AbstractFactor{S}
# end

# Base.length(factor::WiderFactor{S, T}) where {S<:Unsigned} where {T<:Unsigned} = length(factor.basefactor)

# getlevels(factor::WiderFactor{S, T}) where {S<:Unsigned} where {T<:Unsigned} = getlevels(factor.basefactor)

# getname(factor::WiderFactor{S, T}) where {S<:Unsigned} where {T<:Unsigned} = getname(factor.basefactor)

# function slice(factor::WiderFactor{S, T}, fromobs::Integer, toobs::Integer, slicelength::Integer) where {S<:Unsigned} where {T<:Unsigned}
#     slicelength = verifyslicelength(fromobs, toobs, slicelength)
#     if S == T
#         slice(factor.basefactor, fromobs, toobs, slicelength)
#     else
#         f = x -> convert(T, x)
#         mapslice(f, slice(factor.basefactor, fromobs, toobs, slicelength), slicelength, T)
#     end
# end

# function Base.convert(::Type{WiderFactor{S, T}}, x::AbstractFactor{S}) where {S<:Unsigned} where {T<:Unsigned}
#     WiderFactor{S, T}(x)
# end

# function Base.map(factor::WiderFactor, dataframe::AbstractDataFrame)
#     map(factor.basefactor, dataframe)
# end

# function isordinal(factor::WiderFactor)
#     isordinal(factor.basefactor)
# end

max_stars_repo_name: Statfactory/JuML

max_issues_repo_name: Statfactory/JuML

max_forks_repo_name: Statfactory/JuML


text:
function _info(
    model::Optimizer,
    c::MOI.ConstraintIndex{MOI.VectorAffineFunction{Float64},<:MOI.Indicator},
)
    if haskey(model.indicator_constraint_info, c.value)
        return model.indicator_constraint_info[c.value]
    end
    return throw(MOI.InvalidIndex(c))
end

function MOI.supports_constraint(
    ::Optimizer,
    ::Type{MOI.VectorAffineFunction{Float64}},
    ::Type{<:MOI.Indicator{A,S}},
) where {A,S<:_SUPPORTED_SCALAR_SETS}
    return true
end

function MOI.is_valid(
    model::Optimizer,
    c::MOI.ConstraintIndex{MOI.VectorAffineFunction{Float64},S},
) where {S<:MOI.Indicator}
    info = get(model.indicator_constraint_info, c.value, nothing)
    if info === nothing
        return false
    end
    return isa(info.set, S)
end

function MOI.get(
    model::Optimizer,
    ::MOI.ConstraintSet,
    c::MOI.ConstraintIndex{<:MOI.VectorAffineFunction,<:MOI.Indicator},
)
    MOI.throw_if_not_valid(model, c)
    return _info(model, c).set
end

function MOI.get(
    model::Optimizer,
    ::MOI.ConstraintFunction,
    c::MOI.ConstraintIndex{<:MOI.VectorAffineFunction,<:MOI.Indicator},
)
    MOI.throw_if_not_valid(model, c)
    _update_if_necessary(model)
    info = _info(model, c)
    binvarP, nvarsP = Ref{Cint}(), Ref{Cint}()
    ret = GRBgetgenconstrIndicator(
        model,
        Cint(info.row - 1),
        binvarP,
        C_NULL,
        nvarsP,
        C_NULL,
        C_NULL,
        C_NULL,
        C_NULL,
    )
    _check_ret(model, ret)
    vars = Vector{Cint}(undef, nvarsP[])
    vals = Vector{Cdouble}(undef, nvarsP[])
    rhsP = Ref{Cdouble}()
    ret = GRBgetgenconstrIndicator(
        model,
        Cint(info.row - 1),
        C_NULL,
        C_NULL,
        C_NULL,
        vars,
        vals,
        C_NULL,
        rhsP,
    )
    _check_ret(model, ret)
    terms = Vector{MOI.VectorAffineTerm{Float64}}(undef, nvarsP[] + 1)
    x = model.variable_info[CleverDicts.LinearIndex(binvarP[] + 1)].index
    terms[1] = MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, x))
    for i in 1:nvarsP[]
        x = model.variable_info[CleverDicts.LinearIndex(vars[i] + 1)].index
        terms[i+1] = MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(vals[i], x))
    end
    _, rhs = _sense_and_rhs(info.set.set)
    return MOI.VectorAffineFunction(terms, [0.0, rhs - rhsP[]])
end

function MOI.add_constraint(
    model::Optimizer,
    func::MOI.VectorAffineFunction{Float64},
    s::MOI.Indicator{A,S},
) where {A,S<:_SUPPORTED_SCALAR_SETS}
    if !iszero(func.constants[1])
        error(
            "Constant in output_index 1 should be 0. Got $(func.constants[1])",
        )
    end
    vars = Vector{Cint}(undef, length(func.terms) - 1)
    vals = Vector{Cdouble}(undef, length(func.terms) - 1)
    binvar = Cint(-1)
    i = 1
    for vector_term in func.terms
        row = vector_term.output_index
        term = vector_term.scalar_term
        if row == 1
            if binvar !== Cint(-1)
                error("There should be exactly one term in output_index 1")
            elseif !isapprox(term.coefficient, 1.0)
                error(
                    "Expected coefficient in front of indicator variable to " *
                    "be 1.0. Got $(term.coefficient).",
                )
            end
            binvar = Cint(column(model, term.variable) - 1)
        else
            @assert row == 2
            vars[i] = Cint(column(model, term.variable) - 1)
            vals[i] = term.coefficient
            i += 1
        end
    end
    sense, rhs = _sense_and_rhs(s.set)
    rhs -= func.constants[2]
    ret = GRBaddgenconstrIndicator(
        model,
        "",
        binvar,
        A == MOI.ACTIVATE_ON_ONE ? Cint(1) : Cint(0),
        length(vars),
        vars,
        vals,
        sense,
        rhs,
    )
    _check_ret(model, ret)
    model.last_constraint_index += 1
    info = _ConstraintInfo(length(model.indicator_constraint_info) + 1, s)
    model.indicator_constraint_info[model.last_constraint_index] = info
    _require_update(model)
    return MOI.ConstraintIndex{typeof(func),typeof(s)}(
        model.last_constraint_index,
    )
end

function MOI.get(
    model::Optimizer,
    ::MOI.ListOfConstraintIndices{<:MOI.VectorAffineFunction,S},
) where {S<:MOI.Indicator}
    indices = MOI.ConstraintIndex{MOI.VectorAffineFunction{Float64},S}[
        MOI.ConstraintIndex{MOI.VectorAffineFunction{Float64},S}(key) for
        (key, info) in model.indicator_constraint_info if isa(info.set, S)
    ]
    return sort!(indices, by = x -> x.value)
end

function MOI.get(
    model::Optimizer,
    ::MOI.NumberOfConstraints{MOI.VectorAffineFunction{Float64},S},
) where {S<:MOI.Indicator}
    return count(x -> isa(x.set, S), values(model.indicator_constraint_info))
end

function MOI.get(
    model::Optimizer,
    ::MOI.ConstraintName,
    c::MOI.ConstraintIndex{<:MOI.VectorAffineFunction,<:MOI.Indicator},
)
    MOI.throw_if_not_valid(model, c)
    return _info(model, c).name
end

function MOI.set(
    model::Optimizer,
    ::MOI.ConstraintName,
    c::MOI.ConstraintIndex{<:MOI.VectorAffineFunction,S},
    name::String,
) where {S<:MOI.Indicator}
    MOI.throw_if_not_valid(model, c)
    _update_if_necessary(model)
    info = _info(model, c)
    info.name = name
    if !isempty(name)
        row = Cint(_info(model, c).row - 1)
        ret = GRBsetstrattrelement(model, "GenConstrName", row, name)
        _check_ret(model, ret)
    end
    return
end

function MOI.delete(
    model::Optimizer,
    c::MOI.ConstraintIndex{<:MOI.VectorAffineFunction,<:MOI.Indicator},
)
    MOI.throw_if_not_valid(model, c)
    row = _info(model, c).row
    ind = Ref{Cint}(row - 1)
    ret = GRBdelgenconstrs(model, 1, ind)
    _check_ret(model, ret)
    delete!(model.indicator_constraint_info, c.value)
    for info in values(model.indicator_constraint_info)
        if info.row > row
            info.row -= 1
        end
    end
    _require_update(model)
    return
end


text:
# Load in `deps.jl`, complaining if it does not exist
const depsjl_path = joinpath(@__DIR__, "..", "deps", "deps.jl")
if !isfile(depsjl_path)
    println("Deps path: $depsjl_path")
    error("ITK not installed properly, run `] build ITK`, restart Julia and try again")
end

include(depsjl_path)


text:
"""
    j_func()

Lorem ipsum dolor sit amet.
"""
function j_func()
  "R"
end

"""
    j_func(cur_obj::AType)

Lorem ipsum dolor sit amet.
"""
function j_func(cur_obj::AType)
  "G"
end

"""
    j_func(cur_obj::MType)

Lorem ipsum dolor sit amet.
"""
function j_func(cur_obj::MType)
  "B"
end


text:
mutable struct DescriptorPool
    mVkDevice::vk.VkDevice
    mCreateInfo::DescriptorPoolCreateInfo

    mHandleRef::Ref{vk.VkDescriptorPool}

    function DescriptorPool(device::vk.VkDevice, info::DescriptorPoolCreateInfo)
        this = new()
        this.mVkDevice = device
        this.mCreateInfo = info
        this.mHandleRef = Ref{vk.VkDescriptorPool}()
        if vk.vkCreateDescriptorPool(this.mVkDevice, handleRef(this.mCreateInfo), C_NULL, this.mHandleRef) != vk.VK_SUCCESS
            error("Failed to create descriptor pool!")
        end
        return this
    end
end
@class DescriptorPool

function destroy(this::DescriptorPool)
    vk.vkDestroyDescriptorPool(this.mVkDevice, this.mHandleRef[], C_NULL)
end

function handleRef(this::DescriptorPool)::Ref{vk.VkDescriptorPool}
    return this.mHandleRef
end


text:
#=
Plot the dividend process and the state process for the Markov asset pricing
lecture.

=#

using QuantEcon
using Plots
using LaTeXStrings

pyplot()

n = 25
mc = tauchen(n, 0.96, 0.25)
sim_length = 80

x_series = simulate(mc, sim_length; init=round(Int, n / 2))
lambda_series = exp(x_series)
d_series = cumprod(lambda_series) # assumes d_0 = 1

series = [x_series lambda_series d_series log(d_series)]
labels = [L"$X_t$" L"$g_t$" L"$d_t$" L"$log (d_t)$"]
plot(series, layout=4, labels=labels)

max_stars_repo_name: mwhchen/quantecon

max_issues_repo_name: mwhchen/quantecon

max_forks_repo_name: mwhchen/quantecon


text:
# ## Line plot 2d (2)

#md # ![FILE_NAME.png](images/FILE_NAME.png)

using Random
Random.seed!(2018)

time = 30
warlker1 = cumsum(randn(time))
warlker2 = cumsum(randn(time))
warlker3 = cumsum(randn(time))
warlker4 = cumsum(randn(time))
warlker5 = cumsum(randn(time))

plot(1:time, [warlker1 warlker2 warlker3 warlker4 warlker5],
    xlabel="time",
    ylabel="position",
    label=["walker1" "walker2" "walker3" "walker4" "walker5"],
    leg=:bottomleft)


text:
homogeneous(i::AbstractArray{T,N}) where {T<:Union{Colorant,Real}, N} = -(extrema(i)...) == 0

@testset "Region Splitting" begin

  # 2-d image
  img = fill(1, (8,8))
  img[1:4,1:4] .= 2

  t = region_tree(img, homogeneous)

  @test t[1,1].data == ((2,16))
  @test t[1,2].data == ((1,16))
  @test t[2,1].data == ((1,16))
  @test t[2,2].data == ((1,16))
  @test all(isleaf, [t[1,1], t[1,2], t[2,1], t[2,2]])

  seg = region_splitting(img, homogeneous)

  expected = fill(1,(8,8))
  expected[5:8,1:4] .= 2
  expected[1:4,5:8] .= 3
  expected[5:8,5:8] .= 4
  expected_labels = [1,2,3,4]
  expected_means = Dict(1=>2, 2=>1, 3=>1, 4=>1)
  expected_count = Dict(1=>16, 2=>16, 3=>16, 4=>16)

  @test all(label->(label in expected_labels), seg.segment_labels)
  @test all(label->(label in seg.segment_labels), expected_labels)
  @test expected_count == seg.segment_pixel_count
  @test all(label->(expected_means[label] ≈ seg.segment_means[label]), seg.segment_labels)
  @test seg.image_indexmap == expected

  # 3-d image
  img = fill(1, (4,4,4))
  img[3:4,3:4,3:4] .= 2

  seg = region_splitting(img, homogeneous)

  expected = fill(1,(4,4,4))
  expected[3:4,1:2,1:2] .= 2
  expected[1:2,3:4,1:2] .= 3
  expected[3:4,3:4,1:2] .= 4
  expected[1:2,1:2,3:4] .= 5
  expected[3:4,1:2,3:4] .= 6
  expected[1:2,3:4,3:4] .= 7
  expected[3:4,3:4,3:4] .= 8
  expected_labels = [1,2,3,4,5,6,7,8]
  expected_means = Dict(ntuple(i->(i=>1),7)..., 8=>2)
  expected_count = Dict(ntuple(i->(i=>8), 8)...)

  @test all(label->(label in expected_labels), seg.segment_labels)
  @test all(label->(label in seg.segment_labels), expected_labels)
  @test expected_count == seg.segment_pixel_count
  @test all(label->(expected_means[label] ≈ seg.segment_means[label]), seg.segment_labels)
  @test seg.image_indexmap == expected

end