text:
precompile(Tuple{getfield(Base, Symbol("#kw##printstyled")), NamedTuple{(:bold, :color), Tuple{Bool, Symbol}}, typeof(Base.printstyled), Base.TTY,String})
precompile(Tuple{typeof(Base.start), Tuple{Pkg3.Types.PackageSpec, Bool, String}})
precompile(Tuple{typeof(Base.values), Base.Dict{String, String}})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Base.UUID, Base.Dict{K, V} where V where K}, Base.Dict{String, Any}, Base.UUID})
precompile(Tuple{typeof(Base.collect), Base.Generator{Base.ValueIterator{Base.Dict{String, String}}, Type{Base.UUID}}})
precompile(Tuple{typeof(Base.mapfoldl), typeof(Base.identity), typeof(Base.union!), Base.Set{Base.UUID}, Tuple{Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.Fixed}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}}})
precompile(Tuple{Type{NamedTuple{(:path,), Tuple{String}}}, Tuple{String}})
precompile(Tuple{typeof(Base.getindex), Type{Any}, Type{Nothing}, Type{String}})
precompile(Tuple{typeof(Base.map), Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, Any}}})
precompile(Tuple{typeof(Base.merge_types), Tuple{Symbol, Symbol, Symbol, Symbol}, Type{NamedTuple{(:bare, :checkout_branch, :remote_cb), Tuple{Int32, Base.Cstring, Ptr{Nothing}}}}, Type{NamedTuple{(:fetch_opts,), Tuple{LibGit2.FetchOptionsStruct}}}})
precompile(Tuple{typeof(Base.isempty), Base.Dict{String, Base.UUID}})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.GraphData, Symbol, Array{Array{Base.VersionNumber, 1}, 1}})
precompile(Tuple{typeof(Base.get!), Base.Dict{Base.UUID, Array{String, 1}}, Base.UUID, Array{String, 1}})
precompile(Tuple{typeof(Base.push!), Array{Union{Pkg3.Types.VersionRange, String, Pkg3.REPLMode.Command, Pkg3.REPLMode.Option}, 1}, String})
precompile(Tuple{typeof(Base.collect_to_with_first!), Array{Base.UUID, 1}, Base.UUID, Base.Generator{Base.ValueIterator{Base.Dict{String, Any}}, Type{Base.UUID}}, Int64})
precompile(Tuple{Type{Pkg3.Types.PackageSpec}, Base.SubString{String}, Pkg3.Types.VersionSpec})
precompile(Tuple{typeof(Base.show_method_candidates), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, MethodError, Tuple{}})
precompile(Tuple{Type{Pkg3.Display.VerInfo}, Nothing, String, Base.VersionNumber, Bool})
precompile(Tuple{typeof(Base.collect), Base.Generator{Base.ValueIterator{Base.Dict{Any, Any}}, Type{Base.UUID}}})
precompile(Tuple{Type{Pkg3.Pkg2.Reqs.Comment}, String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{Base.VersionNumber, Base.SHA1}, Base.SHA1, Base.VersionNumber})
precompile(Tuple{typeof(Base.map), Type{Base.UUID}, Base.ValueIterator{Base.Dict{Any, Any}}})
precompile(Tuple{Type{NamedTuple{(:bare, :checkout_branch, :fetch_opts, :remote_cb), Tuple{Int32, Base.Cstring, LibGit2.FetchOptions, Ptr{Nothing}}}}, Tuple{Int32, Base.Cstring, LibGit2.FetchOptions, Ptr{Nothing}}})
precompile(Tuple{Type{Expr}, Symbol, GlobalRef, String, Core.SSAValue, String, Core.SSAValue, String, Core.SlotNumber, String})
precompile(Tuple{typeof(Base.arg_gen), Base.SubString{String}, Base.SubString{String}})
precompile(Tuple{typeof(Base.start), Tuple{Nothing, String}})
precompile(Tuple{typeof(Base.next), Tuple{Base.BitArray{1}}, Int64})
precompile(Tuple{typeof(Base.length), Base.Dict{Base.UUID, Int64}})
precompile(Tuple{Type{Pkg3.Types.VersionBound}, Int64, Int64})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.Graph, Symbol, Array{Int64, 1}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.IOStream}, Tuple{}})
precompile(Tuple{typeof(Pkg3.TOML.insertpair), Pkg3.TOML.Parser{Base.IOStream}, Pkg3.TOML.Table, String, Array{String, 1}, Int64})
precompile(Tuple{typeof(Base.in), String, Array{String, 1}})
precompile(Tuple{typeof(Pkg3.TOML.SOME), Array{String, 1}})
precompile(Tuple{typeof(Base.start), Base.Pair{String, Any}})
precompile(Tuple{typeof(Base.union!), Base.Set{Base.UUID}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.Fixed}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}})
precompile(Tuple{typeof(Base.run), Base.Cmd, Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}})
precompile(Tuple{Type{Pkg3.REPLMode.Command}, Pkg3.REPLMode.CommandKind, Base.SubString{String}})
precompile(Tuple{typeof(Pkg3.Display.not_in_project), Base.Dict{String, Any}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, Type{Base.UUID}, Base.ValueIterator{Base.Dict{Any, Any}}})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.Graph, Symbol, Array{Array{Int64, 1}, 1}})
precompile(Tuple{typeof(Base.get!), Base.Dict{String, Any}, String, Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Base.values), Base.Dict{String, Any}})
precompile(Tuple{getfield(Base, Symbol("#kw##with_output_color")), NamedTuple{(:bold,), Tuple{Bool}}, typeof(Base.with_output_color), typeof(Base.print), Symbol, Base.IOStream, String})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, String}}})
precompile(Tuple{typeof(Pkg3.Display.print_diff), Base.TTY, Array{Pkg3.Display.DiffEntry, 1}})
precompile(Tuple{typeof(Pkg3.Operations.install_archive), Array{String, 1}, Base.VersionNumber, String})
precompile(Tuple{typeof(Base.start), Tuple{typeof(Base.getindex), Array{Any, 1}}})
precompile(Tuple{typeof(Base.collect), Base.Generator{Array{Any, 1}, typeof(Pkg3.TOML.table2dict)}})
precompile(Tuple{typeof(Base.isempty), Base.Dict{String, Any}})
precompile(Tuple{Type{NamedTuple{(:env,), Tuple{Pkg3.Types.EnvCache}}}, Tuple{Pkg3.Types.EnvCache}})
precompile(Tuple{typeof(Base.diff_names), Tuple{Symbol, Symbol}, Tuple{Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol}})
precompile(Tuple{getfield(Core, Symbol("#kw#Type")), NamedTuple{(:bare, :checkout_branch, :fetch_opts, :remote_cb), Tuple{Int32, Base.Cstring, LibGit2.FetchOptions, Ptr{Nothing}}}, Type{LibGit2.CloneOptions}})
precompile(Tuple{typeof(Base.getproperty), Pkg3.Pkg2.Pkg2Types.VersionSet, Symbol})
precompile(Tuple{typeof(Pkg3.API.rm), String})
precompile(Tuple{Type{NamedTuple{(:callbacks,), Tuple{LibGit2.RemoteCallbacks}}}, Tuple{LibGit2.RemoteCallbacks}})
precompile(Tuple{typeof(Base.show), Base.GenericIOBuffer{Array{UInt8, 1}}, TypeVar})
precompile(Tuple{getfield(LibGit2, Symbol("#kw##clone")), NamedTuple{(:branch,), Tuple{String}}, typeof(LibGit2.clone), String, String})
precompile(Tuple{typeof(Base.promote_eltype), Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.Fixed}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID,Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}})
precompile(Tuple{Type{Base.Pair{A, B} where B where A}, Base.UUID, Pkg3.Types.VersionSpec})
precompile(Tuple{typeof(Base.haskey), Base.Dict{String, Pkg3.Types.VersionSpec}, String})
precompile(Tuple{typeof(Base.start), Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.IOStream}, Type{Union{}}})
precompile(Tuple{typeof(Base.next), Base.Channel{Any}, Base.ChannelIterState{Any}})
precompile(Tuple{typeof(Base.merge_names), Tuple{Symbol, Symbol, Symbol}, Tuple{Symbol}})
precompile(Tuple{typeof(Base.getindex), Base.Dict{Any, Any}, Char})
precompile(Tuple{typeof(Base.next), Array{Base.Dict{String, Any}, 1}, Int64})
precompile(Tuple{Type{Base.Pair{A, B} where B where A}, Symbol, TypeVar})
precompile(Tuple{Type{Pkg3.Types.PackageSpec}, Base.SubString{String}})
precompile(Tuple{typeof(Base.diff_names), Tuple{Symbol, Symbol, Symbol}, Tuple{Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, Type{Base.LinRange{T} where T}})
precompile(Tuple{typeof(Base.promote_eltype), Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.Fixed}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID,Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}})
precompile(Tuple{getfield(Core, Symbol("#kw#Type")), NamedTuple{(:prompt_prefix, :prompt_suffix, :sticky), Tuple{String, String, Bool}}, Type{REPL.LineEdit.Prompt}, String})
precompile(Tuple{getfield(Pkg3.TOML, Symbol("#kw##_print")), NamedTuple{(:sorted,), Tuple{Bool}}, typeof(Pkg3.TOML._print), Base.IOStream, Base.Dict{String, Any}, Array{String, 1}})
precompile(Tuple{getfield(Base, Symbol("#kw##printstyled")), NamedTuple{(:bold, :color), Tuple{Bool, Symbol}}, typeof(Base.printstyled), Base.IOStream, String})
precompile(Tuple{typeof(Base.deepcopy), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.diff_names), Tuple{Symbol, Symbol, Symbol, Symbol}, Tuple{Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol}})
precompile(Tuple{typeof(Base.length), Array{Base.Dict{Base.VersionNumber, Int64}, 1}})
precompile(Tuple{typeof(Base.show_tuple_as_call), Base.IOContext{Base.IOStream}, Symbol, Type{Tuple{typeof(Pkg3.Operations.build_versions), Pkg3.Types.Context, Array{Base.UUID, 1}}}})
precompile(Tuple{typeof(Base.empty), Base.Dict{Union{}, Union{}}, Type{String}, Type{Base.UUID}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, Type{Union{}}})
precompile(Tuple{Type{Expr}, Symbol, GlobalRef, QuoteNode, QuoteNode, QuoteNode, QuoteNode, QuoteNode, QuoteNode, QuoteNode})
precompile(Tuple{typeof(Base.isempty), Base.Dict{Base.UUID, Int64}})
precompile(Tuple{typeof(Pkg3.TOML.insertpair), Pkg3.TOML.Parser{Base.IOStream}, Pkg3.TOML.Table, String, String, Int64})
precompile(Tuple{typeof(Base.length), Base.Dict{String, String}})
precompile(Tuple{typeof(Base.diff_names), Tuple{Symbol}, Tuple{Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol}})
precompile(Tuple{typeof(Base.collect), Type{Any}, Base.Generator{Tuple{Nothing, String}, typeof(Core.Typeof)}})
precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{Pkg3.Types.PackageSpec, Bool, String}})
precompile(Tuple{typeof(Base.getindex), Base.BitArray{2}, Base.BitArray{1}, Base.BitArray{1}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, Core.TypeName})
precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{UndefVarError, Array{Union{Ptr{Nothing}, Base.InterpreterIP}, 1}}})
precompile(Tuple{typeof(Base.union), Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.Fixed}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}})
precompile(Tuple{typeof(Base.length), Array{Array{Base.VersionNumber, 1}, 1}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, Type{Union{Base.Slice{T} where T<:(Base.AbstractUnitRange{T} where T), Base.UnitRange{T} where T<:Real}}})
precompile(Tuple{typeof(Base.in), String, Base.KeySet{String, Base.Dict{String, Any}}})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.GraphData, Symbol, Base.Dict{Base.UUID, Int64}})
precompile(Tuple{typeof(Base.ident_cmp), Tuple{String}, Tuple{}})
precompile(Tuple{typeof(Base.deepcopy_internal), Base.Dict{String, String}, Base.IdDict{Any, Any}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, typeof(Core.Typeof), Tuple{Nothing, String}})
precompile(Tuple{typeof(Base.map), Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, String}}})
precompile(Tuple{typeof(Base.empty), Base.Dict{Union{}, Union{}}, Type{String}, Type{String}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, Bool})
precompile(Tuple{typeof(Pkg3.Display.name_ver_info), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.empty), Base.Dict{Union{}, Union{}}, Type{Base.UUID}, Type{Int64}})
precompile(Tuple{typeof(Base.getindex), Type{Pkg3.Types.VersionRange}, Pkg3.Pkg2.Pkg2Types.VersionInterval})
precompile(Tuple{typeof(Base.start), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.GraphData, Symbol, Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.promote_eltype), Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}})
precompile(Tuple{typeof(Base.done), Base.Channel{Any}, Base.ChannelIterState{Any}})
precompile(Tuple{getfield(Base, Symbol("#kw##printstyled")), NamedTuple{(:color,), Tuple{Symbol}}, typeof(Base.printstyled), Base.IOContext{Base.IOStream}, String})
precompile(Tuple{typeof(Pkg3.Display.in_project), Base.Dict{String, Any}})
precompile(Tuple{typeof(REPL.LineEdit.setup_search_keymap), REPL.REPLHistoryProvider})
precompile(Tuple{typeof(Base.foldl), typeof(Base.union!), Base.Set{Base.UUID}, Tuple{Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.Fixed}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}}})
precompile(Tuple{typeof(Base._array_for), Type{Base.BitArray{2}}, Base.UnitRange{Int64}, Base.HasShape{1}})
precompile(Tuple{typeof(Base.close), LibGit2.GitRepo})
precompile(Tuple{typeof(Base.promote_eltype), Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}})
precompile(Tuple{typeof(REPL.LineEdit.setup_prefix_keymap), REPL.REPLHistoryProvider, REPL.LineEdit.Prompt})
precompile(Tuple{typeof(Base.collect_to_with_first!), Array{Base.UUID, 1}, Base.UUID, Base.Generator{Base.ValueIterator{Base.Dict{Any, Any}}, Type{Base.UUID}}, Int64})
precompile(Tuple{typeof(Base.mapfoldl_impl), typeof(Base.identity), typeof(Base.union!), Base.Set{Base.UUID}, Tuple{Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.Fixed}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID,Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}, Base.KeySet{Base.UUID, Base.Dict{Base.UUID, Pkg3.Types.VersionSpec}}}, Int64})
precompile(Tuple{typeof(Base.indexed_next), Tuple{typeof(Base.getindex), Array{Any, 1}}, Int64, Int64})
precompile(Tuple{typeof(Base.keys), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base._array_for), Type{Base.UUID}, Base.ValueIterator{Base.Dict{Any, Any}}, Base.HasLength})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Array{Any, 1}, String})
precompile(Tuple{typeof(Base._compute_eltype), Type{Tuple{Int32, Base.Cstring, Ptr{Nothing}}}})
precompile(Tuple{typeof(Base.hash), Tuple{String, UInt64}, UInt64})
precompile(Tuple{Type{Base.IOContext{IO_t} where IO_t<:IO}, Base.IOStream, Base.Pair{Symbol, Bool}})
precompile(Tuple{typeof(Pkg3.API.build)})
precompile(Tuple{typeof(Base.merge_names), Tuple{Symbol}, Tuple{Symbol}})
precompile(Tuple{getfield(Pkg3.API, Symbol("#kw##checkout")), NamedTuple{(:path,), Tuple{String}}, typeof(Pkg3.API.checkout), Pkg3.Types.Context, Array{Tuple{Pkg3.Types.PackageSpec, Union{Nothing, String}}, 1}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.IOStream}, Type{Union{Nothing, String}}})
precompile(Tuple{typeof(Base.getindex), Array{Array{UInt64, 1}, 1}, Int64})
precompile(Tuple{typeof(Base.merge!), Base.Dict{String, Base.UUID}, Base.Dict{Union{}, Union{}}})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.ResolveLog, Symbol, Base.Dict{Base.UUID, Pkg3.GraphType.ResolveLogEntry}})
precompile(Tuple{typeof(Base.show), Base.GenericIOBuffer{Array{UInt8, 1}}, Type{Base.Pair{A, B} where B where A}})
precompile(Tuple{typeof(Base.print), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, String, Type{getfield(Pkg3.API, Symbol("#kw##checkout"))}, String})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.GraphData, Symbol, Array{Int64, 1}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.IOStream}, Type{Pkg3.Types.Context}})
precompile(Tuple{typeof(Base.merge!), Base.Dict{String, String}, Base.Dict{Union{}, Union{}}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, Tuple{}})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Array{Base.Dict{String, Any}, 1}, String})
precompile(Tuple{typeof(Base.getindex), Base.Dict{String, Pkg3.REPLMode.CommandKind}, Base.SubString{String}})
precompile(Tuple{getfield(Pkg3.TOML, Symbol("#kw##print")), NamedTuple{(:sorted,), Tuple{Bool}}, typeof(Pkg3.TOML.print), Base.IOStream, Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{Pkg3.Types.PackageSpec, String}})
precompile(Tuple{typeof(Base.length), Array{Array{Base.BitArray{2}, 1}, 1}})
precompile(Tuple{typeof(Base.identity), Char})
precompile(Tuple{typeof(Base.promote_typejoin), Type{Int32}, Type{Base.Cstring}})
precompile(Tuple{typeof(Base.length), Array{Array{Int64, 1}, 1}})
precompile(Tuple{typeof(Base.indexed_next), Tuple{Pkg3.Types.PackageSpec, Bool, String}, Int64, Int64})
precompile(Tuple{typeof(Base.values), Base.Dict{Any, Any}})
precompile(Tuple{getfield(Base, Symbol("#kw##sort!")), NamedTuple{(:by,), Tuple{typeof(Base.Unicode.lowercase)}}, typeof(Base.sort!), Array{String, 1}})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.Graph, Symbol, Array{Array{Base.BitArray{2}, 1}, 1}})
precompile(Tuple{typeof(Base.typesof), Nothing, String})
precompile(Tuple{Type{Pkg3.Types.PackageSpec}, String, Base.UUID})
precompile(Tuple{typeof(Base.spawn_opts_inherit), Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}})
precompile(Tuple{typeof(Pkg3.REPLMode.create_mode), REPL.LineEditREPL, REPL.LineEdit.Prompt})
precompile(Tuple{typeof(Base.unescape_string), Base.SubString{String}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.IOStream}, Tuple{Symbol}})
precompile(Tuple{typeof(Base.start), Tuple{UndefVarError, Array{Union{Ptr{Nothing}, Base.InterpreterIP}, 1}}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, Any}}})
precompile(Tuple{typeof(Base.push!), Array{Pkg3.Pkg2.Reqs.Line, 1}, Pkg3.Pkg2.Reqs.Requirement})
precompile(Tuple{typeof(Base._array_for), Type{Base.UUID}, Base.ValueIterator{Base.Dict{String, Any}}, Base.HasLength})
precompile(Tuple{typeof(Base.start), Tuple{Pkg3.Types.PackageSpec, String}})
precompile(Tuple{getfield(Base, Symbol("#kw##show_trace_entry")), NamedTuple{(:prefix,), Tuple{String}}, typeof(Base.show_trace_entry), Base.IOContext{Base.IOStream}, Base.StackTraces.StackFrame, Int64})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Base.Dict{String, String}, String})
precompile(Tuple{getfield(Pkg3.TOML, Symbol("#kw##printvalue")), NamedTuple{(:sorted,), Tuple{Bool}}, typeof(Pkg3.TOML.printvalue), Base.IOStream,Array{String, 1}})
precompile(Tuple{typeof(Base.isempty), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Pkg3.Display.manifest_diff), Base.Dict{String, Any}, Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.length), Base.Dict{String, Any}})
precompile(Tuple{typeof(Base.promote_typejoin), Type{Union{}}, Type{Int32}})
precompile(Tuple{typeof(Base.push!), Array{Pkg3.Pkg2.Reqs.Line, 1}, Pkg3.Pkg2.Reqs.Comment})
precompile(Tuple{typeof(Base.start), Tuple{Base.BitArray{1}}})
precompile(Tuple{Type{Pkg3.Types.VersionSpec}, String})
precompile(Tuple{typeof(Base.print), Base.IOContext{Base.IOStream}, String, Type{Pkg3.Types.Context}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.IOStream}, Int64})
precompile(Tuple{typeof(Base.merge_types), Tuple{Symbol, Symbol}, Type{NamedTuple{(:credentials,), Tuple{Ptr{Nothing}}}}, Type{NamedTuple{(:payload,), Tuple{Ptr{Nothing}}}}})
precompile(Tuple{typeof(Base.collect), Base.KeySet{String, Base.Dict{String, Any}}})
precompile(Tuple{Type{NamedTuple{(:branch,), Tuple{String}}}, Tuple{String}})
precompile(Tuple{Type{NamedTuple{(:prompt_prefix, :prompt_suffix, :sticky), Tuple{String, String, Bool}}}, Tuple{String, String, Bool}})
precompile(Tuple{Pkg3.Display.InProject{Base.Dict{String, Any}}, String, Base.Dict{String, Any}})
precompile(Tuple{Type{Pkg3.Display.VerInfo}, Base.SHA1, Nothing, Base.VersionNumber, Bool})
precompile(Tuple{typeof(Base.join), Base.GenericIOBuffer{Array{UInt8, 1}}, Tuple{String}, Char})
precompile(Tuple{Type{Pkg3.Pkg2.Reqs.Requirement}, String})
precompile(Tuple{typeof(Base.ident_cmp), Tuple{}, Tuple{String}})
precompile(Tuple{typeof(Base.length), Array{Base.Dict{Int64, Int64}, 1}})
precompile(Tuple{getfield(Pkg3.TOML, Symbol("#kw##_print")), NamedTuple{(:sorted,), Tuple{Bool}}, typeof(Pkg3.TOML._print), Base.IOStream, Base.Dict{String, String}, Array{String, 1}})
precompile(Tuple{typeof(Base.show), Base.IOContext{Base.GenericIOBuffer{Array{UInt8, 1}}}, TypeVar})
precompile(Tuple{typeof(Base.cmd_gen), Tuple{Tuple{Base.Cmd}, Tuple{Base.SubString{String}}}})
precompile(Tuple{typeof(Base.show), Base.IOContext{REPL.Terminals.TTYTerminal}, Tuple{}})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{1}, Base.BitArray{1}})
precompile(Tuple{typeof(Base.get!), Base.Dict{String, Array{Base.UUID, 1}}, String, Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.show_datatype), Base.IOContext{Base.IOStream}, Type{Pkg3.Types.Context}})
precompile(Tuple{typeof(Base.delete!), Base.Set{Any}, Char})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{1}})
precompile(Tuple{typeof(Base.:(∉)), Base.UUID, Array{Base.UUID, 1}})
precompile(Tuple{typeof(Pkg3.API.add), String})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Base.UUID, String})
precompile(Tuple{typeof(Base.haskey), Base.Dict{String, Pkg3.REPLMode.CommandKind}, Base.SubString{String}})
precompile(Tuple{typeof(Base.display_error), Base.IOStream, MethodError, Array{Union{Ptr{Nothing}, Base.InterpreterIP}, 1}})
precompile(Tuple{typeof(REPL.eval), Module, Symbol})
precompile(Tuple{getfield(Pkg3.TOML, Symbol("#kw##printvalue")), NamedTuple{(:sorted,), Tuple{Bool}}, typeof(Pkg3.TOML.printvalue), Base.IOStream,String})
precompile(Tuple{typeof(Base.promote_typejoin), Type{Any}, Type{Ptr{Nothing}}})
precompile(Tuple{Type{Pkg3.Types.VersionBound}, Int64, Int64, Int64})
precompile(Tuple{getfield(Base, Symbol("#kw##with_output_color")), NamedTuple{(:bold,), Tuple{Bool}}, typeof(Base.with_output_color), typeof(Base.print), Symbol, Base.IOContext{Base.IOStream}, String})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{1}, Base.BitArray{1}, Base.BitArray{1}})
precompile(Tuple{Type{Base.SHA1}, String})
precompile(Tuple{typeof(Base.ident_cmp), Tuple{String}, Tuple{String}})
precompile(Tuple{typeof(Base.get!), Base.Dict{String, Array{String, 1}}, String, Array{String, 1}})
precompile(Tuple{getfield(Core, Symbol("#kw#Type")), NamedTuple{(:env,), Tuple{Pkg3.Types.EnvCache}}, Type{Pkg3.Types.Context}})
precompile(Tuple{typeof(Base.diff_names), Tuple{Symbol, Symbol, Symbol, Symbol}, Tuple{Symbol}})
precompile(Tuple{typeof(Base.show), Base.IOContext{REPL.Terminals.TTYTerminal}, Type{Union{}}})
precompile(Tuple{typeof(REPL.LineEdit.fixup_keymaps!), Base.Dict{Char, Any}, Int64, Char, Nothing})
precompile(Tuple{typeof(Base.push!), Base.Set{Any}, Char})
precompile(Tuple{typeof(Base.:(!=)), String, Bool})
precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Any}, Base.Dict{Any, Any}, String})
precompile(Tuple{typeof(Base.:(!=)), Base.SubString{String}, Nothing})
precompile(Tuple{Type{Pkg3.Types.PackageSpec}, String})
precompile(Tuple{typeof(Base.hash), Tuple{String}, UInt64})
precompile(Tuple{typeof(Base.print), Base.IOContext{Base.IOStream}, Type{Pkg3.Types.Context}})
precompile(Tuple{typeof(REPL.send_to_backend), Symbol, REPL.REPLBackendRef})
precompile(Tuple{typeof(Base.promote_type), Type{Base.UUID}, Type{Base.UUID}})
precompile(Tuple{Type{Pkg3.Types.VersionBound}, Base.SubString{String}})
precompile(Tuple{getfield(Core, Symbol("#kw#Type")), NamedTuple{(:callbacks,), Tuple{LibGit2.RemoteCallbacks}}, Type{LibGit2.FetchOptions}})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{2}, Base.BitArray{2}})
precompile(Tuple{typeof(Base.promote_typejoin), Type{Union{}}, Type{Base.UUID}})
precompile(Tuple{typeof(Base.done), Array{Base.Dict{String, Any}, 1}, Int64})
precompile(Tuple{typeof(Base.setproperty!), Pkg3.GraphType.GraphData, Symbol, Array{Base.Dict{Base.VersionNumber, Int64}, 1}})
precompile(Tuple{typeof(Base.indexed_next), Tuple{UndefVarError, Array{Union{Ptr{Nothing}, Base.InterpreterIP}, 1}}, Int64, Int64})
precompile(Tuple{typeof(Base.merge), Base.Dict{String, Any}, Base.Dict{String, Any}})
precompile(Tuple{Type{Base.Pair{A, B} where B where A}, Base.VersionNumber, Base.SHA1})
precompile(Tuple{typeof(Base.collect), Base.Generator{Base.ValueIterator{Base.Dict{String, Any}}, Type{Base.UUID}}})
precompile(Tuple{typeof(Base.start), Base.Pair{Any, Any}})
precompile(Tuple{typeof(Base.deepcopy_internal), Array{Base.Dict{String, Any}, 1}, Base.IdDict{Any, Any}})
precompile(Tuple{typeof(REPL.send_to_backend), Symbol, Base.Channel{Any}, Base.Channel{Any}})
precompile(Tuple{typeof(Base.merge), Base.Dict{String, Any}, Base.Dict{String, String}})
precompile(Tuple{typeof(Base.deepcopy_internal), Base.Dict{Any, Any}, Base.IdDict{Any, Any}})
precompile(Tuple{Type{Base.Pair{A, B} where B where A}, String, Base.UUID})
precompile(Tuple{typeof(Base.start), Base.Channel{Any}})
precompile(Tuple{Type{Base.Generator{I, F} where F where I}, typeof(Pkg3.TOML.table2dict), Array{Any, 1}})
precompile(Tuple{typeof(Base.Iterators.enumerate), Array{Base.UUID, 1}})
precompile(Tuple{typeof(Base.similar), Array{Base.Dict{String, Any}, 1}})
precompile(Tuple{typeof(Base.print), Base.GenericIOBuffer{Array{UInt8, 1}}, String, Base.UUID, String})
precompile(Tuple{typeof(Base.done), Tuple{Base.BitArray{1}}, Int64})
precompile(Tuple{typeof(Base.merge!), Base.Dict{Base.UUID, Int64}, Base.Dict{Union{}, Union{}}})
precompile(Tuple{typeof(Base.vcat), Base.BitArray{2}, Base.BitArray{2}, Base.BitArray{2}, Base.BitArray{2}})
precompile(Tuple{typeof(Pkg3.Display.filter_manifest), Pkg3.Display.InProject{Base.Dict{String, Any}}, Base.Dict{String, Any}})

@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_help!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}, REPL.LineEditREPL})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_status!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_add!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_rm!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_up!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_pin!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_free!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_checkout!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_test!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})
@assert precompile(Tuple{typeof(Pkg3.REPLMode.do_build!), Pkg3.Types.Context, Vector{Pkg3.REPLMode.Token}})

@assert precompile(Tuple{Type{Pkg3.GraphType.GraphData}, Dict{UUID,Set{VersionNumber}},
       Dict{UUID,Dict{VersionRange,Dict{String,UUID}}},
       Dict{UUID,Dict{VersionRange,Dict{String,VersionSpec}}},
       Dict{UUID,String}})

@assert precompile(Tuple{Type{Pkg3.GraphType.Graph},Dict{UUID,Set{VersionNumber}},
                                            Dict{UUID,Dict{VersionRange,Dict{String,UUID}}},
                                            Dict{UUID,Dict{VersionRange,Dict{String,VersionSpec}}},
                                            Dict{UUID,String},
                                            Requires,
                                            Dict{UUID,Pkg3.Types.Fixed},
                                            Bool})

@assert precompile(Tuple{typeof(Pkg3.Resolve.simplify_graph!), Pkg3.GraphType.Graph, Set{Int}})

max_stars_repo_name: blegat/julia

max_issues_repo_name: blegat/julia

max_forks_repo_name: blegat/julia


text:
"""
Unit tests for InputChannel type.

------------------------------------------------------------------------------
COPYRIGHT/LICENSE. This file is part of the XYZ package. It is subject to
the license terms in the LICENSE file found in the top-level directory of
this distribution. No part of the XYZ package, including this file, may be
copied, modified, propagated, or distributed except according to the terms
contained in the LICENSE file.
------------------------------------------------------------------------------
"""
# --- Imports

# Standard library
using Test

# External packages
using ZMQ

# Boid.jl package
using Boid

# --- Test fixtures

# Concrete subtype of AbstractChannelData
include("fixtures/TestChannelData.jl")

# Constants
input_url = construct_ipc_url(".", "input-channel-test.zmq")
input_ipc_path = input_url[7:end]

# --- Set up/tear down methods

function _tearDown()
    rm(input_ipc_path, force=true)
end

# --- Tests

@testset "InputChannel: constructor" begin
    # --- Tests

    input_channel = InputChannel(TestChannelData, input_url, use_bind=false)

    @test input_channel.data isa TestChannelData
    @test input_channel.url == input_url
    @test input_channel.socket isa Socket

    # --- Clean up

    _tearDown()
end

@testset "InputChannel: listen()" begin
    # --- Preparations

    # Create InputChannel
    input_channel = InputChannel(TestChannelData, input_url, use_bind=false)

    # Create ZMQ Socket to send data on
    socket = Socket(PUB)
    bind(socket, input_url)

    # Get initial value of input channel data
    initial_channel_value = get_value(input_channel)

    # --- Tests
#=
    # Start listnening for input data
    @async listen(input_channel)
    while !input_channel.state.is_listening
        sleep(0.1)
    end
    @test input_channel.state.is_listening

    # Send value
    data_sent = rand()
    while data_sent == initial_channel_value
        data_sent = rand()
    end
    send(socket, encode_value(TestChannelData, data_sent))

    while input_channel.state.is_listening
        sleep(0.1)
    end
    @test get_value(input_channel) == data_sent
    @test !input_channel.state.is_listening
=#
    # --- Clean up

    _tearDown()
end

ext: jl


text:
function ao_2e3c(BS::BasisSet, auxBS::BasisSet, T::DataType = Float64)

    ATM_SLOTS = 6
    BAS_SLOTS = 8

    natm = BS.natoms
    nbas = BS.nbas + auxBS.nbas
    nshells = BS.nshells + auxBS.nshells

    lc_atm = zeros(Cint, natm*ATM_SLOTS)
    lc_bas = zeros(Cint, nshells*BAS_SLOTS)
    env = zeros(Cdouble, length(BS.lc_env) + length(auxBS.lc_env) - 3*natm)

    # Prepare the lc_atom input
    off = 0
    ib = 0
    for i = eachindex(BS.molecule.atoms)
        A = BS.molecule.atoms[i]
        # lc_atom has ATM_SLOTS (6) "spaces" for each atom
        # The first one (Z_INDEX) is the atomic number
        lc_atm[1 + ATM_SLOTS*(i-1)] = Cint(A.Z)
        # The second one is the env index address for xyz
        lc_atm[2 + ATM_SLOTS*(i-1)] = off
        env[off+1:off+3] .= A.xyz ./ Fermi.PhysicalConstants.bohr_to_angstrom
        off += 3
        # The remaining 4 slots are zero.
    end

    for i = eachindex(BS.molecule.atoms)
        A = BS.molecule.atoms[i]
        # Prepare the lc_bas input
        for j = eachindex(BS.basis[A])
            B = BS.basis[A][j]
            Ne = length(B.exp)
            Nc = length(B.coef)
            # lc_bas has BAS_SLOTS for each basis set
            # The first one is the index of the atom starting from 0
            lc_bas[1 + BAS_SLOTS*ib] = i-1
            # The second one is the angular momentum
            lc_bas[2 + BAS_SLOTS*ib] = B.l
            # The third is the number of primitive functions
            lc_bas[3 + BAS_SLOTS*ib] = Nc
            # The fourth is the number of contracted functions
            lc_bas[4 + BAS_SLOTS*ib] = 1
            # The fifth is a κ parameter
            lc_bas[5 + BAS_SLOTS*ib] = 0
            # Sixth is the env index address for exponents
            lc_bas[6 + BAS_SLOTS*ib] = off
            env[off+1:off+Ne] .= B.exp
            off += Ne
            # Seventh is the env index address for contraction coeff
            lc_bas[7 + BAS_SLOTS*ib] = off
            env[off+1:off+Nc] .= B.coef
            off += Nc
            # Eigth, nothing
            ib += 1
        end
    end

    for i = eachindex(auxBS.molecule.atoms)
        A = auxBS.molecule.atoms[i]
        # Prepare the lc_bas input
        for j = eachindex(auxBS.basis[A])
            B = auxBS.basis[A][j]
            Ne = length(B.exp)
            Nc = length(B.coef)
            # lc_bas has BAS_SLOTS for each basis set
            # The first one is the index of the atom starting from 0
            lc_bas[1 + BAS_SLOTS*ib] = i-1
            # The second one is the angular momentum
            lc_bas[2 + BAS_SLOTS*ib] = B.l
            # The third is the number of primitive functions
            lc_bas[3 + BAS_SLOTS*ib] = Nc
            # The fourth is the number of contracted functions
            lc_bas[4 + BAS_SLOTS*ib] = 1
            # The fifth is a κ parameter
            lc_bas[5 + BAS_SLOTS*ib] = 0
            # Sixth is the env index address for exponents
            lc_bas[6 + BAS_SLOTS*ib] = off
            env[off+1:off+Ne] .= B.exp
            off += Ne
            # Seventh is the env index address for contraction coeff
            lc_bas[7 + BAS_SLOTS*ib] = off
            env[off+1:off+Nc] .= B.coef
            off += Nc
            # Eigth, nothing
            ib += 1
        end
    end

    # Allocate output array
    #N = (BS.nbas^2 + BS.nbas) >> 1
    #out = zeros(T, N, auxBS.nbas)
    out = zeros(T, BS.nbas, BS.nbas, auxBS.nbas)

    # Save a list containing the angular momentum number for each shell
    lvals = [Libcint.CINTcgtos_spheric(i-1, BS.lc_bas) for i = 1:BS.nshells]
    Plvals = [Libcint.CINTcgtos_spheric(P-1, auxBS.lc_bas) for P = 1:auxBS.nshells]
    ao_offset = [sum(lvals[1:(i-1)]) for i = 1:BS.nshells]

    buf_arrays = [zeros(Cdouble, maximum(lvals)^2*maximum(Plvals)) for _ = 1:Threads.nthreads()]

    @sync for p in 1:auxBS.nshells
        Threads.@spawn begin
            @inbounds begin
                buf = buf_arrays[Threads.threadid()]
                Lp = Plvals[p]
                poff = sum(Plvals[1:(p-1)])
                Bp = p + BS.nshells - 1
                for i in 1:BS.nshells
                    Li = lvals[i]
                    ioff = ao_offset[i]
                    for j in i:BS.nshells
                        Lj = lvals[j]
                        joff = ao_offset[j]

                        # Call libcint
                        cint3c2e_sph!(buf, Cint.([i-1, j-1, Bp]), lc_atm, natm, lc_bas, nbas, env)

                        # Loop through shell block and save unique elements
                        for ps = 1:Lp
                            P = poff + ps
                            for js = 1:Lj
                                J = joff + js
                                for is = 1:Li
                                    I = ioff + is
                                    J < I ? break : nothing
                                    out[I,J,P] = buf[is + Li*(js-1) + Li*Lj*(ps-1)]
                                    out[J,I,P] = out[I,J,P]
                                end
                            end
                        end
                    end
                end
            end #inbounds
        end #spwan
    end #sync
    return out
end


text:
using Statistics: mean

# Test detrend function
@testset "Detrend Test" begin
    arr = [1.1, 1.2, 1.3, 1.4, 1.5]
    ϵ = 1e-6
    detrend!(arr)
    μ = mean(arr)
    @test μ < ϵ
end


text:
module RandomField

using FFTW, Random, LinearAlgebra

export
	# from functions.jl
	gaus_rf,
	rect_rf,
	sinc_rf,

	# from cloud.jl:
	Cloud,
	init!,
	tovtk,
	tocsv,
	Cscalar,
	sample!,
	slice,
	dim,
	surface,

	# from fourier.jl:
	create_grids,
	ift!,

	# from random.jl
	draw_realization!

include("functions.jl")

include("cloud.jl")

include("fourier.jl")

include("random.jl")

end # of RandomField


text:
using CSV, DataFrames
HS = [3, 6, 12]
Js = [301, 373, 493]
ensembles = ["BMA", "BMA2", "LAS", "LAS2", "RDG", "RDG2", "RDF", "RDF2", "ARM", "OLS", "MAG", "MAG2", "DFM", "DFM2", "RWM"]
models = vcat(ensembles, "ESMB")
RMSEs = zeros(length(models), length(HS), length(Js))
case = "baseline"
for (h, H) in enumerate(HS)
    for (j, J) in enumerate(Js)
        println("$h, $J")
        file_path = "../data/results/$case/level4-h$H-J$J/combined.csv"
        df_in = CSV.read(file_path)
        y = convert(Vector{Float64}, df_in[Symbol("REAL")])
        y_e = zeros(length(y))
        for e in ensembles
            y_e = y_e .+ convert(Vector{Float64}, df_in[Symbol(e)]) ./ length(ensembles)
        end
        df_in[:ESMB] = y_e
        CSV.write(file_path, df_in)
        for (m ,model) in enumerate(models)
            ŷ = convert(Vector{Float64}, df_in[Symbol(model)])
            RMSEs[m, h, j] = sqrt(mean((ŷ .- y).^2))
        end
    end
end

for (h, H) in enumerate(HS)
    df_out = DataFrame()
    df_out[:Models] = models
    for (j, J) in enumerate(Js)
        df_out[Symbol("h$H J$J")] = RMSEs[:, h, j]
        CSV.write("../data/results/$case/RMSEs_h$H.csv", df_out)
    end
end

max_stars_repo_name: jungangl/forecast-machine-learning

max_issues_repo_name: jungangl/forecast-machine-learning

max_forks_repo_name: jungangl/forecast-machine-learning


text:
@testset "code generation" begin

############################################################################################

@testset "LLVM IR" begin

@testset "JuliaLang/julia#21121" begin
    function foobar()
        weight_matrix = @cuStaticSharedMem(Float32, (16, 16))
        sync_threads()
        weight_matrix[1, 16] *= 2
        sync_threads()
    end

    ir = sprint(io->CUDAnative.code_llvm(io, foobar, Tuple{}))
    @test !occursin("inttoptr", ir)
end

@testset "PTX TBAA" begin
    load(ptr) = unsafe_load(ptr)
    store(ptr) = unsafe_store!(ptr, 0)

    for f in (load, store)
        ir = sprint(io->CUDAnative.code_llvm(io, f,
                                             Tuple{CUDAnative.DevicePtr{Float32,AS.Global}};
                                             dump_module=true, raw=true))
        @test occursin("gputbaa_global", ir)

        # no TBAA on generic pointers
        ir = sprint(io->CUDAnative.code_llvm(io, f,
                                             Tuple{CUDAnative.DevicePtr{Float32,AS.Generic}};
                                             dump_module=true, raw=true))
        @test !occursin("gputbaa", ir)
    end

    cached_load(ptr) = unsafe_cached_load(ptr)

    ir = sprint(io->CUDAnative.code_llvm(io, cached_load,
                                         Tuple{CUDAnative.DevicePtr{Float32,AS.Global}};
                                         dump_module=true, raw=true))
    @test occursin("gputbaa_global", ir)
end

@testset "ghost values" begin
    @eval struct Singleton end

    ir = sprint(io->CUDAnative.code_llvm(io, unsafe_load,
                                         Tuple{CUDAnative.DevicePtr{Singleton,AS.Global}}))
    @test occursin("ret void", ir)
    @test unsafe_load(reinterpret(CUDAnative.DevicePtr{Singleton,AS.Global}, C_NULL)) === Singleton()

    ir = sprint(io->CUDAnative.code_llvm(io, unsafe_store!,
                                         Tuple{CUDAnative.DevicePtr{Singleton,AS.Global},
                                         Singleton}))
    @test !occursin("\bstore\b", ir)
end

@testset "CUDAnative.jl#553" begin
    function kernel(ptr)
       unsafe_store!(ptr, CUDAnative.fma(unsafe_load(ptr), unsafe_load(ptr,2), unsafe_load(ptr,3)))
       return
    end

    ir = sprint(io->CUDAnative.code_llvm(io, kernel, Tuple{Ptr{Float32}}))
    @test !occursin("@__nv_fmaf", ir)
end

@testset "reinterpret(Nothing, nothing)" begin
    kernel(ptr) = Base.unsafe_load(ptr)
    CUDAnative.code_llvm(devnull, kernel, Tuple{CUDAnative.DevicePtr{Nothing,CUDAnative.AS.Global}}; strict=true)
end

@testset "ldg" begin
    ir = sprint(io->CUDAnative.code_llvm(io, CUDAnative.pointerref_ldg, Tuple{CUDAnative.DevicePtr{Int,CUDAnative.AS.Global},Int,Val{1}}))
    @test occursin("@llvm.nvvm.ldg", ir)
end

@testset "assume" begin
    foo(i) = cld(42, i)
    ir = sprint(io->CUDAnative.code_llvm(io, foo, Tuple{Int}))
    @test occursin("@gpu_report_exception", ir)

    bar(i) = (CUDAnative.assume(i > 0); cld(42, i))
    ir = sprint(io->CUDAnative.code_llvm(io, bar, Tuple{Int}))
    @test !occursin("gpu_report_exception", ir)
end

end

############################################################################################

end


text:
using SimplePlots
using Test

include("utils/index.jl")

@testset "SimplePlots.jl" begin

  include("plots/index.jl")
  include("interact.jl")

end


text:
module KeyedFrames

import Base: @deprecate
import DataFrames: deletecols!, deleterows!

using DataFrames
using DataFrames: DataFrameRow, SubDataFrame
using DataFrames: delete!, first, index, last, ncol, nonunique, nrow, permutecols!,
    rename, rename!, select, select!, unique!

struct KeyedFrame <: AbstractDataFrame
    frame::DataFrame
    key::Vector{Symbol}

    function KeyedFrame(df::DataFrame, key::Vector{Symbol})
        key = unique(key)
        df_names = propertynames(df)

        if !issubset(key, df_names)
            throw(
                ArgumentError(
                    string(
                        "The columns provided for the key ($key) must all be ",
                        "present in the DataFrame ($df_names)."
                    )
                )
            )
        end

        return new(df, key)
    end
end

function KeyedFrame(df::DataFrame, key::Vector{<:AbstractString})
    return KeyedFrame(df, map(Symbol, key))
end

KeyedFrame(df::DataFrame, key::Symbol) = KeyedFrame(df, [key])

"""
    KeyedFrame(df::DataFrame, key::Vector{Symbol})

Create an `KeyedFrame` using the provided `DataFrame`; `key` specifies the columns
to use by default when performing a `join` on `KeyedFrame`s when `on` is not provided.

When performing a `join`, if only one of the arguments is an `KeyedFrame` and `on` is not
specified, the frames will be joined on the `key` of the `KeyedFrame`. If both
arguments are `KeyedFrame`s, `on` will default to the intersection of their respective
indices. In all cases, the result of the `join` will share a type with the first argument.

When calling `unique` (or `unique!`) on a KeyedFrame without providing a `cols` argument,
`cols` will default to the `key` of the `KeyedFrame` instead of all columns. If you wish to
remove only rows that are duplicates across all columns (rather than just across the key),
you can call `unique!(kf, names(kf))`.

When `sort`ing, if no `cols` keyword is supplied, the `key` is used to determine precedence.

When testing for equality, `key` ordering is ignored, which means that it's possible to have
two `KeyedFrame`s that are considered equal but whose default sort order will be different
by virtue of having the columns listed in a different order in their `key`s.
"""
KeyedFrame

DataFrames.DataFrame(kf::KeyedFrame) = frame(kf)
Base.copy(kf::KeyedFrame) = KeyedFrame(copy(DataFrame(kf)), copy(keys(kf)))
Base.deepcopy(kf::KeyedFrame) = KeyedFrame(deepcopy(DataFrame(kf)), deepcopy(keys(kf)))

Base.convert(::Type{DataFrame}, kf::KeyedFrame) = frame(kf)

DataFrames.SubDataFrame(kf::KeyedFrame, args...) = SubDataFrame(frame(kf), args...)
DataFrames.DataFrameRow(kf::KeyedFrame, args...) = DataFrameRow(frame(kf), args...)

if isdefined(DataFrames, :_check_consistency)
    DataFrames._check_consistency(kf::KeyedFrame) = DataFrames._check_consistency(frame(kf))
end

##### EQUALITY #####

Base.:(==)(a::KeyedFrame, b::KeyedFrame) = frame(a) == frame(b) && sort(keys(a)) == sort(keys(b))

Base.isequal(a::KeyedFrame, b::KeyedFrame) = isequal(frame(a), frame(b)) && isequal(keys(a), keys(b))
Base.isequal(a::KeyedFrame, b::AbstractDataFrame) = false
Base.isequal(a::AbstractDataFrame, b::KeyedFrame) = false

Base.hash(kf::KeyedFrame, h::UInt) = hash(keys(kf), hash(frame(kf), h))

##### SIZE #####

DataFrames.nrow(kf::KeyedFrame) = nrow(frame(kf))
DataFrames.ncol(kf::KeyedFrame) = ncol(frame(kf))

##### ACCESSORS #####

DataFrames.index(kf::KeyedFrame) = index(frame(kf))
Base.names(kf::KeyedFrame) = names(frame(kf))

##### INDEXING #####

const ColumnIndex = Union{Real, Symbol}

frame(kf::KeyedFrame) = getfield(kf, :frame)
Base.keys(kf::KeyedFrame) = getfield(kf, :key)
Base.setindex!(kf::KeyedFrame, value, ind...) = setindex!(frame(kf), value, ind...)
Base.setproperty!(kf::KeyedFrame, field::Symbol, value) = setproperty!(frame(kf), field, value)

# I don't want to have to write the same function body several times, so...
function _kf_getindex(kf::KeyedFrame, index...)
    # If indexing by column, some keys might be removed.
    df = frame(kf)[index...]
    return KeyedFrame(DataFrame(df), intersect(propertynames(df), keys(kf)))
end

# Returns a KeyedFrame
Base.getindex(kf::KeyedFrame, ::Colon) = copy(kf)
Base.getindex(kf::KeyedFrame, ::Colon, ::Colon) = copy(kf)

# Returns a KeyedFrame
Base.getindex(kf::KeyedFrame, ::typeof(!), col::AbstractVector) = _kf_getindex(kf, !, col)

# Returns a KeyedFrame or a column (depending on the type of col)
Base.getindex(kf::KeyedFrame, ::typeof(!), col) = frame(kf)[!, col]
Base.getindex(kf::KeyedFrame, ::Colon, col) = frame(kf)[:, col]

# Returns a scalar
Base.getindex(kf::KeyedFrame, row::Integer, col::ColumnIndex) = frame(kf)[row, col]

# Returns a KeyedFrame
Base.getindex(kf::KeyedFrame, row::Integer, col::AbstractVector) = _kf_getindex(kf, row, col)

# Returns a column
Base.getindex(kf::KeyedFrame, row::AbstractVector, col::ColumnIndex) = frame(kf)[row, col]

# Returns a KeyedFrame
function Base.getindex(kf::KeyedFrame, row::AbstractVector, col::AbstractVector)
    return _kf_getindex(kf, row, col)
end

# Returns a KeyedFrame
function Base.getindex(kf::KeyedFrame, row::AbstractVector, col::Colon)
    return _kf_getindex(kf, row, col)
end

# Returns a KeyedFrame
Base.getindex(kf::KeyedFrame, row::Integer, col::Colon) = kf[[row], col]

##### SORTING #####

function Base.sort(kf::KeyedFrame, cols=nothing; kwargs...)
    return KeyedFrame(sort(frame(kf), cols === nothing ? keys(kf) : cols; kwargs...), keys(kf))
end

function Base.sort!(kf::KeyedFrame, cols=nothing; kwargs...)
    sort!(frame(kf), cols === nothing ? keys(kf) : cols; kwargs...)
    return kf
end

function Base.issorted(kf::KeyedFrame, cols=nothing; kwargs...)
    return issorted(frame(kf), cols === nothing ? keys(kf) : cols; kwargs...)
end

##### PUSH/APPEND/DELETE #####

function Base.push!(kf::KeyedFrame, data)
    push!(frame(kf), data)
    return kf
end

function Base.append!(kf::KeyedFrame, data)
    append!(frame(kf), data)
    return kf
end

function DataFrames.delete!(kf::KeyedFrame, inds)
    delete!(frame(kf), inds)
    return kf
end

@deprecate deleterows!(kf::KeyedFrame, inds) delete!(kf, inds)
@deprecate deletecols!(kf::KeyedFrame, inds) select!(kf, Not(inds))

function DataFrames.select!(kf::KeyedFrame, inds)
    select!(frame(kf), inds)
    new_keys = propertynames(kf)
    filter!(in(new_keys), keys(kf))
    return kf
end

function DataFrames.select(kf::KeyedFrame, inds; copycols::Bool=true)
    new_df = select(frame(kf), inds; copycols=copycols)
    df_names = propertynames(new_df)
    new_keys = filter(in(df_names), keys(kf))
    return KeyedFrame(new_df, new_keys)
end

##### RENAME #####

function DataFrames.rename!(kf::KeyedFrame, nms::AbstractVector{Pair{Symbol,Symbol}})
    rename!(frame(kf), nms)

    for (from, to) in nms
        i = findfirst(isequal(from), keys(kf))
        if i !== nothing
            keys(kf)[i] = to
        end
    end

    return kf
end

DataFrames.rename!(kf::KeyedFrame, nms::Pair{Symbol, Symbol}...) = rename!(kf, collect(nms))
DataFrames.rename!(kf::KeyedFrame, nms::Dict{Symbol, Symbol}) = rename!(kf, collect(pairs(nms)))
DataFrames.rename!(f::Function, kf::KeyedFrame) = rename!(kf, [(nm => f(nm)) for nm in propertynames(kf)])

DataFrames.rename(kf::KeyedFrame, args...) = rename!(copy(kf), args...)
DataFrames.rename(f::Function, kf::KeyedFrame) = rename!(f, copy(kf))

##### UNIQUE #####

_unique(kf::KeyedFrame, cols) = KeyedFrame(unique(frame(kf), cols), keys(kf))
function _unique!(kf::KeyedFrame, cols)
    unique!(frame(kf), cols)
    return kf
end

Base.unique(kf::KeyedFrame, cols::AbstractVector) = _unique(kf, cols)
Base.unique(kf::KeyedFrame, cols::Union{Integer, Symbol, Colon}) = _unique(kf, cols)
Base.unique(kf::KeyedFrame) = _unique(kf, keys(kf))
DataFrames.unique!(kf::KeyedFrame, cols::Union{Integer, Symbol, Colon}) = _unique!(kf, cols)
DataFrames.unique!(kf::KeyedFrame, cols::AbstractVector) = _unique!(kf, cols)
DataFrames.unique!(kf::KeyedFrame) = _unique!(kf, keys(kf))

DataFrames.nonunique(kf::KeyedFrame) = nonunique(frame(kf), keys(kf))
DataFrames.nonunique(kf::KeyedFrame, cols) = nonunique(frame(kf), cols)

##### JOINING #####

# Implement the various join functions provided by DataFrames.jl. If a `KeyedFrame` is used
# in a join and no `on` keyword is provided then the keys of the `KeyedFrame` will be used
# when joining. Additionally, a `KeyedFrame` will be returned only if the first argument to
# the join function is of type `KeyedFrame`.
for j in (:innerjoin, :leftjoin, :rightjoin, :outerjoin, :semijoin, :antijoin, :crossjoin)

    # Note: We could probably support joining more than two DataFrames but it becomes
    # tricker with what key to use with multiple KeyedFrames.

    @eval begin
        # Returns a KeyedFrame
        function DataFrames.$j(
            kf1::KeyedFrame,
            kf2::KeyedFrame;
            on=nothing,
            kwargs...,
        )
            if on === nothing
                on = intersect(keys(kf1), keys(kf2))
            end

            result = $j(
                frame(kf1),
                frame(kf2);
                on=on,
                kwargs...,
            )

            key = $(if j in (:semijoin, :antijoin)
                :(intersect(keys(kf1), propertynames(result)))
            else
                # A join can sometimes rename columns, meaning some of the key columns "disappear"
                :(intersect(union(keys(kf1), keys(kf2)), propertynames(result)))
            end)

            return KeyedFrame(result, key)
        end

        # Returns a KeyedFrame
        function DataFrames.$j(
            kf::KeyedFrame,
            df::AbstractDataFrame;
            on=nothing,
            kwargs...,
        )
            if on === nothing
                on = intersect(keys(kf), propertynames(df))
            end

            result = $j(
                frame(kf),
                df;
                on=on,
                kwargs...,
            )

            key = intersect(keys(kf), propertynames(result))

            return KeyedFrame(result, key)
        end

        # Does NOT return a KeyedFrame
        function DataFrames.$j(
            df::AbstractDataFrame,
            kf::KeyedFrame;
            on=nothing,
            kwargs...,
        )
            if on === nothing
                on = intersect(keys(kf), propertynames(df))
            end

            result = $j(
                df,
                frame(kf);
                on=on,
                kwargs...,
            )

            return result
        end
    end
end

# Implement the previously defined `join` functions used with DataFrames < 0.21
for (T, S) in [
    (:KeyedFrame, :KeyedFrame),
    (:KeyedFrame, :AbstractDataFrame),
    (:AbstractDataFrame, :KeyedFrame)
]
    @eval begin
        function Base.join(df1::$T, df2::$S; on=nothing, kind=:inner, kwargs...)
            j = if kind === :inner
                innerjoin
            elseif kind === :left
                leftjoin
            elseif kind === :right
                rightjoin
            elseif kind === :outer
                outerjoin
            elseif kind === :semi
                semijoin
            elseif kind === :anti
                antijoin
            elseif kind === :crossjoin
                crossjoin
            else
                throw(ArgumentError("Unknown join kind: $kind"))
            end

            Base.depwarn("$kind joining data frames using `join` is deprecated, use `$(kind)join` instead", :join)

            return j(df1, df2; on=on, kwargs...)
        end
    end
end

##### FIRST/LAST #####

DataFrames.first(kf::KeyedFrame, r::Int) = KeyedFrame(first(frame(kf), r), keys(kf))
DataFrames.last(kf::KeyedFrame, r::Int) = KeyedFrame(last(frame(kf), r), keys(kf))

##### PERMUTE #####

function DataFrames.permutecols!(kf::KeyedFrame, index::AbstractVector)
    select!(frame(kf), index)
    return kf
end

export KeyedFrame

end


text:
abstract type AbstractObservableAccumulator <: AbstractAccumulator end
abstract type AbstractMachineAccumulator <: AbstractAccumulator end

abstract type AbstractMachineValAccumulator <: AbstractMachineAccumulator end
abstract type AbstractMachineGradAccumulator <: AbstractMachineAccumulator end

init!(acc::AbstractObservableAccumulator, σ, ψ_σ, ∇ψ_σ) = init!(acc, σ, ψ_σ)


text:
using Base.Meta: isexpr, quot

# Some names don't follow the automatic conversion rules, so define how to make some
# of the translations explicitly.
const bind_exceptions = Dict{Symbol,Symbol}()

# Distinguishes 32-bit vs 64-bit handle arguments
push!(bind_exceptions, :h5p_get_fapl_mpio32 => :H5Pget_fapl_mpio)
push!(bind_exceptions, :h5p_get_fapl_mpio64 => :H5Pget_fapl_mpio)
push!(bind_exceptions, :h5p_set_fapl_mpio32 => :H5Pset_fapl_mpio)
push!(bind_exceptions, :h5p_set_fapl_mpio64 => :H5Pset_fapl_mpio)

# An expression which is injected at the beginning of the API defitions to aid in doing
# (pre)compile-time conditional compilation based on the libhdf5 version.
_libhdf5_build_ver_expr = quote
    _libhdf5_build_ver = let
            majnum, minnum, relnum = Ref{Cuint}(), Ref{Cuint}(), Ref{Cuint}()
            r = ccall((:H5get_libversion, libhdf5), herr_t,
                      (Ref{Cuint}, Ref{Cuint}, Ref{Cuint}),
                      majnum, minnum, relnum)
            r < 0 && error("Error getting HDF5 library version")
            VersionNumber(majnum[], minnum[], relnum[])
        end
end

# We'll also use this processing pass to automatically generate documentation that simply
# lists all of the bound API functions.
const bound_api = Dict{String,Vector{String}}()

"""
    @bind h5_function(arg1::Arg1Type, ...)::ReturnType [ErrorStringOrExpression]

A binding generator for translating `@ccall`-like declarations of HDF5 library functions
to error-checked `ccall` expressions.

The provided function name is used to define the Julia function with any trailing version
number removed (such as `h5t_open2` -> `h5t_open`). The corresponding C function name is
auto-generated by uppercasing the first few letters (up to the first `_`), the first `_` is
removed. Explicit name mappings can be made by inserting a `:jlname => :h5name` pair into
the `bind_exceptions` dictionary.

The optional `ErrorStringOrExpression` can be either a string literal or an arbitrary
expression. If not provided, no error check is done. If it is a `String`, the string is used
as the message in an `error()` call, otherwise the expression is used as-is. Note that the
expression may refer to any arguments by name.

The declared return type in the function-like signature must be the return type of the C
function, and the Julia return type is inferred as one of the following possibilities:

1. If `ReturnType === :herr_t`, the Julia function returns `nothing` and the C return is
   used only in error checking.

2. If `ReturnType === :htri_t`, the Julia function returns a boolean indicating whether
   the return value of the C function was zero (`false`) or positive (`true`).

3. Otherwise, the C function return value is returned from the Julia function, with the
   following exceptions:

   - If the return type is an C integer type compatible with Int, the return type is
     converted to an Int.

Furthermore, the C return value is interpreted to automatically generate error checks
(only when `ErrorStringOrExpression` is provided):

1. If `ReturnType === :herr_t` or `ReturnType === :htri_t`, an error is raised when the return
   value is negative.

2. If `ReturnType === :haddr_t` or `ReturnType === :hsize_t`, an error is raised when the
   return value is equivalent to `-1 % haddr_t` and `-1 % hsize_t`, respectively.

3. If `ReturnType` is a `Ptr` expression, an error is raised when the return value is
   equal to `C_NULL`.

3. For all other return types, it is assumed a negative value indicates error.

It is assumed that the HDF library names are given in global constants named `libhdf5`
and `libhdf5_hl`. The former is used for all `ccall`s, except if the C library name begins
with "H5DO" or "H5TB" then the latter library is used.
"""
macro bind(sig::Expr, err::Union{String,Expr,Nothing} = nothing,
           vers::Union{Expr,Nothing} = nothing)
    expr = _bind(__module__, __source__, sig, err)
    isnothing(vers) && return esc(expr)

    isexpr(vers, :tuple) || error("Expected 2-tuple of version bounds, got ", vers)
    length(vers.args) == 2 || error("Expected 2-tuple of version bounds, got ", vers)
    lb = vers.args[1]
    ub = vers.args[2]

    if lb !== :nothing && !(isexpr(lb, :macrocall) && lb.args[1] == Symbol("@v_str"))
        error("Lower version bound must be `nothing` or version number literal, got ", lb)
    end
    if ub !== :nothing && !(isexpr(ub, :macrocall) && ub.args[1] == Symbol("@v_str"))
        error("Upper version bound must be `nothing` or version number literal, got ", ub)
    end

    if lb === :nothing && ub !== :nothing
        conditional = :(_libhdf5_build_ver < $(ub))
    elseif lb !== :nothing && ub === :nothing
        conditional = :($(lb) ≤ _libhdf5_build_ver)
    else
        conditional = :($(lb) ≤ _libhdf5_build_ver < $(ub))
    end
    conditional = Expr(:if, conditional, expr)
    return esc(Expr(:macrocall, Symbol("@static"), nothing, conditional))
end

function _bind(__module__, __source__, sig::Expr, err::Union{String,Expr,Nothing})
    sig.head === :(::) || error("return type required on function signature")

    # Pull apart return-type and rest of function declaration
    rettype = sig.args[2]::Union{Symbol,Expr}
    funcsig = sig.args[1]
    isexpr(funcsig, :call) || error("expected function-like expression, found `", funcsig, "`")
    funcsig = funcsig::Expr

    # Extract function name and argument list
    jlfuncname = funcsig.args[1]::Symbol
    funcargs = funcsig.args[2:end]

    # Pull apart argument names and types
    args = Vector{Symbol}()
    argt = Vector{Union{Expr,Symbol}}()
    for ii in 1:length(funcargs)
        argex = funcargs[ii]
        if !isexpr(argex, :(::)) || !(argex.args[1] isa Symbol)
            error("expected `name::type` expression in argument ", ii, ", got ", funcargs[ii])
        end
        push!(args, argex.args[1])
        push!(argt, argex.args[2])
    end

    prefix, rest = split(string(jlfuncname), "_", limit = 2)
    # Translate the C function name to a local equivalent
    if haskey(bind_exceptions, jlfuncname)
        cfuncname = bind_exceptions[jlfuncname]
    else
        # turn e.g. h5f_close into H5Fclose
        cfuncname = Symbol(uppercase(prefix), rest)
        # Remove the version number if present (excluding match to literal "hdf5" suffix)
        if occursin(r"\d(?<!hdf5)$", String(jlfuncname))
            jlfuncname = Symbol(chop(String(jlfuncname), tail = 1))
        end
    end

    # Store the function prototype in HDF5-module specific lists:
    funclist = get!(bound_api, uppercase(prefix), Vector{String}(undef, 0))
    string(jlfuncname) in funclist || push!(funclist, string(jlfuncname))
    # Also start building the matching doc string.
    docfunc = copy(funcsig)
    docfunc.args[1] = jlfuncname
    docstr = "    $docfunc"

    # Determine the underlying C library to call
    lib = startswith(string(cfuncname), r"H5(DO|DS|LT|TB)") ? :libhdf5_hl : :libhdf5

    # Now start building up the full expression:
    statsym = Symbol("#status#") # not using gensym() to have stable naming

    # The ccall(...) itself
    cfunclib = Expr(:quote, cfuncname)
    ccallexpr = :(ccall($cfunclib, $rettype, ($(argt...),), $(args...)))

    # The error condition expression
    errexpr = err isa String ? :(error($err)) : err
    if errexpr === nothing
        # pass through
    elseif rettype === :haddr_t || rettype === :hsize_t
        # Error typically indicated by negative values, but some return types are unsigned
        # integers. From `H5public.h`:
        #   ADDR_UNDEF => (haddr_t)(-1)
        #   HSIZE_UNDEF => (hsize_t)(-1)
        # which are both just `-1 % $type` in Julia
        errexpr = :($statsym == -1 % $rettype && $errexpr)
    elseif isexpr(rettype, :curly) && rettype.args[1] === :Ptr
        errexpr = :($statsym == C_NULL && $errexpr)
    else
        errexpr = :($statsym < 0 && $errexpr)
    end

    # Three cases for handling the return type
    if rettype === :htri_t
        # Returns a Boolean on non-error
        returnexpr = :(return $statsym > 0)
        docstr *= " -> Bool"
    elseif rettype === :herr_t
        # Only used to indicate error status
        returnexpr = :(return nothing)
    elseif rettype === :Cint
        # Convert to Int type
        returnexpr = :(return Int($statsym))
        docstr *= " -> Int"
    else
        # Returns a value
        returnexpr = :(return $statsym)
        docstr *= " -> $rettype"
    end

    docstr *= "\n\nSee `libhdf5` documentation for [`$cfuncname`]" *
              "(https://portal.hdfgroup.org/display/HDF5/$(uppercase(string(funcsig.args[1])))).\n"

    # Then assemble the pieces. Doing it through explicit Expr() objects
    # avoids inserting the line number nodes for the macro --- the call site
    # is instead explicitly injected into the function body via __source__.
    jlfuncsig = Expr(:call, jlfuncname, args...)
    jlfuncbody = Expr(:block, __source__, :($statsym = $ccallexpr))
    if errexpr !== nothing
        push!(jlfuncbody.args, errexpr)
    end
    push!(jlfuncbody.args, returnexpr)
    jlfuncexpr = Expr(:function, jlfuncsig, jlfuncbody)
    jlfuncexpr = Expr(:macrocall, Symbol("@doc"), nothing, docstr, jlfuncexpr)
    return jlfuncexpr
end


text:
"""
Module ParallelStencil

Enables domain scientists to write high-level code for parallel high-performance stencil computations that can be deployed on both GPUs and CPUs.

# General overview and examples
https://github.com/omlins/ParallelStencil.jl

# Macros and functions
- [`@init_parallel_stencil`](@ref)
- [`@parallel`](@ref)
- [`@hide_communication`](@ref)
- [`@zeros`](@ref)
- [`@ones`](@ref)
- [`@rand`](@ref)
!!! note "Advanced"
    - [`@parallel_indices`](@ref)
    - [`@parallel_async`](@ref)
    - [`@synchronize`](@ref)

# Submodules
- [`ParallelStencil.FiniteDifferences1D`](@ref)
- [`ParallelStencil.FiniteDifferences2D`](@ref)
- [`ParallelStencil.FiniteDifferences3D`](@ref)

# Modules generated in caller
- [`Data`](@ref)

To see a description of a function, macro or module type `?<functionname>`, `?<macroname>` (including the `@`) or `?<modulename>`, respectively.
"""
module ParallelStencil

## Alphabetical include of submodules, except computation-submodules (below)
include("ParallelKernel/ParallelKernel.jl")
import .ParallelKernel # NOTE: not using .ParallelKernel as for each exported macro except @init_parallel_kernel a corresponding macro is defined in ParallelStencil - using its own doc (modified ParallelKernel doc) and its own check of proper initialization.
import .ParallelKernel: @init_parallel_kernel
using .ParallelKernel.Exceptions

## Include of constant parameters, types and syntax sugar shared in ParallelStencil top module only (must be after include of ParallelKernel.jl as imports from there)
include("shared.jl")

## Alphabetical include of function files
include("init_parallel_stencil.jl")
include("parallel.jl")
include("reset_parallel_stencil.jl")

## Alphabetical include of computation-submodules (must be at end as needs to import from ParallelStencil, .e.g. INDICES).
include("FiniteDifferences.jl")

## Exports (need to be after include of submodules as re-exports from them)
export @init_parallel_stencil, FiniteDifferences1D, FiniteDifferences2D, FiniteDifferences3D
export @parallel, @hide_communication, @parallel_indices, @parallel_async, @synchronize, @zeros, @ones, @rand

end # Module ParallelStencil


text:
@testset "generate_surface" begin
    img = generate_surface(SynthSphere(50), 1.0, [0,0,1])
    p, q = synthetic_gradient(SynthSphere(50))
    img2 = generate_surface(p, q, 1.0, [0,0,1])
    @test isapprox(img[1,1], Gray(1.0), atol = 0.1)
    @test isapprox(img2[1,1], Gray(1.0), atol = 0.1)
    @test isapprox(img[75,75], Gray(1.0), atol = 0.1)
    @test isapprox(img2[75,75], Gray(1.0), atol = 0.1)
end


text:
struct Bodies{T<:AbstractVector}
    masses::T
    positions::Tuple{T, T, T}
    velocities::Tuple{T, T, T}
    accelerations::Tuple{T, T, T}

    function Bodies{T}(m, r, v, a) where {T}

        !same_size(m, r..., v..., a...) && throw(DimensionMismatch())
        return new(m, r, v, a)
    end

end

function Bodies(
    m::T,
    r::Tuple{T, T, T},
    v::Tuple{T, T, T},
    a::Tuple{T, T, T}
) where{T}

    return Bodies{T}(m, r, v, a)
end

function Base.iterate(b::Bodies, i=1)
    if state > length(m)
        return nothing
    else
        mass = b.masses[i]
        position     = SVector(b.positions[1][i],     b.positions[2][i],     b.positions[3][i])
        velocity     = SVector(b.velocities[1][i],    b.velocities[2][i],    b.velocities[3][i])
        acceleration = SVector(b.accelerations[1][i], b.accelerations[2][i], b.accelerations[3][i])

        return (
            (mass = mass, position = position, velocity = velocity, acceleration = acceleration),
            i+1
        )
    end
end


text:
# SPD-License-Identifier: MIT

using ArgParse
using JLD2
using MarkovModels

function parse_commandline()
    s = ArgParseSettings()
    @add_arg_table s begin
        "--start-non-speech", "-s"
            action = :store_true
            help = "force the graph to start with a non-speech unit"
        "--end-non-speech", "-e"
            action = :store_true
            help = "force the graph to end with a non-speech unit"
        "hmms"
            required = true
            help = "per-unit hmms"
        "cfsm"
            required = true
            help = "output compiled fsm"
    end
    s.description = """
    Build a phone-loop decoding graph.
    """
    parse_args(s)
end

function main(args)
    hmmsdata = load(args["hmms"])
    su_hmms = hmmsdata["speech_units"]
    nsu_hmms = hmmsdata["non_speech_units"]
    num_pdfs = hmmsdata["num_pdfs"]
    hmms = merge(su_hmms, nsu_hmms)

    SF = LogSemifield{Float32}
    fsm = VectorFSM{SF}()

    for unit in collect(keys(hmms))
        s = addstate!(fsm, unit)
        if ! args["start-non-speech"]
            setinit!(s)
        elseif unit ∈ keys(nsu_hmms)
            setinit!(s)
        end

        if ! args["end-non-speech"]
            setfinal!(s)
        elseif unit ∈ keys(nsu_hmms)
            setfinal!(s)
        end
    end

    for src in states(fsm)
        for dest in states(fsm)
            link!(fsm, src, dest)
        end
    end
    fsm = replace(renormalize!(fsm), hmms)
    cfsm, labels = compile(fsm, num_pdfs)

    jldopen(args["cfsm"], "w") do f
        f["cfsm"] = cfsm
        f["labels"] = labels
    end
end

args = parse_commandline()
main(args)

max_stars_repo_name: MartinKocour/SpeechLab

max_issues_repo_name: MartinKocour/SpeechLab

max_forks_repo_name: MartinKocour/SpeechLab


text:
"""
    density(ls)

Return the density of the link stream.
For a link stream the classical graph relation holds
and we have:
```math
\\delta \\left( L \\right)= \\frac{2 m}{n \\left( n-1 \\right)}
```
Note: For link streams with less than 2 nodes, this
function returns 0.

### Reference
- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social
  Networks Analysis and Mining, 8: 61, 2018. "Stream Graphs and
  Link Streams for the Modeling of Interactions over Time".
  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)
"""
function density(ls::Union{LinkStream,DirectedLinkStream})
    length(ls.V) > 1 ? 2*number_of_links(ls)/(number_of_nodes(ls)*(number_of_nodes(ls)-1)) : 0.0
end

"""
    density(s)

Return the density of the stream graph defined as:
```math
\\delta \\left( S \\right) = \\frac{ \\sum_{uv \\in V \\otimes V} \\left| T_{uv} \\right| }{\\sum_{uv \\in V \\otimes V} \\left| T_u \\cap T_v \\right|}
```
Note: For link streams with no node and/or no link, this
function returns 0.

### Reference
- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social
  Networks Analysis and Mining, 8: 61, 2018. "Stream Graphs and
  Link Streams for the Modeling of Interactions over Time".
  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)
"""
function density(s::Union{StreamGraph,DirectedStreamGraph})
    ((length(s.V)==0) | (length(s.E)==0)) && 0.0
    denom = sum([length(times(s,u) ∩ times(s,v)) for (u,v) in s.V ⊗ s.V])
    denom != 0 ? sum([duration(l) for (k,v) in s.E for (kk,l) in v]) / denom : 0
end

"""
    density(s,tc)

Return the density of the stream graph using a TimeCursor.
In this case, the density is computed as:
```math
\\delta \\left( S \\right) = \\frac{ \\int_{t \\in T} \\left| E_t \\right| dt }{\\int_{t \\in T} \\left| V_t \\otimes V_t \\right| dt}
```
Note: For link streams with no node and/or no link, this
function returns 0.

### Reference
- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social
  Networks Analysis and Mining, 8: 61, 2018. "Stream Graphs and
  Link Streams for the Modeling of Interactions over Time".
  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)
"""
function density(s::Union{StreamGraph,DirectedStreamGraph},tc::TimeCursor)
    ((length(s.V)==0) | (length(s.E)==0)) && 0.0
    start!(tc)
    nom::Float64=duration(tc.S)*number_of_links(tc)
    denom::Float64=duration(tc.S)*length(nodes(tc) ⊗ nodes(tc))
    while tc.S.t1 < s.T.list[1][2]
        next!(tc)
        nom+=duration(tc.S)*number_of_links(tc)
        denom+=duration(tc.S)*length(nodes(tc) ⊗ nodes(tc))
    end
    denom != 0 ? nom / denom : 0
end

"""
    density(s,t)

Density at a time instant t in the given stream graph, defined as:
```math
\\delta \\left( t \\right) = \\frac{ \\left| E_t \\right|}{\\left| V_t \\otimes V_t \\right|}
```
Note: If there is no node involved at t, this
function returns 0.

### Reference
- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social
  Networks Analysis and Mining, 8: 61, 2018. "Stream Graphs and
  Link Streams for the Modeling of Interactions over Time".
  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)
"""
function density(s::Union{StreamGraph,DirectedStreamGraph}, t::Float64)
    Vt=Set{AbstractString}(nodes(s,t))
    length(Vt)!=0 ? length(links(s,t))/length(Vt ⊗ Vt) : 0.0
end

"""
    density(ls,t)

Density at a time instant t in the given link stream.
In a link stream, the density of a time instant reduces to:
```math
\\delta \\left( t \\right) = \\frac{ \\left| E_t \\right|}{\\left| V \\otimes V \\right|} = l_t
```
Note: For link streams with less than 2 nodes, this
function returns 0.

### Reference
- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social
  Networks Analysis and Mining, 8: 61, 2018. "Stream Graphs and
  Link Streams for the Modeling of Interactions over Time".
  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)
"""
function density(ls::Union{LinkStream,DirectedLinkStream}, t::Float64)
    length(ls.V)>1 ? 2 * sum([duration(l) for l in links(ls,t)])/(length(ls.V)*(length(ls.V)-1)) : 0
end

"""
    density(s,n1,n2)

Density of the pair of nodes (n1,n2) in the given stream graph, defined as:
```math
\\delta \\left( uv \\right) = \\frac{ \\left| T_{uv} \\right|}{\\left| T_u \\cap T_v \\right|}
```
Note: If u and v are never involved at the same time, this
function returns 0.

### Reference
- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social
  Networks Analysis and Mining, 8: 61, 2018. "Stream Graphs and
  Link Streams for the Modeling of Interactions over Time".
  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)
"""
function density(s::Union{StreamGraph,DirectedStreamGraph},n1::AbstractString,n2::AbstractString)
    denom=length(times(s,n1) ∩ times(s,n2))
    denom != 0 ? length(times(s,n1,n2))/denom : 0.0
end

"""
    density(ls,n1,n2)

Density of the pair of nodes (n1,n2) in the given link stream.
In a link stream, the density of a pair of nodes reduces to:
```math
\\delta \\left( uv \\right) = \\frac{ \\left| T_{uv} \\right|}{\\left| T \\right|}
```
Note: If the link stream has a duration of 0, this
function returns 0.

### Reference
- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social
  Networks Analysis and Mining, 8: 61, 2018. "Stream Graphs and
  Link Streams for the Modeling of Interactions over Time".
  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)
"""
function density(ls::Union{LinkStream,DirectedLinkStream},n1::AbstractString,n2::AbstractString)
    duration(ls)!=0 ? duration(links(ls,n1,n2))/duration(ls) : 0
end

"""
    density(s,n)

Density of a node in the given stream, defined as:
```math
\\delta \\left( v \\right) = \\frac{ \\sum_{u \\in V,u \\neq v} \\left| T_{uv} \\right|}{\\sum_{u \\in V,u \\neq v} \\left| T_u \\cap T_v \\right|}
```
Note: If there is no node present at the same time as v, this
function returns 0.

### Reference
- Matthieu Latapy, Tiphaine Viard and Clémence Magnien Social
  Networks Analysis and Mining, 8: 61, 2018. "Stream Graphs and
  Link Streams for the Modeling of Interactions over Time".
  [(arXiv)](https://arxiv.org/pdf/1710.04073.pdf)
"""
function density(s::AbstractStream,n::AbstractString)
    nom=sum([length(times(s,u,n)) for u in s.V if u != n])
    denom=sum([length(times(s,u) ∩ times(s,n)) for u in s.V if u != n])
    denom != 0 ? nom/denom : 0.0
end

"""
  density(tc)

Return the density of the graph representing the current
state of the TimeCursor.
"""
function density(tc::TimeCursor)
    number_of_nodes(tc) > 1 ? (2*number_of_links(tc))/(number_of_nodes(tc)*(number_of_nodes(tc)-1)) : 0.0
end

"""
  density(tc,t)

Return the density of the graph representing the state of
the TimeCursor at time t.
"""
function density(tc::TimeCursor,t::Float64)
    n=number_of_nodes(tc,t)
    m=number_of_links(tc,t)
    n > 1 ? (2*m)/(n*(n-1)) : 0.0
end

"""
  density(tc,t0,t1)

Return the density of the aggregated graph representing the states of
the TimeCursor at between time t0 and t1.
"""
function density(tc::TimeCursor,t0::Float64,t1::Float64)
    n=number_of_nodes(tc,t0,t1)
    m=number_of_links(tc,t0,t1)
    n > 1 ? (2*m)/(n*(n-1)) : 0.0
end


text:
coord = LaneCoord()
coord = LaneCoord(0, 1.0, 2.0, 3.0)   # distance perpendicular to the track
@test coord.trackid == 0
@test coord.s == 1.0
@test coord.t == 2.0
@test coord.z == 3.0
@test coord.h == 0.0
@test coord.p == 0.0
@test coord.r == 0.0
@test coord.laneid == 1
@test coord.offset == 0.0

@test coord == LaneCoord(0, 1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1, 0.0)

coord = LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1, 1.0)   # distance perpendicular to the track
@test coord == LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1, 1.0)

coordim = LaneCoordIm(0, 1.0, 2.0, 3.0)
@test coordim.trackid == 0
@test coordim.s == 1.0
@test coordim.t == 2.0
@test coordim.z == 3.0
@test coordim.h == 0.0
@test coordim.p == 0.0
@test coordim.r == 0.0
@test coordim.laneid == 1
@test coordim.offset == 0.0

@test coordim == LaneCoord(0, 1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1, 0.0)
@test coordim == LaneCoordIm(0, 1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1, 0.0)

coordim = LaneCoordIm(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1, 1.0)
@test coord == coordim
@test coordim == coord

show(coord); print("\n")
show(coordim); print("\n")
print(coord, "\n")
print(coordim, "\n")

@test copy(coord) == LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1, 1.0)
@test deepcopy(coord) == LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1, 1.0)
@test copy!(LaneCoord(), coord) == LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1, 1.0)
@test init!(copy(coord)) == LaneCoord(0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0.0)

@test plus!(copy(coord), LaneCoord(1, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 2, 6.5)) ==
        LaneCoord(1, 1.5, 3.5, 5.5, 7.5, 5.0, 6.0, 3, 7.5)
@test plus!(copy(coord), TrackCoord(1, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5)) ==
        LaneCoord(1, 1.5, 3.5, 5.5, 7.5, 5.0, 6.0, 1, 1.0)

@test copy(coordim) == LaneCoordIm(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1, 1.0)
@test deepcopy(coord) == LaneCoord(0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1, 1.0)

coordA = LaneCoord(1, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 2, 6.5)
coordim = LaneCoordIm(1, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 2, 6.5)

@test isa(convert(LaneCoord, coordA), LaneCoord)
@test isa(convert(LaneCoordIm, coordA), LaneCoordIm)
@test isa(convert(LaneCoord, coordim), LaneCoord)
@test isa(convert(LaneCoordIm, coordim), LaneCoordIm)

@test convert(LaneCoord, coordA) == coordA
@test convert(LaneCoord, coordim) == coordim
@test convert(LaneCoordIm, coordA) == coordA
@test convert(LaneCoordIm, coordim) == coordim

max_stars_repo_name: sisl/OpenDriveManagerLite

max_issues_repo_name: sisl/OpenDriveManagerLite

max_forks_repo_name: sisl/OpenDriveManagerLite


text:
using MOCNeutronTransport
using Test
using Logging
Logging.disable_logging(Logging.Error)
tests = ["Tree",
         "./primitives/Point",
         "./primitives/LineSegment",
         "./primitives/AABB",
#         "./primitives/QuadraticSegment_2D",
#         "./primitives/Triangle_2D",
#         "./primitives/Quadrilateral_2D",
#         "./primitives/Triangle6_2D",
#         "./primitives/Quadrilateral8_2D",
#         "./mesh/UnstructuredMesh_2D",
#         "./mesh/IO_abaqus",
#         "./mesh/IO_vtk",
#         "./mesh/IO_xdmf",
#         "AngularQuadrature",
        ]
for t in tests
  include("$(t).jl")
end

max_stars_repo_name: KyleVaughn/MOCNeutronTransport

max_issues_repo_name: KyleVaughn/MOCNeutronTransport

max_forks_repo_name: KyleVaughn/MOCNeutronTransport


text:
# include("znccUtils.jl")

"""
	2D IMPLEMENTATION: f is search volume, g is interrogation volume (translated function)
"""

#  Lewis, J.P.: Fast normalized cross-correlation. Ind. Light Magic10(2001)
#
#  ZNCC = (IA - meanIA )(SA - meanSA ) / ( sqrt( sum(IA-meanIA)^2 )*sqrt( sum(SA-meanSA)^2 ) )
#          --------------------------            ----------------         ----------------
#        FFTcross( IA-meanIA, SA-meanSA)    constant: std(IA)*sqrt(N)       integralArray

function crossCorrelation!( ::ZNCC, cmat::A{T,2}, shifted::A{T,2}, shifts,
                                    padf::A{C{T},2}, padg::A{C{T},2}, plan, iplan,
                                    intArr2::A{T,2}, stdG, sizeF, sizeG
                           ) where {T<:AbstractFloat}

    # Computing numerator
    crossCorrelation!( FFT(), cmat, padf, padg, plan, iplan );
    Base.circshift!( shifted, cmat, shifts[1:2] )

	# Constant denominator
    N    = prod(sizeG);
	denG = stdG*sqrt(N);

	# Variable denominator for each translation
	fh, fw = sizeF
	gh, gw = sizeG .- 1

	for c in 0:size(cmat,2)-1; 		c1 = max(1, fw - c ); c2 = min( fw, c1 + gw )
		for r in 0:size(cmat,1)-1;  r1 = max(1, fh - r ); r2 = min( fh, r1 + gh )

			sumF2 = integralArea( intArr2, (r1-1,c1-1), (r2,c2) )
			sumF2 = ( sumF2 <= 0.0 ) ? Inf : sumF2;
		    cmat[ r+1, c+1 ] = shifted[ r+1, c+1 ]/( sqrt( sumF2 )*denG );
    end	end
end

function PIV_2D( ::ZNCC, img1::A{<:Real,2}, img2::A{<:Real,2},
                         IA::III, SM::III, overlap::III, mpass::I, width::I,
                         peak::S, sigNoise::S, filtFun::Function, threshold::F;
					     corrType=Float32, vfType=Float32 )

    step   = IA  .-  overlap;
	imsize = ( size(img1,1), size(img1,2), size(img1,3) )
    vfSize = length.( StepRange.( IA, step, imsize ) );

    U  = zeros( vfType, vfSize[1:2] );
    V  = zeros( vfType, vfSize[1:2] );
    SN = zeros( vfType, vfSize[1:2] );

	ignoreSN = ( sigNoise == "" );
	SM = ( SM[1], SM[2], 0 );

    for mp in mpass:-1:1

        last_mp = ( mp == 1 );

        # Scaling IA, SM and step (overlap) to multi-pass iteration.
        IA_mp    =  IA  .* mp;
        SM_mp    =  SM  .* mp;
        step_mp  = step .* mp;
		IAranges = StepRange.( IA_mp, step_mp, imsize )

        # Initializing variables for FFT cross-Correlation.
        csize   = 2 .* ( IA_mp .+ SM_mp  );
		shifts  = div.(csize , 2) .+ SM_mp .- 1;
        cmatrix = zeros( corrType, csize[1:2] );
        num     = zeros( corrType, csize[1:2] );
        pads    = zeros( Complex{corrType}, csize[1:2] );
        padi    = zeros( Complex{corrType}, csize[1:2] );
        plan    =  FFTW.plan_fft!( pads );
        iplan   = FFTW.plan_ifft!( pads );

		# Initializing integral arrays for computing ZNCC
        ssize   = IA_mp .+ 2 .* SM_mp
        intArr2 = zeros( corrType, ssize[1:2] .+ 1 );

		# Nested loop establishing IA and UV coordinates
		vfx = [ 1-mp, 0 ]
		for x2 in IAranges[2];     x1 = x2-IA_mp[2]+1; vfx .+= mp; vfy = [ 1-mp, 0 ];
			for y2 in IAranges[1]; y1 = y2-IA_mp[1]+1; vfy .+= mp;

				# 0-. Filtering undesirable IAs, ex background
				interr = view( img1, y1:y2, x1:x2 )

				if filtFun( interr ) < threshold
					SN[ vfy[1]:vfy[2], vfx[1]:vfx[2] ] .= -1.0
					continue;
				end

			    # 1.1-. Previously computed displacements shift the search area during multipass
			    u = round(Int32, U[ vfy[1], vfx[1] ]);
			    v = round(Int32, V[ vfy[1], vfx[1] ]);

				scoords, offset = SAcoords( (y1,x1,1), (y2,x2,1), (u,v,0), SM_mp, imsize );

				# 1.3-. Computing the mean and std of IA and mean and mean^2 of SA
				meanI, stdI = meanStd( interr )

				meanS = 0.0
				@inbounds for x in x1:x2
					@simd for y in y1:y2
						meanS += img2[y,x]
				end	end
				meanS = meanS/length(img2)

				# 1.4-. Copying IA - meanI and SA - meanS into the padded arrays for FFT
				setTo0!( pads, padi )
			    putWithinPadded!( pads, img2, meanS, offset, scoords );
			    putWithinPadded!( padi, img1, meanI, (0,0,0), (y1,y2,x1,x2,1,1) );

				# 1.5-. Computing integral array and integral array ^2
				setTo0!( intArr2 )
				integralArraySQ!( pads, intArr2 )

		        # 2-. Cross-Correlation
		        crossCorrelation!( ZNCC(), cmatrix, num, shifts, pads, padi, plan, iplan,
		                                   intArr2, stdI, ssize, IA_mp );

		        # 3.1-. Calculation of displacement
		        ( r, c ) = approxTranslation( cmatrix, peak, Val(last_mp) )

				# 3.2-. Computing signal to noise ration, if needed
				if ( !ignoreSN && last_mp )
		        	SN[ vfy[1]:vfy[2], vfx[1]:vfx[2] ] = SNRatio( cmatrix, sigNoise, width )
				end

		        # 4-. Updating U, V matrices
		        U[ vfy[1]:vfy[2], vfx[1]:vfx[2] ] .= u - r;
		        V[ vfy[1]:vfy[2], vfx[1]:vfx[2] ] .= v - c;

		end	end
    end # Multi-pass loop

    return U, V, SN
end

"""
	3D IMPLEMENTATION: f is search volume, g is interrogation volume (translated function)
"""

function crossCorrelation!( ::ZNCC, cmat::A{T,3}, shifted::A{T,3},  shifts,
                                    padf::A{C{T},3}, padg::A{C{T},3}, plan, iplan,
                                    intArr2::A{T,3}, stdG, sizeF, sizeG
						  ) where {T<:AbstractFloat}

    # Computing numerator
    crossCorrelation!( FFT(), cmat, padf, padg, plan, iplan );
    Base.circshift!( shifted, cmat, shifts )

	# Constant denominator
	N = prod(sizeG);
	denG = stdG*sqrt(N);

	# Variable denominator for each translation
	fh, fw, fd = sizeF
	gh, gw, gd = sizeG .- 1
	off        = sizeF .- sizeG .+ 1 # = 2*searchMargin + 1

    for z in 0:size(cmat,3)-1;         #z1 = max( 1, fd - z ); z2 = min( fd, z1 + gd )
                                       z3 = max( 1 ,min(off[3],fd-z)); z4 = z3 + gd;
		for c in 0:size(cmat,2)-1;     #c1 = max( 1, fw - c ); c2 = min( fw, c1 + gw )
                                       c3 = max( 1 ,min(off[2],fw-c)); c4 = c3 + gw;
			for r in 0:size(cmat,1)-1; #r1 = max( 1, fh - r ); r2 = min( fh, r1 + gh )
									   r3 = max( 1 ,min(off[1],fh-r)); r4 = r3 + gh;

				sumF2 = integralArea( intArr2, (r3-1,c3-1,z3-1), (r4,c4,z4) )
				sumF2 = ( sumF2 <= 0.0 ) ? Inf : sumF2;
                cmat[ r+1, c+1, z+1 ] = shifted[ r+1, c+1, z+1 ]/( sqrt( sumF2 )*denG );
	end	end end
end

function PIV_3D( ::ZNCC, vol1::A{T,3}, vol2::A{T,3},
                         IA::III, SM::III, overlap::III, mpass::I, width::I,
                         peak::S, sigNoise::S, filtFun::Function, threshold::F ;
                         corrType=Float32, vfType=Float32
			   ) where {T<:Real}

    step   = IA  .-  overlap;
    vfSize = length.( StepRange.( IA, step, size(vol1) ) );

    U  = zeros( vfType, vfSize );
    V  = zeros( vfType, vfSize );
    W  = zeros( vfType, vfSize );
    SN = zeros( vfType, vfSize );
	df = zeros( vfType, vfSize );

	ignoreSN = sigNoise == "";

    @inbounds for mp in mpass:-1:1
        last_mp = ( mp == 1 );

        # Scaling IA, SM and step (overlap) to multi-pass iteration.
        IA_mp    =  IA  .* mp;
        SM_mp    =  SM  .* mp;
        step_mp  = step .* mp;
		IAranges = StepRange.( IA_mp, step_mp, size(vol1) )

		# Initializing integral arrays for computing ZNCC
        ssize   = IA_mp .+ 2 .* SM_mp
        intArr2 = zeros( corrType, ssize .+ 1 );

        # Initialize cross-correlation variables once per multi-pass iteration
        csize   = 2 .* ( IA_mp .+ SM_mp  );
        cmatrix = zeros( corrType, csize );
        shifted = zeros( corrType, csize );
        shifts  = div.(csize,2) .+ SM_mp .- 1;
        pads    = zeros( Complex{corrType}, csize );
        padi    = zeros( Complex{corrType}, csize );
        plan    =  FFTW.plan_fft!( pads );
        iplan   = FFTW.plan_ifft!( pads );

		# Nested loop establishing IV and UVW coordinates
		vfz = [ 1-mp, 0 ]
		for z2 in IAranges[3];         z1 = z2-IA_mp[3]+1; vfz .+= mp; vfx = [ 1-mp, 0 ];
			for x2 in IAranges[2];     x1 = x2-IA_mp[2]+1; vfx .+= mp; vfy = [ 1-mp, 0 ];
				for y2 in IAranges[1]; y1 = y2-IA_mp[1]+1; vfy .+= mp;

					# 0-. Filtering undesirable IAs, ex background
					interr = view( vol1, y1:y2, x1:x2, z1:z2 )

					if filtFun( interr ) < threshold
						SN[ vfy[1]:vfy[2], vfx[1]:vfx[2], vfz[1]:vfz[2] ] .= -1.0
						continue;
					end

				    # 1-. Previously computed displacements shift the search area during multipass
				    u = round(Int32, U[ vfy[1], vfx[1], vfz[1] ]);
				    v = round(Int32, V[ vfy[1], vfx[1], vfz[1] ]);
				    w = round(Int32, W[ vfy[1], vfx[1], vfz[1] ]);

					# 1.2-. Search volume coordinates after shifting.
					scoords, off = SAcoords( (y1,x1,z1), (y2,x2,z2), (u,v,w), SM_mp, size(vol1) );

					# 1.3-. Computing the mean and std of IA and mean and mean^2 of SA
					meanI, stdI = meanStd( interr )

					meanS = 0.0
					@inbounds for z in z1:z2, x in x1:x2
						@simd for y in y1:y2
							meanS += vol2[y,x,z]
					end	end
					meanS = meanS/length(vol2)

					# 1.4-. Copying IA - meanI and SA - meanS into the padded arrays for FFT
					setTo0!( pads, padi )
					putWithinPadded!( pads, vol2, meanS, off, scoords );
					putWithinPadded!( padi, vol1, meanI, (0,0,0), (y1,y2,x1,x2,z1,z2) );

					# 1.5-. Computing integral array and integral array ^2
					setTo0!( intArr2 )
					integralArraySQ!( pads, intArr2 )

				    # 2-. Cross-Correlation
				    crossCorrelation!( ZNCC(), cmatrix, shifted, shifts, pads, padi, plan, iplan,
				                       intArr2, stdI, ssize, IA_mp );

				    # 3-. Extracting the displacement
				    ( r, c, z ) = approxTranslation( shifted, peak, Val(last_mp) )

					# 3.2 -. Computing signal to noise ration, if needed
		 			if ( !ignoreSN && last_mp )
						snres = SNRatio( shifted, sigNoise, width )
				    	SN[ vfy[1]:vfy[2], vfx[1]:vfx[2], vfz[1]:vfz[2] ] .= snres

					end

				    # 4-. Updating U, V, W matrices
				    U[ vfy[1]:vfy[2], vfx[1]:vfx[2], vfz[1]:vfz[2] ] .= u - r;
				    V[ vfy[1]:vfy[2], vfx[1]:vfx[2], vfz[1]:vfz[2] ] .= v - c;
				    W[ vfy[1]:vfy[2], vfx[1]:vfx[2], vfz[1]:vfz[2] ] .= w - z;
				   df[ vfy[1]:vfy[2], vfx[1]:vfx[2], vfz[1]:vfz[2] ] .= maxval(cmatrix)
		end	end	end
    end # Multi-pass loop

    return U, V, W, SN, df
end

""" ZNCC out of place CROSS CORRELATION """

function crossCorrelation( ::ZNCC, g::A{<:Real,N}, f::A{<:Real,N}; corrType=Float32) where {N}

    sizef  = size( f );
    sizeg  = size( g );

    csize   = sizef .+ sizeg;
	shifts  = div.( csize, 2 ) .+ div.( size(f) .- size(g), 2 ) .- 1;

    corr    = zeros( corrType, csize );
    shifted = zeros( corrType, csize );
    padf    = zeros( Complex{corrType}, csize );
    padg    = zeros( Complex{corrType}, csize );
    plan    =  plan_fft!( padf );
    iplan   = plan_ifft!( padf );

    meang, stdg = meanStd( g )
    meanf = Statistics.mean( f );

    putWithinPadded!( padf, f, meanf, (0,0,0), (1,size(f,1),1,size(f,2),1,size(f,3)) );
    putWithinPadded!( padg, g, meang, (0,0,0), (1,size(g,1),1,size(g,2),1,size(g,3)) );

    sumf2 = zeros( corrType, sizef .+ 1 );
    integralArraySQ!( padf, sumf2 );

    crossCorrelation!( ZNCC(), corr, shifted, shifts, padf, padg, plan, iplan,
                               sumf2, stdg, sizef, sizeg );

    return corr;
end

max_issues_repo_name: ErichZimmer/quickPIV

max_forks_repo_name: ErichZimmer/quickPIV


text:
using RipsererPrep
using Test

@testset "RipsererPrep.jl" begin
    # Write your tests here.
end


text:
@test check_derivative(x -> sin(x), x -> cos(x), 0.0) < 10e-4
@test check_derivative(x -> sin(x), x -> cos(x), 1.0) < 10e-4
@test check_derivative(x -> sin(x), x -> cos(x), 10.0) < 10e-4
@test check_derivative(x -> sin(x), x -> cos(x), 100.0) < 10e-4
@test check_derivative(x -> sin(x), x -> cos(x), 1000.0) < 10e-4

@test check_gradient(x -> sin(x[1]) + cos(x[2]), x -> [cos(x[1]), -sin(x[2])], [0.0, 0.0]) < 10e-4
@test check_gradient(x -> sin(x[1]) + cos(x[2]), x -> [cos(x[1]), -sin(x[2])], [1.0, 1.0]) < 10e-4
@test check_gradient(x -> sin(x[1]) + cos(x[2]), x -> [cos(x[1]), -sin(x[2])], [10.0, 10.0]) < 10e-4
@test check_gradient(x -> sin(x[1]) + cos(x[2]), x -> [cos(x[1]), -sin(x[2])], [100.0, 100.0]) < 10e-4
@test check_gradient(x -> sin(x[1]) + cos(x[2]), x -> [cos(x[1]), -sin(x[2])], [1000.0, 1000.0]) < 10e-4

@test check_second_derivative(x -> sin(x), x -> -sin(x), 0.0) < 10e-4
@test check_second_derivative(x -> sin(x), x -> -sin(x), 1.0) < 10e-4
@test check_second_derivative(x -> sin(x), x -> -sin(x), 10.0) < 10e-4
@test check_second_derivative(x -> sin(x), x -> -sin(x), 100.0) < 10e-4
@test check_second_derivative(x -> sin(x), x -> -sin(x), 1000.0) < 10e-4

@test check_hessian(x -> sin(x[1]) + cos(x[2]), x -> [-sin(x[1]) 0.0; 0.0 -cos(x[2])], [0.0, 0.0]) < 10e-4
@test check_hessian(x -> sin(x[1]) + cos(x[2]), x -> [-sin(x[1]) 0.0; 0.0 -cos(x[2])], [1.0, 1.0]) < 10e-4
@test check_hessian(x -> sin(x[1]) + cos(x[2]), x -> [-sin(x[1]) 0.0; 0.0 -cos(x[2])], [10.0, 10.0]) < 10e-4
@test check_hessian(x -> sin(x[1]) + cos(x[2]), x -> [-sin(x[1]) 0.0; 0.0 -cos(x[2])], [100.0, 100.0]) < 10e-4
@test check_hessian(x -> sin(x[1]) + cos(x[2]), x -> [-sin(x[1]) 0.0; 0.0 -cos(x[2])], [1000.0, 1000.0]) < 10e-4


text:
using MacroTools
macro wildprop(e)
    if e.head != :(=) || length(e.args) != 2 || !(e.args[1] isa AbstractString)
        error("expected AbstractString = value")
    end
    keys = Symbol[Symbol(e.args[1])]
    esc(:(NamedTuple{Tuple($(keys))}(Tuple(Any[$(e.args[2])]))...))
end

function parse_props(s)
    function make_prop(part)
        m = match(r"^(?<id>[A-Za-z]+[\w\-\:\.]*)\.(?<prop>[A-Za-z]+[\w\-\:\.]*)$", strip(part))
        if isnothing(m)
            error("expected <id>.<property>[,<id>.<property>...] in $(part)")
        end

        return (Symbol(m[:id]), Symbol(m[:prop]))
    end

    props_parts = split(s, ",", keepempty = false)

    return map(props_parts) do part
        return make_prop(part)
    end
end

"""
    @callid_str"

Macro for crating Dash CallbackId.
Parse string in form "[{State1[, ...]}] Input1[, ...] => Output1[, ...]"

#Examples
```julia
    id1 = callid"{inputDiv.children} input.value => output1.value, output2.value"
```
"""
macro callid_str(s)
    rex = r"(\{(?<state>.*)\})?(?<input>.*)=>(?<output>.*)"ms
    m = match(rex, s)
    if isnothing(m)
        error("expected {state} input => output")
    end
    input = parse_props(strip(m[:input]))
    output = parse_props(strip(m[:output]))
    state = isnothing(m[:state]) ? Vector{IdProp}() : parse_props(strip(m[:state]))
    return CallbackId(state, input, output)
end


text:
struct PbClosure{T<:Tuple}
    pbs::T
end

function PbClosure_impl(x::Type{PbClosure{T}}, y::Type{Ty}) where {T,Ty}
    # Number of layers (pullbacks)
    N = length(T.parameters)

    pb_vars = [Symbol("∂Ȳ$i") for i=1:N]
    # sensitivity propagated by layers (ȳ_end+1 = 1)
    ȳ_vars  = [Symbol("ȳ$i") for i=1:N+1]
    ȳ_vars[end] = Symbol("y")
    # resulting gradient for layers
    ∇y_vars = [Symbol("∇y$i") for i=1:N]

    expr = Expr(:block)

    for i=N:-1:1
        pb_i = :(getfield(pb.pbs, $i))
        expr_i = :(($(∇y_vars[i]), $(ȳ_vars[i])) = $(pb_i)($(ȳ_vars[i+1])))
        push!(expr.args, expr_i)
    end

    push!(expr.args, :(∂chain = tuple($(∇y_vars...))))
    push!(expr.args, :(return (∂chain, $(ȳ_vars[1]))))

    return expr
end

@generated function (pb::PbClosure{A})(y::B) where {A,B}
    return PbClosure_impl(pb, y)
end