text:
#################################################################
#                                                               #
#    This file provides functions for converting .pwf into      #
#              PowerModels.jl data structure                    #
#                                                               #
#################################################################

# This parser was develop using ANAREDE v09' user manual and PSSE
# .raw manual for references.

# This converter uses Organon HPPA raw - pwf converter as benchmark

const bus_type_num_to_str    = Dict(1 => "PQ", 2 => "PV", 3 => "Vθ", 4 => "OFF")
const bus_type_str_to_num    = Dict("PQ" => 1, "PV" => 2, "Vθ" => 3, "OFF" => 4)
const bus_type_pwf_to_raw    = Dict(0 => 1, 1 => 2, 2 => 3, 3 => 1)
const bus_type_raw_to_pwf    = Dict(1 => 0, 2 => 1, 3 => 2)
const element_status         = Dict(0 => "OFF", "D" => "OFF", 1 => "ON", "L" => "ON")

function _parse_pwf_to_powermodels(pwf_data::Dict; validate::Bool=true, software = ANAREDE, add_control_data::Bool=false)
    software = software()
    pm_data = Dict{String,Any}()

    pm_data["per_unit"] = false
    pm_data["source_type"] = "pwf"
    pm_data["source_version"] = "09"
    pm_data["name"] = pwf_data["name"]

    pm_data["baseMVA"] = _handle_base_mva(pwf_data)

    _pwf2pm_bus!(pm_data, pwf_data, add_control_data = add_control_data)
    _pwf2pm_branch!(pm_data, pwf_data, add_control_data = add_control_data)
    _pwf2pm_load!(pm_data, pwf_data)
    _pwf2pm_generator!(pm_data, pwf_data)
    _pwf2pm_transformer!(pm_data, pwf_data, add_control_data = add_control_data)
    _pwf2pm_dcline!(pm_data, pwf_data)
    _pwf2pm_shunt!(pm_data, pwf_data, add_control_data = add_control_data)

    if add_control_data
        _pwf2pm_info!(pm_data, pwf_data)
    end

    # ToDo: fields not yet contemplated by the parser

    pm_data["storage"] = Dict{String,Any}()
    pm_data["switch"] = Dict{String,Any}()

    # Apply corrections in the pm_data accordingly to the specified software
    _pwf2pm_corrections!(pm_data, pwf_data, software)

    if validate
        _correct_pwf_network_data(pm_data)
        PowerModels.correct_network_data!(pm_data)
    end

    return pm_data
end

"""
    parse_pwf_to_powermodels(filename::String, validate::Bool=false)::Dict

Parse .pwf file directly to PowerModels data structure
"""
function parse_pwf_to_powermodels(filename::String; validate::Bool=true, software = ANAREDE, add_control_data::Bool=false)
    pwf_data = open(filename) do f
        parse_pwf(f)
    end

    # Parse Dict to a Power Models format
    pm = _parse_pwf_to_powermodels(pwf_data, validate = validate, software = software, add_control_data = add_control_data)
    return pm
end

"""
    parse_pwf_to_powermodels(io::Io, validate::Bool=false)::Dict

"""
function parse_pwf_to_powermodels(io::IO; validate::Bool=true, software = ANAREDE, add_control_data::Bool=false)
    pwf_data = _parse_pwf_data(io)

    # Parse Dict to a Power Models format
    pm = _parse_pwf_to_powermodels(pwf_data, validate = validate, software = software, add_control_data = add_control_data)
    return pm
end


text:
function model1dhemo!(yout::Vector{Float64},children::Vector{Int64},Ph::Float64,
    beta::Vector{Float64},rho::Float64,c0::Vector{Float64},A0::Vector{Float64},
    h::Float64,W1::Float64,W2 = [0.],V = 0.,Q = 0.)

    if ~isempty(children) # bifurcation downstream
        yout[1] = (Ph./beta[1] .+ sqrt.(A0[1])).^2;
        yout[2] = W1 .- 8.*((yout[1].*(0.5.*beta[1]./rho).^2).^0.25 .- c0[1]);
        yout[3] = 0.5.*yout[1].*(W1 .+ yout[2]);
        # system.branches.A[ID][system.solverparams.JL,n+2] = (system.hemo.Ph/
        #     system.branches.beta[ID][end]+sqrt(system.branches.A0[ID][end]))^2;
        # system.branches.W2[ID] = system.branches.W1[ID]-
        #     8*((system.branches.A[ID][system.solverparams.JL,n+2]*(system.branches.beta[ID][end]/
        #     (2*system.solverparams.rho))^2)^0.25-system.branches.c0[ID][end]);
        # system.branches.Q[ID][system.solverparams.JL,n+2] = 0.5*
        #     system.branches.A[ID][system.solverparams.JL,n+2]*(system.branches.W1[ID]+
        #     system.branches.W2[ID])
        yout[4] = yout[3].*h;
    else # terminal downstream
        yout[1] = (Ph./beta[1] .+ sqrt.(A0[1])).^2;
        W2 = W1 .- 8.*((yout[1].*(0.5.*beta[1]./rho).^2).^0.25 .- c0[1]);
        yout[2] = 0.5.*yout[1].*(W1 .+ W2);
        # system.branches.A[ID][system.solverparams.JL,n+2] = (system.hemo.Ph/
        #     system.branches.beta[ID][end]+sqrt(system.branches.A0[ID][end]))^2;
        # W2 = system.branches.W1end[ID]-
        #     8*((system.branches.A[ID][system.solverparams.JL,n+2]*(system.branches.beta[ID][end]/
        #     (2*system.solverparams.rho))^2)^0.25-system.branches.c0[ID][end]);
        # system.branches.Q[ID][system.solverparams.JL,n+2] = 0.5*
        #     system.branches.A[ID][system.solverparams.JL,n+2]*(system.branches.W1[ID]+
        #     W2)
        yout[3] = yout[2].*h;
    end

    # system.hemo.Vloss += system.branches.Q[ID][system.solverparams.JL,n+2]*
    #     system.solverparams.h;

    if ~isempty(children) # bifurcation downstream
        for i = 1:length(children)
            cID = children[i];
            yout[5+3*(i-1)] = (Ph./beta[i+1] .+ sqrt.(A0[i+1])).^2;
            yout[6+3*(i-1)] = W2[i] + 8.*((yout[5+3*(i-1)].*(0.5.*beta[i+1]./rho).^2)^0.25 .- c0[i+1]);
            yout[7+3*(i-1)] = 0.5.*yout[5+3*(i-1)].*(yout[6+3*(i-1)] + W2[i]);
            yout[4] += yout[7+3*(i-1)].*h;
            # system.branches.A[cID][1,n+2] = (system.hemo.Ph/system.branches.beta[cID][end]+
            #     sqrt(system.branches.A0[cID][end]))^2;
            # system.branches.W1[cID] = system.branches.W2[cID]+8*((system.branches.A[cID][1,n+2]*
            #     (system.branches.beta[cID][end]/(2*system.solverparams.rho))^2)^0.25-
            #     system.branches.c0[cID][end]);
            # system.branches.Q[cID][1,n+2] = 0.5*system.branches.A[cID][1,n+2]*
            #     (system.branches.W1[cID]+system.branches.W2[cID]);
            # system.hemo.Vloss += -system.branches.Q[cID][1,n+2]*system.solverparams.h;
        end
    else # terminal compartments downstream
        yout[4] = V;
        yout[5] = Ph;
        yout[3] += -Q.*h;
        # system.branches.term[ID].V[n+2,1] = system.branches.term[ID].V[n+1,1]; # keep V constant (no pressure gradient to force out accumulating backflow)
        # system.branches.term[ID].P[n+2,1] = system.hemo.Ph;
        # system.hemo.Vloss += -system.branches.term[ID].Q[1,n+1]*system.solverparams.h;
    end

end

ext: jl

max_stars_repo_name: dcanuto/CardioModeling

max_issues_repo_name: dcanuto/CardioModeling

max_forks_repo_name: dcanuto/CardioModeling


text:
# Buckets implementation for the cuckoo filter

using Base.Iterators: enumerate

struct Bucket{F}
    buffer :: Vector{F}
end

Bucket{F}() where F = Bucket{F}(Vector{F}(undef, 0))

Base.length(b::Bucket) = length(b.buffer)
Base.in(x, b::Bucket) = x ∈ b.buffer
Base.insert!(b::Bucket, x) = append!(b.buffer, x)

function Base.delete!(b::Bucket, key)
    for (i, x) in enumerate(b.buffer)
        if x == key
            deleteat!(b.buffer, i)
            return true
        end
    end

    false
end

isfull(b::Bucket, max_size) = (length(b) ≥ max_size)


text:
# ---
# title: 1460. Make Two Arrays Equal by Reversing Sub-arrays
# id: problem1460
# author: Tian Jun
# date: 2020-10-31
# difficulty: Easy
# categories: Array
# link: <https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/description/>
# hidden: true
# ---
#
# Given two integer arrays of equal length `target` and `arr`.
#
# In one step, you can select any **non-empty sub-array** of `arr` and reverse
# it. You are allowed to make any number of steps.
#
# Return _True_ if you can make `arr` equal to `target`, or _False_ otherwise.
#
#
#
# **Example 1:**
#
#
#
#     Input: target = [1,2,3,4], arr = [2,4,1,3]
#     Output: true
#     Explanation: You can follow the next steps to convert arr to target:
#     1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]
#     2- Reverse sub-array [4,2], arr becomes [1,2,4,3]
#     3- Reverse sub-array [4,3], arr becomes [1,2,3,4]
#     There are multiple ways to convert arr to target, this is not the only way to do so.
#
#
# **Example 2:**
#
#
#
#     Input: target = [7], arr = [7]
#     Output: true
#     Explanation: arr is equal to target without any reverses.
#
#
# **Example 3:**
#
#
#
#     Input: target = [1,12], arr = [12,1]
#     Output: true
#
#
# **Example 4:**
#
#
#
#     Input: target = [3,7,9], arr = [3,7,11]
#     Output: false
#     Explanation: arr doesn't have value 9 and it can never be converted to target.
#
#
# **Example 5:**
#
#
#
#     Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]
#     Output: true
#
#
#
#
# **Constraints:**
#
#   * `target.length == arr.length`
#   * `1 <= target.length <= 1000`
#   * `1 <= target[i] <= 1000`
#   * `1 <= arr[i] <= 1000`
#
#
## @lc code=start
using LeetCode

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


text:
using OrdinaryDiffEq, Test
prob = ODEProblem((u,p,t)->1.01u,0.5,(0.0,1.0), save_start=false, save_end=false)
function prob_func(prob,i,repeat)
  remake(prob,u0=rand()*prob.u0)
end
ensemble_prob = EnsembleProblem(prob,prob_func=prob_func)
sim = solve(ensemble_prob,Tsit5(),EnsembleThreads(),trajectories=10, save_everystep=false)
@test ndims(sim) == 2
@test length(sim) == 10
ts = 0.0:0.1:1.0

using SciMLBase.EnsembleAnalysis
sim = solve(ensemble_prob,Tsit5(),EnsembleThreads(),trajectories=10,saveat=0.1)
timeseries_point_meancov(sim,ts)


text:
"""
    mutable struct Context
A contextual data object that hosts OpenGL handles.
"""
Base.@kwdef mutable struct Context
    GlslVersion = 150
    FontTexture = GLuint(0)
    ShaderHandle = GLuint(0)
    VertHandle = GLuint(0)
    FragHandle = GLuint(0)
    AttribLocationTex = GLint(0)
    AttribLocationProjMtx = GLint(0)
    AttribLocationVtxPos = GLint(0)
    AttribLocationVtxUV = GLint(0)
    AttribLocationVtxColor = GLint(0)
    VboHandle = GLuint(0)
    ElementsHandle = GLuint(0)
    ImageTexture = Dict{Int,GLuint}()
end

"""
    create_context(glsl_version=150)
Return a OpenGL backend contextual data object.
"""
create_context(glsl_version=150) = Context(; GlslVersion=glsl_version)


text:
@kernel function rt_interaction!(R⁻⁺_, T⁺⁺_, R⁺⁻_, T⁻⁻_, r⁻⁺_, t⁺⁺_, r⁺⁻_, t⁻⁻_, aux1_, aux2_, aux3_, pivot_, n)
    N = @index(Global)

    # Views:
    R⁻⁺   = view(R⁻⁺_, :, :, N)
    T⁺⁺   = view(T⁺⁺_, :, :, N)
    R⁺⁻   = view(R⁺⁻_, :, :, N)
    T⁻⁻   = view(T⁻⁻_, :, :, N)
    r⁻⁺   = view(r⁻⁺_, :, :, N)
    t⁺⁺   = view(t⁺⁺_, :, :, N)
    r⁺⁻   = view(r⁺⁻_, :, :, N)
    t⁻⁻   = view(t⁻⁻_, :, :, N)
    aux1  = view(aux1_, :, :, N)
    aux2  = view(aux2_, :, :, N)
    aux3  = view(aux3_, :, :, N)
    pivot = view(pivot_, :,  N)

    # Compute M1 = (I - R⁺⁻ * r⁻⁺) \ T⁺⁺
    mat_multiply!(aux1, R⁺⁻, r⁻⁺,n)                 # aux1  =  R⁺⁻ * r⁻⁺
    eye_minus_matrix!(aux1,n)                       # aux1  = (I - R⁺⁻ * r⁻⁺)
    LU_decomposition!(aux1, pivot, n)
    LU_solve!(aux1, T⁺⁺, aux2, aux3, pivot, n)     # aux2 = (I - R⁺⁻ * r⁻⁺) \ T⁺⁺

    # Compute t_R⁻⁺ = R⁻⁺ + T⁻⁻ * r⁻⁺ * M1
    mat_multiply!(aux1, r⁻⁺, aux2,n)   # r⁻⁺ * M1
    mat_multiply!(aux3, T⁻⁻, aux1,n)   # T⁻⁻ * r⁻⁺ * M1
    mat_add!(R⁻⁺,aux3,n)               # t_R⁻⁺ = R⁻⁺ + T⁻⁻ * r⁻⁺ * M1

    # t_T⁺⁺ = t⁺⁺ * M1
    mat_multiply!(T⁺⁺, t⁺⁺, aux2,n)

    # Repeating for mirror-reflected directions
    # Compute M1 = (I - r⁻⁺ * R⁺⁻) \ t⁻⁻
    mat_multiply!(aux1, r⁻⁺, R⁺⁻,n)              # r⁻⁺ * R⁺⁻
    eye_minus_matrix!(aux1,n)                    # (I - r⁻⁺ * R⁺⁻)
    LU_decomposition!(aux1, pivot, n)
    LU_solve!(aux1, t⁻⁻, aux2, aux3, pivot, n)  # aux2 = (I - r⁻⁺ * R⁺⁻) \ t⁻⁻

    # t_R⁺⁻ = r⁺⁻ + t⁺⁺ * R⁺⁻ * M1
    mat_multiply!(aux3, R⁺⁻, aux2,n)   # R⁺⁻ * M1
    mat_multiply!(aux1, t⁺⁺, aux3,n)   # t⁺⁺ * R⁺⁻ * M1
    mat_add!(R⁺⁻, r⁺⁻, aux1,n)     # t_R⁺⁻ = r⁺⁻ + t⁺⁺ * R⁺⁻ * M1

    # t_T⁻⁻ = T⁺⁺ * M1
    mat_multiply!(T⁻⁻, T⁺⁺, aux2,n)
end

@kernel function rt_interaction_rup!(R⁻⁺_, T⁺⁺_, R⁺⁻_, T⁻⁻_, r⁻⁺_, t⁺⁺_, r⁺⁻_, t⁻⁻_,aux1_,aux2_,aux3_)
    N = @index(Global)
    # Views:
    R⁻⁺   = view(R⁻⁺_, :, :, N)
    T⁺⁺   = view(T⁺⁺_, :, :, N)
    R⁺⁻   = view(R⁺⁻_, :, :, N)
    T⁻⁻   = view(T⁻⁻_, :, :, N)
    r⁻⁺   = view(r⁻⁺_, :, :, N)
    t⁺⁺   = view(t⁺⁺_, :, :, N)
    r⁺⁻   = view(r⁺⁻_, :, :, N)
    t⁻⁻   = view(t⁻⁻_, :, :, N)
    aux1   = view(aux1_, :, :, N)
    aux2   = view(aux2_, :, :, N)
    aux3   = view(aux3_, :, :, N)
    rt_interaction!(R⁻⁺, T⁺⁺, R⁺⁻, T⁻⁻, r⁻⁺, t⁺⁺, r⁺⁻, t⁻⁻,aux1,aux2,aux3)
end

function mat_eye_minus!(out::AbstractArray{FT,3}) where {FT}
    out = -out
    for k=1:size(out,3)
        out[:,:,k] += I
    end
end
"Allocation free matrix multiplication"
function eye_minus_matrix!(out::AbstractArray{FT,3}) where {FT}
    @inbounds begin
        for k=1:size(out,3)
            for i = 1:size(out,2) # for each column but the last
                for j=1:size(out,2)
                    out[j,i] = -out[j,i]
                end
                out[i,i] += 1
            end
        end
    end
end

function rt_interaction_GPU!(R⁻⁺, T⁺⁺, R⁺⁻, T⁻⁻, r⁻⁺, t⁺⁺, r⁺⁻, t⁻⁻, aux1, aux2, aux3,I_static)

    # Compute M1 = (I - R⁺⁻ * r⁻⁺) \ T⁺⁺
    aux2 = CUBLAS.gemm_strided_batched('N','N',R⁺⁻, r⁻⁺) #mat_multiply!(aux1, R⁺⁻, r⁻⁺,n)                 # aux1  =  R⁺⁻ * r⁻⁺
    aux2 = I_static - aux2

    pivot, info      = CUBLAS.getrf_strided_batched!(aux2, true)
    getri_strided_batched(aux2, aux1, pivot) # inv stored in aux1
    aux2 = CUBLAS.gemm_strided_batched('N','N',aux1,T⁺⁺)  # inv(I - R⁺⁻ * r⁻⁺) * T⁺⁺

    # Compute t_R⁻⁺ = R⁻⁺ + T⁻⁻ * r⁻⁺ * M1
    aux1 = CUBLAS.gemm_strided_batched('N','N',r⁻⁺, aux2)  # r⁻⁺ * M1
    aux3 = CUBLAS.gemm_strided_batched('N','N',T⁻⁻, aux1)  #
    R⁻⁺ = R⁻⁺ + aux3

    # t_T⁺⁺ = t⁺⁺ * M1
    T⁺⁺ = CUBLAS.gemm_strided_batched('N','N',t⁺⁺, aux2)

    # Repeating for mirror-reflected directions
    # Compute M1 = (I - r⁻⁺ * R⁺⁻) \ t⁻⁻
    aux2 = CUBLAS.gemm_strided_batched('N','N',r⁻⁺, R⁺⁻)
    aux2 = I_static -aux2
    pivot, info      = CUBLAS.getrf_strided_batched!(aux2, true)
    getri_strided_batched(aux2, aux1, pivot) # inv stored in aux1
    aux2 = CUBLAS.gemm_strided_batched('N','N',aux1,t⁻⁻)

    # t_R⁺⁻ = r⁺⁻ + t⁺⁺ * R⁺⁻ * M1
    aux3 = CUBLAS.gemm_strided_batched('N','N',R⁺⁻, aux2)
    aux1 = CUBLAS.gemm_strided_batched('N','N',t⁺⁺, aux3)
    R⁺⁻ =  r⁺⁻ + aux1
    T⁻⁻ = CUBLAS.gemm_strided_batched('N','N',T⁺⁺, aux2)
end


text:
using Base.Test
using Meganet
using LinearOperators

nImg = [8,10]
sK   = [3,3,2,4]
for TYPE=[Float64,Float32]
    K = getConvGEMMKernel(TYPE,nImg,sK)

    @testset  "adjoint test $TYPE" begin
	nex = 2;
    theta = initTheta(K)
    A     = getOp(K,theta);
    v     = randn(TYPE,nFeatIn(K),nex)
    w     = randn(TYPE,nFeatOut(K),nex)

    t1    = dot(w,A*v)
    t2    = dot(v,A'*w)
    # println("adjointTest t1=$t1\t t2=$t2")
    @test norm(t1-t2)/norm(t1) < 1e3*eps(TYPE)
    end

    @testset "derivative Test" begin
    th  = initTheta(K);
    dth = initTheta(K);
    nex = 2;
    Y  = randn(TYPE,nFeatIn(K),nex);
    Z  = randn(TYPE,nFeatOut(K),nex);

    t1 = vec(Z)'*vec(Jthetamv(K,dth,th,Y));
    t2 = vec(dth)'*vec(JthetaTmv(K,Z,th,Y));
    # println("derivativeTest t1=$t1\t t2=$t2")
    @test norm(t1-t2)/norm(t2) < 1e3*eps(TYPE)
    end
end


text:
using Dates
using ArgParse
using Printf
using Random
using GaussianProcesses

# before_all = Dates.now()

include("../../btg.jl")
s = ArgParseSettings()
# The defaut setting: --test: multiple length scale, QMC
@add_arg_table! s begin
    "--p"
        help = "degree of covariate function"
        arg_type = Int
        default = 1
    "--ntrain"
        help = "number of training points"
        arg_type = Int
        default = 8
    "--ntest"
        help = "number of testing points"
        arg_type = Int
        default = 50
    "--noiselevel"
        help = "noise level in observation"
        arg_type = Int
        default = 1
    "--lmin"
        help = "minimal length scale"
        arg_type = Float64
        default = 0.5
    "--lmax"
        help = "maximum length scale"
        arg_type = Float64
        default = 2.
    "--randseed"
        help = "noise level in observation"
        arg_type = Int
        default = 1234
end
parsed_args = parse_args(ARGS, s)

function covariate_fun(x, p)
    n = size(x, 1)
    d = size(x, 2)
    if p == 1
        return ones(n, 1)
    elseif p == 1 + d
        return hcat(ones(n), x)
    else
        throw(ArgumentError("Only support constant or linear convariate."))
    end
end

true_fun(x, s) = sin(x) + s*randn() + 3
true_fun_noise(x) = max(true_fun(x, 1e-1), 0)^1/3
true_fun_0(x) = true_fun(x, 0.)^1/3

# training set
randseed = parsed_args["randseed"]; rng = MersenneTwister(randseed)
n_train = parsed_args["ntrain"]
data = range(-pi, stop=pi, length=n_train)
# data = 2pi .* rand(n_train) .- pi
target = (sin.(data) .+ 0.1 * parsed_args["noiselevel"].* randn(rng, n_train) .+ 10).^(1/3)
x = reshape(data, n_train, 1)
Fx = covariate_fun(x, parsed_args["p"])
max_train = maximum(target)
y = target ./ max_train
trainingData0 = trainingData(x, Fx, y)
d = getDimension(trainingData0); n = getNumPts(trainingData0); p = getCovDimension(trainingData0)
# testing set
n_test = parsed_args["ntest"]
x_test = range(-pi, stop=pi, length=n_test)
x_test = reshape(x_test, n_test, 1)
Fx_test = covariate_fun(x_test, parsed_args["p"])
y_test_true = (sin.(x_test) .+ 10).^(1/3)
elapsedmin = 0

#parameter setting
# myquadtype = parsed_args["sparse"] ? ["SparseCarlo", "SparseCarlo"] : ["QuasiMonteCarlo", "QuasiMonteCarlo"]
myquadtype = ["Gaussian", "Gaussian"]
#rangeλ = [-1.5 1.]
rangeλ = reshape([0], 1, 1)
lmin = parsed_args["lmin"]
lmax = parsed_args["lmax"]
rangeθ = [1/lmax^2 1/lmin^2]
@info "rangeθ, rangel:" rangeθ, [lmin lmax]
# rangeθ = [0.111 25]
# build btg model
btg0 = btg(trainingData0, rangeθ, rangeλ; quadtype = myquadtype)
(pdf0_raw, cdf0_raw, dpdf0_raw, quantInfo0_raw) = solve(btg0);

####################################
############### Test ###############
####################################

@info "Start Test"
before = Dates.now()
count_test = 0
error_abs = 0.
error_sq = 0.
nlpd = 0.
id_fail = []
id_nonproper = []
CI_set = zeros(n_test, 2)
median_set = zeros(n_test)
for i in 1:n_test
    global error_abs, error_sq, nlpd, count_test
    # mod(i, 20) == 0 ? (@info i) : nothing
    # @info "i" i
    x_test_i = reshape(x_test[i, :], 1, d)
    Fx_test_i = reshape(Fx_test[i, :], 1, p)
    try
        pdf_test_i, cdf_test_i, dpdf_test_i, quantbound_test_i, support_test_i = pre_process(x_test_i, Fx_test_i, pdf0_raw, cdf0_raw, dpdf0_raw, quantInfo0_raw)
        y_test_i_true = y_test_true[i]
        median_test_i = max_train * quantile(cdf_test_i, quantbound_test_i, support_test_i)[1]
        # @info "True, median " y_test_i_true, median_test_i
        median_set[i] = median_test_i
        try
            CI_test_i = max_train .* credible_interval(cdf_test_i, quantbound_test_i, support_test_i; mode=:equal, wp=.95)[1]
            count_test += (y_test_i_true >= CI_test_i[1])&&(y_test_i_true <= CI_test_i[2]) ? 1 : 0
            # @info "CI" CI_test_i
            @info CI_test_i
            CI_set[i, :] = CI_test_i
        catch err
            append!(id_fail, i)
        end
        error_abs += abs(y_test_i_true - median_test_i)
        error_sq += (y_test_i_true - median_test_i)^2
        nlpd += log(pdf_test_i(y_test_i_true/max_train))
    # @info "Count, id_fail" count_test, id_fail
    catch err
        append!(id_nonproper, i)
    end
    count_test /= n_test - length(id_fail) - length(id_nonproper)
    error_abs  /= n_test - length(id_nonproper)
    error_sq   /= n_test - length(id_nonproper)
    nlpd       /= -n_test - length(id_nonproper)
    after = Dates.now()
    elapsedmin = round(((after - before) / Millisecond(1000))/60, digits=5)

    # Plot
    PyPlot.close("all") #close existing windows
    PyPlot.plot(x_test, median_set, label = "BTG median")
    PyPlot.plot(x_test, y_test_true, label = "true")
    PyPlot.fill_between(dropdims(x_test; dims = 2), CI_set[:, 1], CI_set[:, 2], alpha = 0.3, label = "95% confidence interval")
    PyPlot.scatter(x, target, s = 10, c = "k", marker = "*")
    PyPlot.legend(fontsize=8)
    PyPlot.grid()
    PyPlot.title("BTG $myquadtype", fontsize=10)
    PyPlot.savefig("exp_synthetic_mle_btg3.pdf")
end

max_stars_repo_name: dbindel/btg

max_issues_repo_name: dbindel/btg

max_forks_repo_name: dbindel/btg


text:
#Network analysis tools
#-------------------------------------------------------------------------------
module NetwAnalysis

using CMDimCircuits.CircuitAnalysis
import CMDimCircuits.CircuitAnalysis: TImpedance, TAdmittance, TInductance, TCapacitance

import MDDatasets
import MDDatasets: DataMD
import MDDatasets: DS #To dispatch on a symbol & minimize namespace pollution

#Types that are meant to operate on network parameters:
const TNetIop = Union{DataMD,Number,Array}

include("base.jl")
include("npconvert.jl")
include("cktelements.jl")
include("gains.jl")
include("show.jl")

#==Exported symbols
===============================================================================#
#Objects
#-------------------------------------------------------------------------------
export Network
export NPType #Network parameter type

#Functions
#-------------------------------------------------------------------------------
export kstab, gain
export series, shunt
export vector_push #Vector{NwPar{Number}} => NwPar{Vector{Number}}
export vector_pull #NwPar{Vector{Number}} => Vector{NwPar{Number}}
export portcount
export mx2elem #Returns 2-port matrix elements as a tuple of elements in intuitive order
	#TODO: Find better name than mx2elem
export submatrix #Get subset of network parameter matrix

#==Other interface tools (symbols not exported to avoid collisions):
================================================================================
#Already in base:
	Base.Symbol(::NPType)
	Base.eltype(::NetworkParameters)
	Base.size(::NetworkParameters)
==#

#==Symbols *not* exported (useful for implementing custom functions)
===============================================================================#
#=
SParameters{NP, T}
TParameters{T}
ZParameters{NP, T}
YParameters{NP, T}
ABCDParameters{T}
=#

#Notation: z0: Reference impedance.  zC: Characteristic impedance
end #module NetwAnalysis


text:
using GridPotentialFlow
using Plots
Δx = 0.01
Lx = 2.0
xlim = (-Lx/2,Lx/2)
ylim = (-Lx/2,Lx/2)
g = PhysicalGrid(xlim,ylim,Δx);

c = Lx/2 # chord length
α = -π/6 # angle of attack
plate = Plate(c,4*cellsize(g))
Tr = RigidTransform((0.0,0.0),α)
Tr(plate)
pfb = PotentialFlowBody(plate);
model = VortexModel(g,bodies=[pfb]);

setU∞(model,(1.0,0.0))
sol = solve(model);

plot(sol.ψ,g,levels=60);
plot!(plate,linecolor=:black,linewidth=2,xlabel="x",ylabel="y")

plot(sol.f,xlabel="body point index",ylabel="f",legend=false)

ones = ScalarData(length(plate))
ones .= 1.0
f₀ = model.system.ibp.Sfact\ones
plot(f₀)

plot(sol.f./f₀,xlabel="body point index",ylabel="f̃",legend=false)

pfb = PotentialFlowBody(plate,edges=[length(plate)])
model = VortexModel(g,bodies=[pfb],U∞=(1.0,0.0))
sol = solve(model);

plot(sol.ψ,g);
plot!(plate,linecolor=:black,linewidth=2,xlabel="x",ylabel="y")

plot(plot(sol.f,xlabel="body point index",ylabel="f",legend=false),plot(sol.f./f₀,xlabel="body point index",ylabel="f̃",legend=false),size=[800,300])

Δt = 1e-2
vTE = Vortex(plate.x[end]+3*Δt*cos(α+π/2),plate.y[end]+3*Δt*sin(α+π/2),0.0);

pfb = PotentialFlowBody(plate,edges=[length(plate)])
model = VortexModel(g,bodies=[pfb],vortices=[vTE],U∞=(1.0,0.0))
sol = solve(model);
plot(sol.ψ,g);
plot!(plate,linecolor=:black,linewidth=2)
scatter!(model.vortices.x,model.vortices.y,color=:black,markersize=2,xlabel="x",ylabel="y")

plot(plot(sol.f,xlabel="body point index",ylabel="f",legend=false),plot(sol.f./f₀,xlabel="body point index",ylabel="f̃",legend=false),size=[800,300])

vLE = Vortex(plate.x[1]+3*Δt*plate.len*cos(plate.α+π/2),plate.y[1]+3*Δt*plate.len*sin(plate.α+π/2),0.0);
vTE = Vortex(plate.x[end]+3*Δt*cos(α+π/2),plate.y[end]+3*Δt*sin(α+π/2),0.0);

pfb = PotentialFlowBody(plate,edges=[1,length(plate)])
model = VortexModel(g,bodies=[pfb],vortices=[vLE,vTE],U∞=(1.0,0.0))
sol = solve(model);
plot(sol.ψ,g);
plot!(plate,linecolor=:black,linewidth=2)
scatter!(model.vortices.x,model.vortices.y,markersize=2,xlabel="x",ylabel="y")

plot(plot(sol.f,xlabel="body point index",ylabel="f",legend=false),plot(sol.f./f₀,xlabel="body point index",ylabel="f̃",legend=false),size=[800,300])

# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl


text:
module StaticExample

using Mixtape
import Mixtape: CompilationContext, transform, allow
using CodeInfoTools
using MacroTools

struct Mix <: CompilationContext end

module Rosenbrock

rosenbrock(x, y, a, b) = (a - x)^2 + b * (y - x^2)^2
fake() = rosenbrock(1, 1, 1, 1)

end

entry = jit(Rosenbrock.rosenbrock,
                    Tuple{Float64, Int, Int, Int};
                    opt = true)

display(@time entry(3.1, 1, 1, 1))
display(@time entry(3.1, 1, 1, 1))

entry = Mixtape.jit(Rosenbrock.rosenbrock,
                    Tuple{Int, Int, Int, Int};
                    opt = true)

display(@time entry(3, 1, 1, 1))
display(@time entry(3, 1, 1, 1))

allow(::Mix, m::Module) = m == Rosenbrock

# A few little utility functions for working with Expr instances.
swap(e) = e
function swap(e::Expr)
    new = MacroTools.postwalk(e) do s
        isexpr(s, :call) || return s
        s.args[1] == Base.:(*) || return s
        return Expr(:call, Base.:(+), e.args[2 : end]...)
    end
    return new
end

# This is pre-inference - you get to see a CodeInfoTools.Builder instance.
function transform(::Mix, src)
    b = CodeInfoTools.Builder(src)
    for (v, st) in b
        b[v] = swap(st)
    end
    return CodeInfoTools.finish(b)
end

Mixtape.@load_abi()
display(call(Rosenbrock.rosenbrock, 5, 5, 5, 5; ctx = Mix()))
display(call(Rosenbrock.fake; ctx = Mix()))

end # module


text:
facts("timearray works on Request object") do

  context("not sure how to include a Request object in test suite") do
      @fact isempty("") => true
  end
end


text:
"""
`module  JAC.ConfigurationSpace`
    ... a submodel of JAC that contains methods for dealing with configurations and CSF.
"""
module ConfigurationSpace

    using Printf, ..AngularMomentum, ..Basics, ..Continuum, ..Defaults, ..ManyElectron, ..Radial

    export dummyConfiguration

end # module


text:
using ControlSystems

"""
    freqresp(s, G)

The frequency response of FOTF.
"""
function ControlSystems.freqresp(s, G::FOTF)
    (a, na, b, nb, L) = fotfdata(G)

    # Initialize response
    # H1 = zeros(length(s))
    H1 = []

    for  k = 1:length(s)
        P = b'*(s[k].^nb)
        Q = a'*(s[k].^na)
        #H1[k] = P/Q
        push!(H1, P/Q)
    end

    if L>0
        H1 = H1.*exp.(-L*s)
    end
    return H1
end
#=
a=fotf([1, 2], [0.3, 0.4], [1, 2], [0.5, 0.6], 2)
freq=myfreqresp(collect(0:0.1:4).*im, a)
=#


text:
using Changepoints, Base.Test

println("Running CROPS tests...")

n = 1000;        # Number of samples
λ = 100;         # Frequencey of changes
pen = (1.1, 6.1)

function test_CROPS(segment_cost::Function , n::Int64, pen::Tuple{Real,Real})
    out = CROPS(segment_cost, n, pen)
    for (i, β) in enumerate(out["penalty"])
        #println("i=$i, β=$β")
        cps, cost = PELT(segment_cost, n; pen=β)
        @test_approx_eq_eps out["constrained"][i] (cost-(length(cps)-1)*β) 1e-3
    end
end

########################
# Normal mean segments #
########################

μ, σ = Normal(0.0, 10.0), 1.0
sample, cps = @changepoint_sampler n λ Normal(μ, σ)
segment_cost = NormalMeanSegment(sample);
#test_CROPS(segment_cost, n, pen)
out=@PELT sample Normal(?,σ) pen[1] pen[2]

# num,cons = Int[], Float64[]
# for (i, β) in enumerate(out["penalty"])
#     #println("i=$i, β=$β")
#     cps, cost = PELT(segment_cost, n; pen=β)
#     push!(num, length(cps))
#     push!(cons, cost-(length(cps)-1)*β)
# end

# cons'
# out["constrained"]'

#######################
# Normal var segments #
#######################
μ, σ = 1.0, Uniform(2.0, 15.0)
sample, cps = @changepoint_sampler n λ Normal(μ, σ)
seg_costs = NormalVarSegment(sample, μ)
test_CROPS(seg_costs, n, pen)
@PELT sample Normal(μ, ?) pen[1] pen[2]

############################
# Exponential changepoints #
############################
μ = Uniform(0.0, 10.0)
sample, cps = @changepoint_sampler n λ Exponential(μ)
seg_costs = ExponentialSegment(sample)
CROPS(seg_costs, n, pen)
@PELT sample Exponential(?) pen[1] pen[2]

########################
# Poisson changepoints #
########################
μ = Uniform(0.0, 10.0)
sample, cps = @changepoint_sampler n λ Poisson(μ)
seg_costs = PoissonSegment(sample)
CROPS(seg_costs, n, pen)
@PELT sample Poisson(?) pen[1] pen[2]


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

using Random, LinearAlgebra

# For curmod_*
include("testenv.jl")

@testset "SystemError" begin
    err = try; systemerror("reason", Cint(0)); false; catch ex; ex; end::SystemError
    errs = sprint(Base.showerror, err)
    @test startswith(errs, "SystemError: reason: ")

    err = try; systemerror("reason", Cint(0), extrainfo="addend"); false; catch ex; ex; end::SystemError
    errs = sprint(Base.showerror, err)
    @test startswith(errs, "SystemError (with addend): reason: ")

    err = try
            Libc.errno(0xc0ffee)
            systemerror("reason", true)
            false
        catch ex
            ex
        end::SystemError
    errs = sprint(Base.showerror, err)
    @test startswith(errs, "SystemError: reason: ")

    err = try; Base.windowserror("reason", UInt32(0)); false; catch ex; ex; end::SystemError
    errs = sprint(Base.showerror, err)
    @test startswith(errs, Sys.iswindows() ? "SystemError: reason: " :
        "SystemError (with Base.WindowsErrorInfo(0x00000000, nothing)): reason: ")

    err = try; Base.windowserror("reason", UInt32(0); extrainfo="addend"); false; catch ex; ex; end::SystemError
    errs = sprint(Base.showerror, err)
    @test startswith(errs, Sys.iswindows() ? "SystemError (with addend): reason: " :
        "SystemError (with Base.WindowsErrorInfo(0x00000000, \"addend\")): reason: ")

    @static if Sys.iswindows()
        err = try
                ccall(:SetLastError, stdcall, Cvoid, (UInt32,), 0x00000000)
                Base.windowserror("reason", true)
                false
            catch ex
                ex
            end::SystemError
        errs = sprint(Base.showerror, err)
        @test startswith(errs, "SystemError: reason: ")
    end
end

cfile = " at $(@__FILE__):"
c1line = @__LINE__() + 1
method_c1(x::Float64, s::AbstractString...) = true

buf = IOBuffer()
Base.show_method_candidates(buf, Base.MethodError(method_c1,(1, 1, "")))
@test String(take!(buf)) == "\nClosest candidates are:\n  method_c1(!Matched::Float64, !Matched::AbstractString...)$cfile$c1line"
@test length(methods(method_c1)) <= 3 # because of '...' in candidate printing
Base.show_method_candidates(IOContext(buf, :color => true), Base.MethodError(method_c1,(1, 1, "")))

@test String(take!(buf)) == "\n\e[0mClosest candidates are:\n\e[0m  method_c1(\e[91m::Float64\e[39m, \e[91m::AbstractString...\e[39m)$cfile$c1line"
Base.show_method_candidates(buf, Base.MethodError(method_c1,(1, "", "")))
@test String(take!(buf)) == "\nClosest candidates are:\n  method_c1(!Matched::Float64, ::AbstractString...)$cfile$c1line"

# should match
Base.show_method_candidates(buf, Base.MethodError(method_c1,(1., "", "")))
@test String(take!(buf)) == "\nClosest candidates are:\n  method_c1(::Float64, ::AbstractString...)$cfile$c1line"

# Have no matches so should return empty
Base.show_method_candidates(buf, Base.MethodError(method_c1,(1, 1, 1)))
@test String(take!(buf)) == ""

# matches the implicit constructor -> convert method
Base.show_method_candidates(buf, Base.MethodError(Tuple{}, (1, 1, 1)))
let mc = String(take!(buf))
    @test occursin("\nClosest candidates are:\n  (::Type{T})", mc)
    @test !occursin(cfile, mc)
end

c2line = @__LINE__
method_c2(x::Int32, args...) = true
method_c2(x::Int32, y::Float64, args...) = true
method_c2(x::Int32, y::Float64) = true
method_c2(x::Int32, y::Int32, z::Int32) = true
method_c2(x::T, y::T, z::T) where {T<:Real} = true

Base.show_method_candidates(buf, Base.MethodError(method_c2,(1., 1., 2)))
@test String(take!(buf)) ==  "\nClosest candidates are:\n  method_c2(::T, ::T, !Matched::T) where T<:Real$cfile$(c2line+5)\n  method_c2(!Matched::Int32, ::Float64, ::Any...)$cfile$(c2line+2)\n  method_c2(!Matched::Int32, ::Any...)$cfile$(c2line+1)\n  ..."

c3line = @__LINE__() + 1
method_c3(x::Float64, y::Float64) = true
Base.show_method_candidates(buf, Base.MethodError(method_c3,(1.,)))
@test String(take!(buf)) ==  "\nClosest candidates are:\n  method_c3(::Float64, !Matched::Float64)$cfile$c3line"

# Test for the method error in issue #8651
c4line = @__LINE__
method_c4() = true
method_c4(x::AbstractString) = false
Base.show_method_candidates(buf, MethodError(method_c4,("",)))
@test String(take!(buf)) == "\nClosest candidates are:\n  method_c4(::AbstractString)$cfile$(c4line+2)\n  method_c4()$cfile$(c4line+1)"

c5line = @__LINE__() + 1
method_c5(::Type{Float64}) = true
Base.show_method_candidates(buf, MethodError(method_c5,(Float64,)))
@test String(take!(buf)) == "\nClosest candidates are:\n  method_c5(::Type{Float64})$cfile$c5line"

Base.show_method_candidates(buf, MethodError(method_c5,(Int32,)))
@test String(take!(buf)) == "\nClosest candidates are:\n  method_c5(!Matched::Type{Float64})$cfile$c5line"

mutable struct Test_type end
test_type = Test_type()
for f in [getindex, setindex!]
    Base.show_method_candidates(buf, MethodError(f,(test_type, 1,1)))
    @test String(take!(buf)) == ""
end

PR16155line = @__LINE__() + 2
mutable struct PR16155
    a::Int64
    b
end
PR16155line2 = @__LINE__() + 1
(::Type{T})(arg::Any) where {T<:PR16155} = "replace call-to-convert method from sysimg"

Base.show_method_candidates(buf, MethodError(PR16155,(1.0, 2.0, Int64(3))))
@test String(take!(buf)) == "\nClosest candidates are:\n  $(curmod_prefix)PR16155(::Any, ::Any)$cfile$PR16155line\n  $(curmod_prefix)PR16155(!Matched::Int64, ::Any)$cfile$PR16155line\n  (::Type{T})(::Any) where T<:$(curmod_prefix)PR16155$cfile$PR16155line2"

Base.show_method_candidates(buf, MethodError(PR16155,(Int64(3), 2.0, Int64(3))))
@test String(take!(buf)) == "\nClosest candidates are:\n  $(curmod_prefix)PR16155(::Int64, ::Any)$cfile$PR16155line\n  $(curmod_prefix)PR16155(::Any, ::Any)$cfile$PR16155line\n  (::Type{T})(::Any) where T<:$(curmod_prefix)PR16155$cfile$PR16155line2"

Base.show_method_candidates(buf, MethodError(Complex{T} where T<:Integer, (1.2,)))
@test startswith(String(take!(buf)), "\nClosest candidates are:\n  (::Type{T})(::T) where T<:Number")

c6line = @__LINE__
method_c6(; x=1) = x
method_c6(a; y=1) = y
m_error = try method_c6(y=1) catch e; e; end
showerror(buf, m_error)
error_out = String(take!(buf))
m_error = try method_c6(1, x=1) catch e; e; end
showerror(buf, m_error)
error_out1 = String(take!(buf))

c6mline = @__LINE__
module TestKWError
method_c6_in_module(; x=1) = x
method_c6_in_module(a; y=1) = y
end
m_error = try TestKWError.method_c6_in_module(y=1) catch e; e; end
showerror(buf, m_error)
error_out2 = String(take!(buf))
m_error = try TestKWError.method_c6_in_module(1, x=1) catch e; e; end
showerror(buf, m_error)
error_out3 = String(take!(buf))

@test occursin("method_c6(; x)$cfile$(c6line + 1) got unsupported keyword argument \"y\"", error_out)
@test occursin("method_c6(!Matched::Any; y)$cfile$(c6line + 2)", error_out)
@test occursin("method_c6(::Any; y)$cfile$(c6line + 2) got unsupported keyword argument \"x\"", error_out1)
@test occursin("method_c6_in_module(; x)$cfile$(c6mline + 2) got unsupported keyword argument \"y\"", error_out2)
@test occursin("method_c6_in_module(!Matched::Any; y)$cfile$(c6mline + 3)", error_out2)
@test occursin("method_c6_in_module(::Any; y)$cfile$(c6mline + 3) got unsupported keyword argument \"x\"", error_out3)

c7line = @__LINE__() + 1
method_c7(a, b; kargs...) = a
Base.show_method_candidates(buf, MethodError(method_c7, (1, 1)), pairs((x = 1, y = 2)))
@test String(take!(buf)) == "\nClosest candidates are:\n  method_c7(::Any, ::Any; kargs...)$cfile$c7line"
c8line = @__LINE__() + 1
method_c8(a, b; y=1, w=1) = a
Base.show_method_candidates(buf, MethodError(method_c8, (1, 1)), pairs((x = 1, y = 2, z = 1, w = 1)))
@test String(take!(buf)) == "\nClosest candidates are:\n  method_c8(::Any, ::Any; y, w)$cfile$c8line got unsupported keyword arguments \"x\", \"z\""

let no_kwsorter_match, e
    no_kwsorter_match() = 0
    no_kwsorter_match(a;y=1) = y
    e = try no_kwsorter_match(y=1) catch ex; ex; end
    @test occursin(r"no method matching.+\(; y=1\)", sprint(showerror, e))
end

ac15639line = @__LINE__
addConstraint_15639(c::Int32) = c
addConstraint_15639(c::Int64; uncset=nothing) = addConstraint_15639(Int32(c), uncset=uncset)

Base.show_method_candidates(buf, MethodError(addConstraint_15639, (Int32(1),)), pairs((uncset = nothing,)))
@test String(take!(buf)) == "\nClosest candidates are:\n  addConstraint_15639(::Int32)$cfile$(ac15639line + 1) got unsupported keyword argument \"uncset\"\n  addConstraint_15639(!Matched::Int64; uncset)$cfile$(ac15639line + 2)"

macro except_str(expr, err_type)
    return quote
        let err = nothing
            try
                $(esc(expr))
            catch err
            end
            err === nothing && error("expected failure, but no exception thrown")
            @test typeof(err) === $(esc(err_type))
            buf = IOBuffer()
            showerror(buf, err)
            String(take!(buf))
        end
    end
end

macro except_strbt(expr, err_type)
    errmsg = "expected failure, but no exception thrown for $expr"
    return quote
        let err = nothing
            try
                $(esc(expr))
            catch err
            end
            err === nothing && error($errmsg)
            @test typeof(err) === $(esc(err_type))
            buf = IOBuffer()
            showerror(buf, err, catch_backtrace())
            String(take!(buf))
        end
    end
end

macro except_stackframe(expr, err_type)
    return quote
       let err = nothing
           local st
           try
               $(esc(expr))
           catch err
               st = stacktrace(catch_backtrace())
           end
           err === nothing && error("expected failure, but no exception thrown")
           @test typeof(err) === $(esc(err_type))
           sprint(show, st[1])
       end
    end
end

# Pull Request 11007
abstract type InvokeType11007 end
abstract type MethodType11007 <: InvokeType11007 end
mutable struct InstanceType11007 <: MethodType11007
end
let
    f11007(::MethodType11007) = nothing
    err_str = @except_str(invoke(f11007, Tuple{InvokeType11007},
                                 InstanceType11007()), MethodError)
    @test !occursin("::$(curmod_prefix)InstanceType11007", err_str)
    @test occursin("::$(curmod_prefix)InvokeType11007", err_str)
end

module __tmp_replutil

using Test
import ..@except_str
global +
+() = nothing
err_str = @except_str 1 + 2 MethodError
@test occursin("import Base.:+", err_str)

err_str = @except_str Float64[](1) MethodError
@test !occursin("import Base.Array", err_str)

Array() = 1
err_str = @except_str Array([1]) MethodError
@test occursin("import Base.Array", err_str)

end

let
    g11007(::AbstractVector) = nothing
    err_str = @except_str g11007([[1] [1]]) MethodError
    @test occursin("row vector", err_str)
    @test occursin("column vector", err_str)
end

struct TypeWithIntParam{T <: Integer} end
struct Bounded  # not an AbstractArray
    bound::Int
end
Base.getindex(b::Bounded, i) = checkindex(Bool, 1:b.bound, i) || throw(BoundsError(b, i))
Base.summary(io::IO, b::Bounded) = print(io, "$(b.bound)-size Bounded")
let undefvar
    err_str = @except_strbt sqrt(-1) DomainError
    @test occursin("Try sqrt(Complex(x)).", err_str)
    err_str = @except_strbt 2^(1-2) DomainError
    @test occursin("Cannot raise an integer x to a negative power -1", err_str)
    err_str = @except_strbt (-1)^0.25 DomainError
    @test occursin("Exponentiation yielding a complex result requires a complex argument", err_str)
    A = zeros(10, 10)
    A[2,1] = 1
    A[1,2] = -1
    err_str = @except_strbt eigmax(A) DomainError
    @test occursin("DomainError with [0.0 -1.0 …", err_str)

    err_str = @except_str (1, 2, 3)[4] BoundsError
    @test err_str == "BoundsError: attempt to access (1, 2, 3) at index [4]"

    err_str = @except_str [5, 4, 3][-2, 1] BoundsError
    @test err_str == "BoundsError: attempt to access 3-element Vector{$Int} at index [-2, 1]"
    err_str = @except_str [5, 4, 3][1:5] BoundsError
    @test err_str == "BoundsError: attempt to access 3-element Vector{$Int} at index [1:5]"

    err_str = @except_str Bounded(2)[3] BoundsError
    @test err_str == "BoundsError: attempt to access 2-size Bounded at index [3]"

    err_str = @except_str 0::Bool TypeError
    @test err_str == "TypeError: non-boolean ($Int) used in boolean context"
    err_str = @except_str 0::AbstractFloat TypeError
    @test err_str == "TypeError: in typeassert, expected AbstractFloat, got a value of type $Int"
    err_str = @except_str 0::7 TypeError
    @test err_str == "TypeError: in typeassert, expected Type, got a value of type $Int"
    err_str = @except_str "" <: AbstractString TypeError
    @test err_str == "TypeError: in <:, expected Type, got a value of type String"
    err_str = @except_str AbstractString <: "" TypeError
    @test err_str == "TypeError: in <:, expected Type, got a value of type String"
    err_str = @except_str Type{""} TypeError
    @test err_str == "TypeError: in Type, in parameter, expected Type, got a value of type String"
    err_str = @except_str TypeWithIntParam{Any} TypeError
    @test err_str == "TypeError: in TypeWithIntParam, in T, expected T<:Integer, got Type{Any}"
    err_str = @except_str Type{Vararg} TypeError
    @test err_str == "TypeError: in Type, in parameter, expected Type, got Vararg"

    err_str = @except_str mod(1,0) DivideError
    @test err_str == "DivideError: integer division error"
    err_str = @except_str Vector{Any}(undef, 1)[1] UndefRefError
    @test err_str == "UndefRefError: access to undefined reference"
    err_str = @except_str undefvar UndefVarError
    @test err_str == "UndefVarError: undefvar not defined"
    err_str = @except_str read(IOBuffer(), UInt8) EOFError
    @test err_str == "EOFError: read end of file"
    err_str = @except_str Dict()[:doesnotexist] KeyError
    @test err_str == "KeyError: key :doesnotexist not found"
    err_str = @except_str throw(InterruptException()) InterruptException
    @test err_str == "InterruptException:"
    err_str = @except_str throw(ArgumentError("not an error")) ArgumentError
    @test err_str == "ArgumentError: not an error"
    err_str = @except_str @assert(false) AssertionError
    @test err_str == "AssertionError: false"
end

# issue 11845
let buf = IOBuffer()
    showerror(buf, MethodError(convert, (3, 1.0)))
    showerror(buf, MethodError(convert, (Int, 1.0)))
    showerror(buf, MethodError(convert, Tuple{Type, Float64}))
    showerror(buf, MethodError(convert, Tuple{DataType, Float64}))
end

# Issue #14884
primitive type EightBitType 8 end
primitive type EightBitTypeT{T} 8 end
struct FunctionLike <: Function; end
let err_str,
    i = reinterpret(EightBitType, 0x54),
    j = reinterpret(EightBitTypeT{Int32}, 0x54)

    err_str = @except_str Bool() MethodError
    @test occursin("MethodError: no method matching Bool()", err_str)
    err_str = @except_str :a() MethodError
    @test occursin("MethodError: objects of type Symbol are not callable", err_str)
    err_str = @except_str EightBitType() MethodError
    @test occursin("MethodError: no method matching $(curmod_prefix)EightBitType()", err_str)
    err_str = @except_str i() MethodError
    @test occursin("MethodError: objects of type $(curmod_prefix)EightBitType are not callable", err_str)
    err_str = @except_str EightBitTypeT() MethodError
    @test occursin("MethodError: no method matching $(curmod_prefix)EightBitTypeT()", err_str)
    err_str = @except_str EightBitTypeT{Int32}() MethodError
    @test occursin("MethodError: no method matching $(curmod_prefix)EightBitTypeT{Int32}()", err_str)
    err_str = @except_str j() MethodError
    @test occursin("MethodError: objects of type $(curmod_prefix)EightBitTypeT{Int32} are not callable", err_str)
    err_str = @except_str FunctionLike()() MethodError
    @test occursin("MethodError: no method matching (::$(curmod_prefix)FunctionLike)()", err_str)
    err_str = @except_str [1,2](1) MethodError
    @test occursin("MethodError: objects of type Vector{$Int} are not callable\nUse square brackets [] for indexing an Array.", err_str)
    # Issue 14940
    err_str = @except_str randn(1)() MethodError
    @test occursin("MethodError: objects of type Vector{Float64} are not callable", err_str)
end
@test repr("text/plain", FunctionLike()) == "(::$(curmod_prefix)FunctionLike) (generic function with 0 methods)"
@test occursin(r"^@doc \(macro with \d+ method[s]?\)$", repr("text/plain", getfield(Base, Symbol("@doc"))))

# Issue 34636
let err_str
    err_str = @except_str 1 + rand(5) MethodError
    @test occursin("MethodError: no method matching +(::$Int, ::Vector{Float64})", err_str)
    @test occursin("For element-wise addition, use broadcasting with dot syntax: scalar .+ array", err_str)
    err_str = @except_str rand(5) - 1//3 MethodError
    @test occursin("MethodError: no method matching -(::Vector{Float64}, ::Rational{$Int})", err_str)
    @test occursin("For element-wise subtraction, use broadcasting with dot syntax: array .- scalar", err_str)
end

method_defs_lineno = @__LINE__() + 1
String() = throw(ErrorException("1"))
(::String)() = throw(ErrorException("2"))
EightBitType() = throw(ErrorException("3"))
(::EightBitType)() = throw(ErrorException("4"))
EightBitTypeT() = throw(ErrorException("5"))
EightBitTypeT{T}() where {T} = throw(ErrorException("6"))
(::EightBitTypeT)() = throw(ErrorException("7"))
(::FunctionLike)() = throw(ErrorException("8"))

struct StructWithUnionAllMethodDefs{T}
end
(::Type{StructWithUnionAllMethodDefs{T} where T<:Integer})(x) = x

let err_str,
    i = reinterpret(EightBitType, 0x54),
    j = reinterpret(EightBitTypeT{Int32}, 0x54),
    sp = Base.source_path()
    sn = basename(sp)

    @test sprint(show, which(String, Tuple{})) ==
        "String() in $curmod_str at $sp:$(method_defs_lineno + 0)"
    @test sprint(show, which("a", Tuple{})) ==
        "(::String)() in $curmod_str at $sp:$(method_defs_lineno + 1)"
    @test sprint(show, which(EightBitType, Tuple{})) ==
        "$(curmod_prefix)EightBitType() in $curmod_str at $sp:$(method_defs_lineno + 2)"
    @test sprint(show, which(reinterpret(EightBitType, 0x54), Tuple{})) ==
        "(::$(curmod_prefix)EightBitType)() in $curmod_str at $sp:$(method_defs_lineno + 3)"
    @test sprint(show, which(EightBitTypeT, Tuple{})) ==
        "$(curmod_prefix)EightBitTypeT() in $curmod_str at $sp:$(method_defs_lineno + 4)"
    @test sprint(show, which(EightBitTypeT{Int32}, Tuple{})) ==
        "$(curmod_prefix)EightBitTypeT{T}() where T in $curmod_str at $sp:$(method_defs_lineno + 5)"
    @test sprint(show, which(reinterpret(EightBitTypeT{Int32}, 0x54), Tuple{})) ==
        "(::$(curmod_prefix)EightBitTypeT)() in $curmod_str at $sp:$(method_defs_lineno + 6)"
    @test startswith(sprint(show, which(Complex{Int}, Tuple{Int})),
                     "Complex{T}(")
    @test startswith(sprint(show, which(getfield(Base, Symbol("@doc")), Tuple{LineNumberNode, Module, Vararg{Any}})),
                     "@doc(__source__::LineNumberNode, __module__::Module, x...) in Core at boot.jl:")
    @test startswith(sprint(show, which(FunctionLike(), Tuple{})),
                     "(::$(curmod_prefix)FunctionLike)() in $curmod_str at $sp:$(method_defs_lineno + 7)")
    @test startswith(sprint(show, which(StructWithUnionAllMethodDefs{<:Integer}, (Any,))),
                     "($(curmod_prefix)StructWithUnionAllMethodDefs{T} where T<:Integer)(x)")
    @test repr("text/plain", FunctionLike()) == "(::$(curmod_prefix)FunctionLike) (generic function with 1 method)"
    @test repr("text/plain", Core.arraysize) == "arraysize (built-in function)"

    err_str = @except_stackframe String() ErrorException
    @test err_str == "String() at $sn:$(method_defs_lineno + 0)"
    err_str = @except_stackframe "a"() ErrorException
    @test err_str == "(::String)() at $sn:$(method_defs_lineno + 1)"
    err_str = @except_stackframe EightBitType() ErrorException
    @test err_str == "$(curmod_prefix)EightBitType() at $sn:$(method_defs_lineno + 2)"
    err_str = @except_stackframe i() ErrorException
    @test err_str == "(::$(curmod_prefix)EightBitType)() at $sn:$(method_defs_lineno + 3)"
    err_str = @except_stackframe EightBitTypeT() ErrorException
    @test err_str == "$(curmod_prefix)EightBitTypeT() at $sn:$(method_defs_lineno + 4)"
    err_str = @except_stackframe EightBitTypeT{Int32}() ErrorException
    @test err_str == "$(curmod_prefix)EightBitTypeT{Int32}() at $sn:$(method_defs_lineno + 5)"
    err_str = @except_stackframe j() ErrorException
    @test err_str == "(::$(curmod_prefix)EightBitTypeT{Int32})() at $sn:$(method_defs_lineno + 6)"
    err_str = @except_stackframe FunctionLike()() ErrorException
    @test err_str == "(::$(curmod_prefix)FunctionLike)() at $sn:$(method_defs_lineno + 7)"
end

# Issue #20108
let err, buf = IOBuffer()
    try Array() catch err end
    Base.show_method_candidates(buf,err)
    @test isa(err, MethodError)
    @test occursin("Closest candidates are:", String(take!(buf)))
end

# @macroexpand tests
macro seven_dollar(ex)
    # simonbyrne example 18240
    isa(ex,Expr) && ex.head == :$ ? 7 : esc(ex)
end

let
    @test (@macroexpand @macroexpand x) == macroexpand(@__MODULE__, :(@macroexpand x))
    @test (@macroexpand  :(1+$y) ) == macroexpand(@__MODULE__, :( :(1+ $y) ))
    @test (@macroexpand @fastmath 1+2    ) == :(Base.FastMath.add_fast(1,2))
    @test (@macroexpand @fastmath +      ) == :(Base.FastMath.add_fast)
    @test (@macroexpand @fastmath min(1) ) == :(Base.FastMath.min_fast(1))
    let err = try; @macroexpand @doc "" f() = @x; catch ex; ex; end
        file, line = @__FILE__, @__LINE__() - 1
        err = err::LoadError
        @test err.file == file && err.line == line
        err = err.error::LoadError
        @test err.file == file && err.line == line
        err = err.error::UndefVarError
        @test err == UndefVarError(Symbol("@x"))
    end
    @test (@macroexpand @seven_dollar $bar) == 7
    x = 2
    @test (@macroexpand @seven_dollar 1+$x) == :(1 + $(Expr(:$, :x)))
end

macro nest1(code)
    code
end

macro nest2(code)
    :(@nest1 $code)
end

macro nest2b(code)
    :(@nest1($code); @nest1($code))
end

@testset "@macroexpand1" begin
    M = @__MODULE__
    _macroexpand1(ex) = macroexpand(M, ex, recursive=false)
    ex = :(@nest1 42)
    @test _macroexpand1(ex) == macroexpand(M,ex)
    ex = :(@nest2 42)
    @test _macroexpand1(ex) != macroexpand(M,ex)
    @test _macroexpand1(_macroexpand1(ex)) == macroexpand(M,ex)
    ex = :(@nest2b 42)
    @test _macroexpand1(ex) != macroexpand(M,ex)
    @test _macroexpand1(_macroexpand1(ex)) == macroexpand(M, ex)
    @test (@macroexpand1 @nest2b 42) == _macroexpand1(ex)
end

foo_9965(x::Float64; w=false) = x
foo_9965(x::Int) = 2x

@testset "closest candidates kwarg #9965" begin
    ex = try
        foo_9965(1, w=true)
    catch e
        e
    end
    @test typeof(ex) == MethodError
    io = IOBuffer()
    Base.show_method_candidates(io, ex, pairs((w = true,)))
    @test occursin("got unsupported keyword argument \"w\"", String(take!(io)))
end

# Issue #20556
import REPL
module EnclosingModule
    abstract type AbstractTypeNoConstructors end
end
let
    method_error = MethodError(EnclosingModule.AbstractTypeNoConstructors, ())

    # Test that it shows a special message when no constructors have been defined by the user.
    @test sprint(showerror, method_error) ==
        "MethodError: no constructors have been defined for $(EnclosingModule.AbstractTypeNoConstructors)"

    # Does it go back to previous behaviour when there *is* at least
    # one constructor defined?
    EnclosingModule.AbstractTypeNoConstructors(x, y) = x + y
    @test startswith(sprint(showerror, method_error),
        "MethodError: no method matching $(EnclosingModule.AbstractTypeNoConstructors)()")

    # Test that the 'default' sysimg.jl method is not displayed.
    @test !occursin("where T at sysimg.jl", sprint(showerror, method_error))

    # Test that tab-completion will not show the 'default' sysimg.jl method.
    completions = REPL.REPLCompletions.complete_methods(:(EnclosingModule.AbstractTypeNoConstructors()), @__MODULE__)
    @test !isempty(completions)
    for method_string in completions
        @test !startswith(REPL.REPLCompletions.completion_text(method_string), "(::Type{T})(arg) where T in Base at sysimg.jl")
    end
end

@testset "show for manually thrown MethodError" begin
    global f21006

    f21006() = nothing
    # Normal method error should not warn about world age.
    ex1 = try
        f21006(())
    catch e
        e
    end::MethodError
    str = sprint(Base.showerror, ex1)
    @test startswith(str, "MethodError: no method matching f21006(::Tuple{})")
    @test !occursin("The applicable method may be too new", str)

    # If newer applicable methods are available, world age should be mentioned.
    f21006(x) = x
    @test f21006(()) === ()
    str = sprint(Base.showerror, ex1)
    @test startswith(str, "MethodError: no method matching f21006(::Tuple{})")
    @test occursin("The applicable method may be too new: running in world age $(ex1.world)", str)

    # This method error should be thrown in a world new enough for `f21006(())`.
    # Also makes sure it's printed correctly.
    ex2 = try
        f21006((), ())
    catch e
        e
    end::MethodError
    str = sprint(Base.showerror, ex2)
    @test startswith(str, "MethodError: no method matching f21006(::Tuple{}, ::Tuple{})")
    @test !occursin("The applicable method may be too new", str)

    # If the method is available in the exception world or if the exception world is invalid,
    # don't warn about world age
    for ex3 in (MethodError(ex1.f, ex1.args, ex2.world),
                MethodError(ex1.f, ex1.args, typemax(UInt)))
        str = sprint(Base.showerror, ex3)
        @test startswith(str, "MethodError: no method matching f21006(::Tuple{})")
        @test !occursin("The applicable method may be too new", str)
    end
end

# Custom hints
struct HasNoOne end
function recommend_oneunit(io, ex, arg_types, kwargs)
    if ex.f === Base.one && length(arg_types) == 1 && arg_types[1] === HasNoOne
        if isempty(kwargs)
            print(io, "\nHasNoOne does not support `one`; did you mean `oneunit`?")
        else
            print(io, "\n`one` doesn't take keyword arguments, that would be silly")
        end
    end
end
@test Base.Experimental.register_error_hint(recommend_oneunit, MethodError) === nothing
let err_str
    err_str = @except_str one(HasNoOne()) MethodError
    @test occursin(r"MethodError: no method matching one\(::.*HasNoOne\)", err_str)
    @test occursin("HasNoOne does not support `one`; did you mean `oneunit`?", err_str)
    err_str = @except_str one(HasNoOne(); value=2) MethodError
    @test occursin(r"MethodError: no method matching one\(::.*HasNoOne; value=2\)", err_str)
    @test occursin("`one` doesn't take keyword arguments, that would be silly", err_str)
end
pop!(Base.Experimental._hint_handlers[MethodError])  # order is undefined, don't copy this

function busted_hint(io, exc, notarg)  # wrong number of args
    print(io, "\nI don't have a hint for you, sorry")
end
@test Base.Experimental.register_error_hint(busted_hint, DomainError) === nothing
try
    sqrt(-2)
catch ex
    io = IOBuffer()
    @test_logs (:error, "Hint-handler busted_hint for DomainError in $(@__MODULE__) caused an error") showerror(io, ex)
end
pop!(Base.Experimental._hint_handlers[DomainError])  # order is undefined, don't copy this

# issue #28442
@testset "Long stacktrace printing" begin
    f28442(c) = g28442(c + 1)
    g28442(c) = c > 10000 ? (return backtrace()) : f28442(c+1)
    bt = f28442(1)
    io = IOBuffer()
    Base.show_backtrace(io, bt)
    output = split(String(take!(io)), '\n')
    @test lstrip(output[3])[1:3] == "[1]"
    @test occursin("g28442", output[3])
    @test lstrip(output[5])[1:3] == "[2]"
    @test occursin("f28442", output[5])
    # Issue #30233
    # Note that we can't use @test_broken on FreeBSD here, because the tests actually do
    # pass with some compilation options, e.g. with assertions enabled
    if !Sys.isfreebsd()
        @test occursin("the last 2 lines are repeated 5000 more times", output[7])
        @test lstrip(output[8])[1:7] == "[10003]"
    end
end

@testset "Line number correction" begin
    getbt() = backtrace()
    bt = getbt()
    Base.update_stackframes_callback[] = function(list)
        modify((sf, n)) = sf.func == :getbt ? (StackTraces.StackFrame(sf.func, sf.file, sf.line+2, sf.linfo, sf.from_c, sf.inlined, sf.pointer), n) : (sf, n)
        map!(modify, list, list)
    end
    io = IOBuffer()
    Base.show_backtrace(io, bt)
    outputc = split(String(take!(io)), '\n')
    Base.update_stackframes_callback[] = identity
    Base.show_backtrace(io, bt)
    output0 = split(String(take!(io)), '\n')
    function getline(output)
        idx = findfirst(str->occursin("getbt", str), output)
        return parse(Int, match(r":(\d*)$", output[idx+1]).captures[1])
    end
    @test getline(outputc) == getline(output0) + 2
end

# issue #30633
@test_throws ArgumentError("invalid index: \"foo\" of type String") [1]["foo"]
@test_throws ArgumentError("invalid index: nothing of type Nothing") [1][nothing]

# test showing MethodError with type argument
struct NoMethodsDefinedHere; end
let buf = IOBuffer()
    Base.show_method_candidates(buf, Base.MethodError(sin, Tuple{NoMethodsDefinedHere}))
    @test length(take!(buf)) !== 0
end

# pr #32814
let t1 = @async(error(1)),
    t2 = @async(wait(t1))
    local e
    try
        wait(t2)
    catch e_
        e = e_
    end
    buf = IOBuffer()
    showerror(buf, e)
    s = String(take!(buf))
    @test length(findall("Stacktrace:", s)) == 2
    @test occursin("[1] error(s::Int", s)
end

module TestMethodShadow
    struct Foo; x; end
    +(a::Foo, b::Foo) = Foo(a.x + b.x)
    ==(a::Foo, b::Foo) = Foo(a.x == b.x)
    div(a::Foo, b::Foo) = Foo(div(a.x, b.x))
end
for (func,str) in ((TestMethodShadow.:+,":+"), (TestMethodShadow.:(==),":(==)"), (TestMethodShadow.:div,"div"))
    ex = try
        foo = TestMethodShadow.Foo(3)
        func(foo,foo)
    catch e
       e
    end::MethodError
    @test occursin("You may have intended to import Base.$str", sprint(Base.showerror, ex))
end

# Test that implementation detail of include() is hidden from the user by default
let bt = try
        include("testhelpers/include_error.jl")
    catch
        catch_backtrace()
    end
    bt_str = sprint(Base.show_backtrace, bt)
    @test occursin(" include(", bt_str)
    @test !occursin(" _include(", bt_str)
end

# Test backtrace printing
module B
    module C
        f(x; y=2.0) = error()
    end
    module D
        import ..C: f
        g() = f(2.0; y=3.0)
    end
end

@testset "backtrace" begin
    bt = try B.D.g()
    catch
        catch_backtrace()
    end
    bt_str = sprint(Base.show_backtrace, bt)
    m = @__MODULE__
    @test contains(bt_str, "f(x::Float64; y::Float64)")
    @test contains(bt_str, "@ $m.B.C")
    @test contains(bt_str, "@ $m.B.D")
end

max_stars_repo_name: mrdofu/julia

max_issues_repo_name: mrdofu/julia

max_forks_repo_name: mrdofu/julia


text:
function setup_integrations()
    @require Blink="ad839575-38b3-5650-b840-f874b8c74a25" begin
        function Base.open(core::CoreVisualizer, w::Blink.AtomShell.Window)
            # Ensure the window is ready
            Blink.wait(w)
            # Set its contents
            Blink.loadurl(w, url(core))
            w
        end
    end

    @require WebIO="0f1e0344-ec1d-5b48-a673-e5cf874b6c29" begin
        WebIO.render(vis::Visualizer) = WebIO.render(vis.core)

        WebIO.render(core::CoreVisualizer) = WebIO.render(MeshCat.render(core))
    end
end


text:
function plot_panels(panels :: Vector{<: Panel3D})
    coords = panel_coords.(panels)
    tupvector.([coord; [coord[1]]] for coord in coords)
end

function plot_wing(wing :: Union{HalfWing, Wing}, rotation, translation)
    affine = Translation(translation) ∘ LinearMap(rotation)
    leading, trailing = wing_bounds(wing)
    wing_coords = [ leading; trailing[end:-1:1]; [ first(leading) ] ]
    # foil_coords = [ [ [coord[1]; 0; coord[2]] .* chord .+ loc for coord in foil.coords ] for (chord, foil, loc) in zip(wing.right.chords[end:-1:1], wing.right.foils[end:-1:1], wing_coords) ]

    [ tuple(affine(coords)...) for coords in wing_coords ]
end

plot_wing(wing :: Union{HalfWing, Wing}; angle = 0., axis = [1., 0., 0.], position = zeros(3)) = plot_wing(wing, AngleAxis{Float64}(angle, axis...), position)

plot_streams(freestream, points, horseshoes, Γs, length, num_steps) = tupvector.(streamlines(freestream, points, horseshoes, Γs, length, num_steps))

plot_surface(wing :: Union{HalfWing, Wing}, span_num = 5, chord_num = 30; rotation = one(RotMatrix{3, Float64}), translation = SVector(0, 0, 0)) = plot_panels(transform(panel, rotation, translation) for panel in mesh_wing(wing, span_num, chord_num)[:])

## Doublet-source
#==========================================================================================#

## Plotting domain
# x_domain, y_domain = (-1, 2), (-1, 1)
# grid_size = 50
# x_dom, y_dom = linspace(x_domain..., grid_size), linspace(y_domain..., grid_size)
# grid = x_dom × y_dom

# vels, pots = grid_data(dub_src_panels, grid)
# cp = pressure_coefficient.(uniform.magnitude, vels);

# lower_panels, upper_panels = split_panels(dub_src_panels);

# ## Airfoil plot
# plot( (first ∘ collocation_point).(upper_panels), (last ∘ collocation_point).(upper_panels),
#         label = "Upper", markershape = :circle,
#         xlabel = "x", ylabel = "C_p")
# plot!((first ∘ collocation_point).(lower_panels), (last ∘ collocation_point).(lower_panels),
#         label = "Lower", markershape = :circle,
#         xlabel = "x", ylabel = "C_p")

# ## Pressure coefficient
# plot( (first ∘ collocation_point).(upper_panels), :cp .<< upper_panels,
#         label = "Upper", markershape = :circle,
#         xlabel = "x", ylabel = "C_p")
# plot!((first ∘ collocation_point).(upper_panels), :cp .<< lower_panels,
#         label = "Lower", markershape = :circle, yaxis = :flip)

# ## Control volume
# p1 = contour(x_dom, y_dom, cp, fill = true)
# plot(p1)
# plot!(first.(:start .<< panels), last.(:start .<< panels),
#       color = "black", label = "Airfoil", aspect_ratio = :equal)

max_forks_repo_name: GodotMisogi/AeroMDAO


text:
#=
Copyright (c) 2015, Intel Corporation
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
=#

# Some image manipulation functions

module Image

using ParallelAccelerator
export downSample, interpolateFlow, warpMotion, readImage, writeFlo

@acc begin

function downsample_inner(x, y, sx, sy, a)
  x0 = sx * Float32(x - 1)
  y0 = sy * Float32(y - 1)
  x1 = sx * Float32(x) - 1f-3
  y1 = sy * Float32(y) - 1f-3
  c = 0f0
  for i = round(Int, floor(x0)):round(Int, ceil(x1)) - 1
    for j = round(Int, floor(y0)):round(Int, ceil(y1)) - 1
      ii = Float32(i)
      jj = Float32(j)
      p = ii < x0 ? (ii + 1f0 - x0) : (ii > x1 - 1f0 ? (x1 - ii) : 1f0)
      q = jj < y0 ? (jj + 1f0 - y0) : (jj > y1 - 1f0 ? (y1 - jj) : 1f0)
      c += p * q * a[i + 1, j + 1]
    end
  end
  c / (sx * sy)
end

# Down sample an image to a smaller size
#   We can think of the image as dividing up into a grid of equal sized pixels
#   The pixels of the desired smaller image overlap the pixels of the larger original image
#   We want the value of the output pixel to be the average of the input pixels overlapped weighted by
#   area of overlap
# Pre: size(oi)>=(nw,nh)
function downSample(a::Array{Float32, 2}, nw::Int, nh::Int)
  (w, h) = size(a)
  sx::Float32 = Float32(w) / Float32(nw)
  sy::Float32 = Float32(h) / Float32(nh)
  na = [ downsample_inner(x, y, sx, sy, a) for x = 1:nw, y = 1:nh ]
  return na
end

# Linearly interpolate between array values
# Pre: 1<=x<size(a,1) && 1<=y<size(a,2)
function interpolate(a::Matrix{Float32}, x::Float32, y::Float32)
# Returns Float32
  xx = round(Int, floor(x))
  yy = round(Int, floor(y))
  #println("x,y=",x,",",y)
  alpha = x-Float32(xx)
  beta  = y-Float32(yy)
  return Float32(beta*(alpha*a[xx+1,yy+1] + (1f0-alpha)*a[xx,yy+1]) +
         (1f0-beta)*(alpha*a[xx+1,yy] + (1f0-alpha)*a[xx,yy]))
end

# Given a flow at a coarser grain, interpolate it to a finer grain
# Pre: size(ou)==size(ov)<=(nh,nw)
function interpolateFlow(ou::Matrix{Float32}, ov::Matrix{Float32}, nw::Int, nh::Int)
# Returns two Matrix{Float32} size=(nh,nw)
  (ow::Int, oh::Int) = size(ou)
  if ow==nw && oh==nh
    return ou, ov
  end
  sx::Float32 = Float32(ow-1) / Float32(nw)
  sy::Float32 = Float32(oh-1) / Float32(nh)
  nu = [ interpolate(ou, Float32(x-1)*sx+1f0, Float32(y-1)*sy+1f0)*sx for x = 1:nw, y = 1:nh ]
  nv = [ interpolate(ou, Float32(x-1)*sx+1f0, Float32(y-1)*sy+1f0)*sx for x = 1:nw, y = 1:nh ]
  return nu, nv
end

function warpMotion_inner(u,v,i,ii,w,h,x,y)
  nx = Float32(x)+u[x,y]
  ny = Float32(y)+v[x,y]
  (nx<1f0 || nx>=float(w) || ny<1f0 || ny>=float(h)) ? ii[x,y] : interpolate(i, nx, ny)
end

# Given a flow and an image, move the image according to the flow
# Pre: size(i)==size(u)==size(v)==size(ii)
function warpMotion(i::Matrix{Float32}, u::Matrix{Float32}, v::Matrix{Float32}, ii::Matrix{Float32})
# Returns Matrix{Float32} size=size(i)
  (w::Int, h::Int) = size(i)
  [ warpMotion_inner(u,v,i,ii,w,h,x,y) for x = 1:w, y = 1:h ]
end

end

function readImage(fn::AbstractString)
  f = open(fn, "r")
  w = read(f, Int32)
  h = read(f, Int32)
  img = zeros(Float32, w, h)
  for i in 1:h
    for j in 1:w
      img[j,i] = Float32(read(f, UInt8))/255.0
    end
  end
  close(f)
  return img
end

function writeFlo(u::Matrix{Float32}, v::Matrix{Float32}, fn::AbstractString)
  w = size(u, 1)
  h = size(u, 2)
  f = open(fn, "w")
  write(f, w)
  write(f, h)
  for i in 1:h
    for j in 1:w
      write(f, u[j, i])
      write(f, v[j, i])
    end
  end
  close(f)
end

end


text:
using JuMP; using NCDatasets; using AxisArrays; using CalliopeJuMP.Util;

function load_cost_constraints(model_dict)
    sets = model_dict["sets"]
    constraint_dict = Dict()

    if haskey(sets, "loc_techs_cost_constraint")
        constraint_dict["cost_constraint"] = (
            build_constraint(["costs", "loc_techs_cost_constraint"],
            "cost", model_dict)
        )
    end

    if haskey(sets, "loc_techs_cost_investment_constraint")
        model_dict["expressions"]["cost_investment_rhs"] = @expression(
            model_dict["backend_model"], [costs=sets["costs"],
            loc_techs_investment=sets["loc_techs_investment_cost"]],
            0
        )

        constraint_dict["cost_investment_constraint"] = (
            build_constraint(["costs", "loc_techs_cost_investment_constraint"],
            "cost_investment", model_dict)
        )
    end

    if haskey(sets, "loc_techs_cost_var_constraint")
        model_dict["expressions"]["cost_var_rhs"] = @expression(
            model_dict["backend_model"], [costs=sets["costs"],
            loc_techs_om_var=sets["loc_techs_om_cost"],
            timesteps=sets["timesteps"]],
            0
        )

        constraint_dict["cost_var_constraint"] = (
            build_constraint(["costs", "loc_techs_cost_var_constraint", "timesteps"],
            "cost_var", model_dict)
        )

    end

    return constraint_dict
end

function cost_constraint_rule(backend_model, set_indices, model_dict)
    """
    Combine investment and time varying costs into one cost per technology
    """
    cost, loc_tech = set_indices
    variables = model_dict["variables"]
    sets = model_dict["sets"]

    if loc_tech_is_in(sets, loc_tech, "loc_techs_investment_cost")
        cost_investment = variables["cost_investment"][cost, loc_tech]
    else
        cost_investment = 0
    end

    if loc_tech_is_in(sets, loc_tech, "loc_techs_om_cost")
        cost_var = sum(variables["cost_var"][cost, loc_tech, timestep]
                       for timestep in sets["timesteps"])
    else
        cost_var = 0
    end

    return @constraint(backend_model,
        variables["cost"][cost, loc_tech] == cost_investment + cost_var
    )

end

function cost_investment_constraint_rule(backend_model, set_indices, model_dict)
    """
    Calculate costs from capacity decision variables
    """
    cost, loc_tech = set_indices
    variables = model_dict["variables"]
    sets = model_dict["sets"]

    function _get_investment_cost(capacity_decision_variable, calliope_set)
        """
        Conditionally add investment costs, if the relevant set of technologies
        exists. Both inputs are strings.
        """
        if loc_tech_is_in(sets, loc_tech, calliope_set)
            _cost = (
                variables[capacity_decision_variable][loc_tech] *
                get_param(model_dict, string("cost_", capacity_decision_variable),
                          [loc_tech, cost])
            )
            return _cost
        else
            return 0
        end
    end

    cost_energy_cap = (variables["energy_cap"][loc_tech]
        * get_param(model_dict, "cost_energy_cap", [loc_tech, cost]))

    cost_storage_cap = _get_investment_cost("storage_cap", "loc_techs_store")
    cost_resource_cap = _get_investment_cost("resource_cap", "loc_techs_supply_plus")
    cost_resource_area = _get_investment_cost("resource_area", "loc_techs_area")

    cost_om_annual_investment_fraction = get_param(model_dict, "cost_om_annual_investment_fraction", [loc_tech, cost])
    cost_om_annual = get_param(model_dict, "cost_om_annual", [loc_tech, cost])

    ts_weight = get_timestep_weight(model_dict)
    depreciation_rate = model_dict["parameters"]["cost_depreciation_rate"][loc_tech, cost]

    cost_con = (
        depreciation_rate * ts_weight *
        (cost_energy_cap + cost_storage_cap + cost_resource_cap +
         cost_resource_area)
    )

    # Transmission technologies exist at two locations, thus their cost is divided by 2
    if loc_tech_is_in(sets, loc_tech, "loc_techs_transmission")
            cost_con = cost_con / 2
    end
    cost_fractional_om = cost_om_annual_investment_fraction * cost_con
    cost_fixed_om = cost_om_annual * variables["energy_cap"][loc_tech] * ts_weight

    append!(model_dict["expressions"]["cost_investment_rhs"][cost, loc_tech],
        cost_fractional_om + cost_fixed_om + cost_con
    )

    return @constraint(backend_model,
        variables["cost_investment"][cost, loc_tech] ==
        model_dict["expressions"]["cost_investment_rhs"][cost, loc_tech]
    )
end

function cost_var_constraint_rule(backend_model, set_indices, model_dict)
    """
    Calculate costs from time-varying decision variables
    """
    cost, loc_tech, timestep = set_indices
    variables = model_dict["variables"]
    sets = model_dict["sets"]

    cost_om_prod = get_param(model_dict, "cost_om_prod", [loc_tech, cost], timestep)
    cost_om_con = get_param(model_dict, "cost_om_con", [loc_tech, cost], timestep)
    weight = model_dict["parameters"]["timestep_weights"][timestep]

    loc_tech_carrier = model_dict["parameters"]["lookup_loc_techs"][loc_tech]

    if cost_om_prod !== nothing
        cost_prod = cost_om_prod * weight * variables["carrier_prod"][loc_tech_carrier, timestep]
    else
        cost_prod = 0
    end

    if loc_tech_is_in(sets, loc_tech, "loc_techs_supply_plus") && cost_om_con !== nothing
        resource_eff = get_param(model_dict, "resource_eff", [loc_tech], timestep)
        if resource_eff > 0  # In case resource_eff is zero, to avoid an infinite value
            # Dividing by r_eff here so we get the actual r used, not the r
            # moved into storage...
            cost_con = cost_om_con * weight * (variables["resource_con"][loc_tech, timestep] / resource_eff)
        else
            cost_con = 0
        end
    elseif loc_tech_is_in(sets, loc_tech, "loc_techs_supply") && cost_om_con > 0
        energy_eff = get_param(model_dict, "energy_eff", [loc_tech], timestep)
        if energy_eff > 0  # in case energy_eff is zero, to avoid an infinite value
            cost_con = cost_om_con * weight * (
                variables["carrier_prod"][loc_tech_carrier, timestep] / energy_eff
            )
        else
            cost_con = 0
        end
    else
        cost_con = 0
    end

    model_dict["expressions"]["cost_var_rhs"][cost, loc_tech, timestep] = (
        cost_prod + cost_con
    )

    return @constraint(
        backend_model, variables["cost_var"][cost, loc_tech, timestep] ==
        model_dict["expressions"]["cost_var_rhs"][cost, loc_tech, timestep]
    )
end

max_stars_repo_name: calliope-project/CalliopeJuMP

max_issues_repo_name: calliope-project/CalliopeJuMP

max_forks_repo_name: calliope-project/CalliopeJuMP


text:
struct Closure{F,Free}
    frees::Free
end

function (closure::Closure{F,X})(args...; kwargs...) where {F,X}
    F(closure.frees..., args...; kwargs...)
end


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "PORTA"
version = v"1.4.1"

# Collection of sources required to complete build
sources = [
    GitSource("https://github.com/bdoolittle/julia-porta.git", "93b99656f390c2252a0142bf9a4c22f5217a42da")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir
mkdir -p ${bindir}
make -C julia-porta/gnu-make/ CC=${CC}
cp julia-porta/gnu-make/bin/xporta${exeext} ${bindir}
cp julia-porta/gnu-make/bin/valid${exeext} ${bindir}
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# The products that we will ensure are always built
products = [
    ExecutableProduct("xporta", :xporta),
    ExecutableProduct("valid", :valid)
]

# Dependencies that must be installed before this package can be built
dependencies = Dependency[
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
# ---
# title: 1139. Largest 1-Bordered Square
# id: problem1139
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Dynamic Programming
# link: <https://leetcode.com/problems/largest-1-bordered-square/description/>
# hidden: true
# ---
#
# Given a 2D `grid` of `0`s and `1`s, return the number of elements in the
# largest **square**  subgrid that has all `1`s on its **border** , or `0` if
# such a subgrid doesn't exist in the `grid`.
#
#
#
# **Example 1:**
#
#
#
#     Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
#     Output: 9
#
#
# **Example 2:**
#
#
#
#     Input: grid = [[1,1,0,0]]
#     Output: 1
#
#
#
#
# **Constraints:**
#
#   * `1 <= grid.length <= 100`
#   * `1 <= grid[0].length <= 100`
#   * `grid[i][j]` is `0` or `1`
#
#
## @lc code=start
using LeetCode

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


text:
"""
    System

The abstract base type for a (quantum) system.
"""
abstract type System end

"""
    SubSystem{which}

A subsystem, i.e. limited to a set of coordinates.
"""
struct SubSystem{which} <: System end

"""
    quantum_numbers(system, a, b)

Return the quantum numbers characterizing `system` for the orbitals `a` and `b`.
"""
quantum_numbers(system, a, b) = quantum_numbers(system, a), quantum_numbers(system, b)

"""
    other_quantum_numbers(system, a, b)

Return the quantum numbers characterizing the orthogonal complement to
`system` for the orbitals `a` and `b`.
"""
other_quantum_numbers(system, a, b) = other_quantum_numbers(system, a), other_quantum_numbers(system, b)

# * Full system

"""
    FullSystem

The entire system, i.e. all coordinates.
"""
struct FullSystem <: System end

"""
    quantum_numbers(::FullSystem, o::SpinOrbital{<:Orbital})

The full system of an uncoupled spin-orbital is ``n\\ell m_\\ell; s
m_s``, where ``;`` denotes that the spatial and spin subsystems are
separable.
"""
quantum_numbers(::FullSystem, o::SpinOrbital{<:Orbital}) =
    quantum_numbers(SpatialSubSystem(), o), quantum_numbers(SpinSubSystem(), o)

"""
    quantum_numbers(::FullSystem, o::SpinOrbital{<:RelativisticOrbital})

The full system of a coupled spin-orbital is ``n\\ell s j m_j``.
"""
quantum_numbers(::FullSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    ((o.orb.n, o.orb.ℓ, half(1), o.orb.j), o.m[1])

"""
    other_quantum_numbers(::FullSystem, ::SpinOrbital)

No quantum numbers characterize the orthogonal complement to
[`FullSystem`](@ref).
"""
other_quantum_numbers(::FullSystem, ::SpinOrbital) = ((),missing)

# * Spatial subsystem

"""
    SpatialSubSystem

The spatial subsystem, i.e. the coordinates `r`, `θ`, and `ϕ`.
"""
const SpatialSubSystem = SubSystem{:spatial}

"""
    quantum_numbers(::SpatialSubSystem, o::SpinOrbital{<:Orbital})

The spatial subsystem of an uncoupled spin-orbital is ``n\\ell m_\\ell``.
"""
quantum_numbers(::SpatialSubSystem, o::SpinOrbital{<:Orbital}) =
    ((o.orb.n, o.orb.ℓ), o.m[1])

"""
    quantum_numbers(::SpatialSubSystem, o::SpinOrbital{<:RelativisticOrbital})

The spatial subsystem of a coupled spin-orbital is just ``n\\ell
m_\\ell``; ``m_\\ell`` is not a good quantum number.
"""
quantum_numbers(::SpatialSubSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    ((o.orb.n, o.orb.ℓ), missing)

"""
    other_quantum_numbers(::SpatialSubSystem, o::SpinOrbital{<:Orbital})

The orthogonal complement to [`SpatialSubSystem`](@ref) is
[`SpinSubSystem`](@ref), which is characterized by ``sm_s``.
"""
other_quantum_numbers(::SpatialSubSystem, o::SpinOrbital{<:Orbital}) =
    (half(1), o.m[2])

"""
    other_quantum_numbers(::SpatialSubSystem, o::SpinOrbital{<:RelativisticOrbital})

The orthogonal complement to [`SpatialSubSystem`](@ref) is
[`SpinSubSystem`](@ref), which is characterized by ``s``; its
projection is not a good quantum number in the coupled basis.
"""
other_quantum_numbers(::SpatialSubSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    (half(1), missing)

# * Orbital angular momentum subsystem

"""
    OrbitalAngularMomentaSubSystem

The orbital angular momentum subsystem, i.e. the coordinates, `θ` and
`ϕ`.
"""
const OrbitalAngularMomentumSubSystem = SubSystem{:orbital_angular_momentum}

"""
    quantum_numbers(::OrbitalAngularMomentumSubSystem, o::SpinOrbital{<:Orbital})

The orbital angular momentum subsystem of an uncoupled spin-orbital is ``\\ell m_\\ell``.
"""
quantum_numbers(::OrbitalAngularMomentumSubSystem, o::SpinOrbital{<:Orbital}) =
    (o.orb.ℓ, o.m[1])

"""
    quantum_numbers(::OrbitalAngularMomentumSubSystem, o::SpinOrbital{<:RelativisticOrbital})

The orbital angular momentum subsystem of a coupled spin-orbital is
just ``\\ell``; ``m_\\ell`` is not a good quantum number.
"""
quantum_numbers(::OrbitalAngularMomentumSubSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    (o.orb.ℓ, missing)

"""
    other_quantum_numbers(::OrbitalAngularMomentumSubSystem, o::SpinOrbital{<:Orbital})

The orthogonal complement to [`OrbitalAngularMomentumSubSystem`](@ref)
is characterized by the quantum numbers ``n s m_s``.
"""
other_quantum_numbers(::OrbitalAngularMomentumSubSystem, o::SpinOrbital{<:Orbital}) =
    ((o.orb.n,half(1)), o.m[2])

"""
    other_quantum_numbers(::OrbitalAngularMomentumSubSystem, o::SpinOrbital{<:RelativisticOrbital})

The orthogonal complement to [`OrbitalAngularMomentumSubSystem`](@ref)
is characterized by the quantum numbers ``n s``; the projection of the
latter is not a good quantum number in the coupled basis.
"""
other_quantum_numbers(::OrbitalAngularMomentumSubSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    ((o.orb.n,half(1)), missing)

const SpatialSubSystems = Union{SpatialSubSystem,OrbitalAngularMomentumSubSystem}

# * Spin subsystem

"""
    SpinSubSystem

The spin subsystem, i.e. the coordinate `s`.
"""
const SpinSubSystem = SubSystem{:spin}

"""
    quantum_numbers(::SpinSubSystem, o::SpinOrbital{<:Orbital})

The spin subsystem of an uncoupled spin-orbital is ``s m_s``.
"""
quantum_numbers(::SpinSubSystem, o::SpinOrbital{<:Orbital}) =
    (half(1), o.m[2])

"""
    quantum_numbers(::SpinSubSystem, o::SpinOrbital{<:RelativisticOrbital})

The spin subsystem of a coupled spin-orbital is just ``s``; ``m_s`` is
not a good quantum number.
"""
quantum_numbers(::SpinSubSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    (half(1), missing)

"""
    other_quantum_numbers(::SpinSubSystem, o::SpinOrbital{<:Orbital})

The orthogonal complement to [`SpinSubSystem`](@ref) is
[`SpatialSubSystem`](@ref) which is characterized by the quantum
numbers ``n \\ell m_\\ell``.
"""
other_quantum_numbers(::SpinSubSystem, o::SpinOrbital{<:Orbital}) =
    ((o.orb.n,o.orb.ℓ), o.m[1])

"""
    other_quantum_numbers(::SpinSubSystem, o::SpinOrbital{<:RelativisticOrbital})

The orthogonal complement to [`SpinSubSystem`](@ref) is
[`SpatialSubSystem`](@ref) which is characterized by the quantum
numbers ``n \\ell``; the projection of the latter is not a good
quantum number in the coupled basis.
"""
other_quantum_numbers(::SpinSubSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    ((o.orb.n,o.orb.ℓ), missing)

# * Total angular momentum subsystem

"""
    TotalAngularMomentumSubSystem

The total angular momentum subsystem, i.e. the coordinates, `θ`, `ϕ`, and
`s`.
"""
const TotalAngularMomentumSubSystem = SubSystem{:total_angular_momentum}

"""
    quantum_numbers(::TotalAngularMomentumSubSystem, o::SpinOrbital{<:Orbital})

The total angular momentum of an uncoupled spin-orbital is not a good
quantum number; only its projection is known. The system is specified
by ``\\ell m_\\ell; s m_s``, where ``;`` denotes that the spatial and
spin subsystems are separable.
"""
quantum_numbers(::TotalAngularMomentumSubSystem, o::SpinOrbital{<:Orbital}) =
    quantum_numbers(OrbitalAngularMomentumSubSystem(), o), quantum_numbers(SpinSubSystem(), o)

"""
    quantum_numbers(::TotalAngularMomentumSubSystem, o::SpinOrbital{<:RelativisticOrbital})

The total angular momentum subsystem of a coupled spin-orbital just
``\\ell s j m_j``.
"""
quantum_numbers(::TotalAngularMomentumSubSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    ((o.orb.ℓ, half(1), o.orb.j), o.m[1])

"""
    other_quantum_numbers(::TotalAngularMomentumSubSystem, o::SpinOrbital{<:Orbital})

The orthogonal complement to [`TotalAngularMomentumSubSystem`](@ref)
is characterized by the quantum number ``n``.
"""
other_quantum_numbers(::TotalAngularMomentumSubSystem, o::SpinOrbital{<:Orbital}) =
    (o.orb.n, missing)

"""
    other_quantum_numbers(::TotalAngularMomentumSubSystem, o::SpinOrbital{<:RelativisticOrbital})

The orthogonal complement to [`TotalAngularMomentumSubSystem`](@ref)
is characterized by the quantum number ``n``.
"""
other_quantum_numbers(::TotalAngularMomentumSubSystem, o::SpinOrbital{<:RelativisticOrbital}) =
    (o.orb.n, missing)

export quantum_numbers, other_quantum_numbers,
    SubSystem, FullSystem,
    SpatialSubSystem,
    OrbitalAngularMomentumSubSystem, SpinSubSystem,
    TotalAngularMomentumSubSystem


text:
using POMDPs
using POMDPModels
using DiscreteValueIteration

using BenchmarkTools

function bench_sparsevi(size)
    world = SimpleGridWorld(size=size)
    solver = SparseValueIterationSolver(max_iterations=500, belres=0.0)
    policy = solve(solver, world)
    return policy
end

function bench_vanillavi(size)
    world = SimpleGridWorld(size=size)
    solver = ValueIterationSolver(max_iterations=500, belres=0.0)
    policy = solve(solver, world)
    return policy
end

for size in [(10,10), (100, 100), (1000, 1000), (10000, 10000)]
    @show size
    @info "Sparse"
    @btime bench_sparsevi($size)
    @info "Vanilla"
    @btime bench_vanillavi($size)
end


text:
module DofsTests

end # module


text:
## ExoplanetsSysSim/examples/test.jl
## (c) 2015 Eric B. Ford

# workspace()
# reload("ExoplanetsSysSim")
using ExoplanetsSysSim

println("# Starting end-to-end test (setting parameters, creating physical catalogs, creating observed catalogs, computing summary statistics, computing the distance between them).  ")
test_eval_model()


text:
using Test
using QuantumLattices.Mathematics.VectorSpaces
using QuantumLattices.Mathematics.Combinatorics: Combinations
using QuantumLattices.Interfaces: dimension,⊕,rank,dims,inds

@testset "SimpleVectorSpace" begin
    id1,id2,id3=(1,1),(1,2),(1,3)

    vs=SimpleVectorSpace{'T'}(id1,id2)
    @test vs==deepcopy(vs)
    @test isequal(vs,deepcopy(vs))
    @test vs|>size==(2,)
    @test vs|>dimension==2
    @test vs|>collect==[id1,id2]
    @test vs[1]==id1 && vs[2]==id2
    @test searchsortedfirst(vs,id1)==1 && searchsortedfirst(vs,id2)==2
    @test findfirst(id1,vs)==1 && findfirst(id2,vs)==2
    @test findfirst((id1,id2),vs)==(1,2)
    @test id1 ∈ vs && id2 ∈ vs && id3 ∉ vs
    @test HasTable(typeof(vs))==HasTable(true)
    @test TableSorted(typeof(vs))==TableSorted(true)
    @test IsMultiIndexable(typeof(vs))==IsMultiIndexable(false)
    @test vs==id1⊕id2
    @test vs⊕id3==id1⊕id2⊕id3
    @test id3⊕vs==id3⊕id1⊕id2
    @test (id2⊕id3)⊕vs==id2⊕id3⊕id1⊕id2

    vs=SimpleVectorSpace{'F'}(id1,id2)
    @test vs==deepcopy(vs)
    @test isequal(vs,deepcopy(vs))
    @test vs|>size==(2,)
    @test vs|>dimension==2
    @test vs|>collect==[id1,id2]
    @test vs[1]==id1 && vs[2]==id2
    @test searchsortedfirst(vs,id1)==1 && searchsortedfirst(vs,id2)==2
    @test findfirst(id1,vs)==1 && findfirst(id2,vs)==2
    @test findfirst((id1,id2),vs)==(1,2)
    @test id1 ∈ vs && id2 ∈ vs && id3 ∉ vs
    @test HasTable(typeof(vs))==HasTable(true)
    @test TableSorted(typeof(vs))==TableSorted(false)
    @test IsMultiIndexable(typeof(vs))==IsMultiIndexable(false)
    @test vs==id1⊕id2
    @test vs⊕id3==id1⊕id2⊕id3
    @test id3⊕vs==id3⊕id1⊕id2
    @test (id2⊕id3)⊕vs==id2⊕id3⊕id1⊕id2
end

@testset "SimpleIndices" begin
    foi=SimpleIndices{'F'}(2,2,2)
    @test HasTable(typeof(foi))==HasTable(false)
    @test IsMultiIndexable(typeof(foi))==IsMultiIndexable(true)
    @test MultiIndexOrderStyle(typeof(foi))==MultiIndexOrderStyle('F')
    @test dimension(foi)==8
    @test dims(foi)==(2,2,2)
    @test rank(typeof(foi))==3
    @test inds((1,1,1),foi)==(1,1,1)
    @test Tuple((1,1,1),foi)==(1,1,1)
    @test foi|>collect==[(1,1,1),(2,1,1),(1,2,1),(2,2,1),(1,1,2),(2,1,2),(1,2,2),(2,2,2)]
    @test (1,1,1) ∈ foi && (1,2,3) ∉ foi
    for (i,finds) in enumerate(foi)
        @test findfirst(finds,foi)==i
        @test searchsortedfirst(foi,foi[i])==i
    end
    coi=SimpleIndices{'C'}(2,2,2)
    @test HasTable(typeof(coi))==HasTable(false)
    @test IsMultiIndexable(typeof(coi))==IsMultiIndexable(true)
    @test MultiIndexOrderStyle(typeof(coi))==MultiIndexOrderStyle('C')
    @test dimension(coi)==8
    @test dims(coi)==(2,2,2)
    @test rank(typeof(coi))==3
    @test inds((1,1,1),coi)==(1,1,1)
    @test Tuple((1,1,1),coi)==(1,1,1)
    @test (1,1,1) ∈ coi && (1,2,3) ∉ coi
    @test coi|>collect==[(1,1,1),(1,1,2),(1,2,1),(1,2,2),(2,1,1),(2,1,2),(2,2,1),(2,2,2)]
    for (i,cinds) in enumerate(coi)
        @test findfirst(cinds,coi)==i
        @test searchsortedfirst(coi,coi[i])==i
    end
end

@testset "TabledIndices" begin
    dims=(2,2)
    table=[(1,1),(1,2),(2,1),(2,2)]
    toi=TabledIndices{'T'}(dims,table)
    @test HasTable(typeof(toi))==HasTable(true)
    @test TableSorted(typeof(toi))==TableSorted(true)
    @test toi==TabledIndices{2}(DulPermutations,2)
    @test dimension(toi)==4
    @test toi|>collect==table
    @test (1,1) ∈ toi && (1,3) ∉ toi
    for i=1:length(toi)
        @test searchsortedfirst(toi,toi[i])==i
    end

    table=[(1,2),(2,1),(2,2),(1,1)]
    toi=TabledIndices{'F'}(dims,table)
    @test HasTable(typeof(toi))==HasTable(true)
    @test TableSorted(typeof(toi))==TableSorted(false)
    @test dimension(toi)==4
    @test toi|>collect==table
    @test (1,1) ∈ toi && (1,3) ∉ toi
    for i=1:length(toi)
        @test searchsortedfirst(toi,toi[i])==i
    end
end

struct VSZNamedVectorSpace{NS,BS<:Tuple,VS<:Tuple{Vararg{Vector}}} <: NamedVectorSpace{:zip,NS,BS,VS}
    contents::VS
end
@generated function VSZNamedVectorSpace{NS}(contents::Vector...) where NS
    @assert length(NS)==length(contents) && isa(NS,Tuple{Vararg{Symbol}})
    BS=Expr(:curly,:Tuple,[contents[i]|>eltype for i=1:length(NS)]...)
    return quote
        @assert mapreduce(length,==,contents)
        VSZNamedVectorSpace{NS,$BS,typeof(contents)}(contents)
    end
end

struct VSPNamedVectorSpace{NS,BS<:Tuple,VS<:Tuple{Vararg{Vector}}} <: NamedVectorSpace{:product,NS,BS,VS}
    contents::VS
end
@generated function VSPNamedVectorSpace{NS}(contents::Vector...) where NS
    @assert length(NS)==length(contents) && isa(NS,Tuple{Vararg{Symbol}})
    BS=Expr(:curly,:Tuple,[contents[i]|>eltype for i=1:length(NS)]...)
    return :(VSPNamedVectorSpace{NS,$BS,typeof(contents)}(contents))
end

@testset "NamedVectorSpace" begin
    @test IsMultiIndexable(NamedVectorSpace)==IsMultiIndexable(true)
    @test MultiIndexOrderStyle(NamedVectorSpace)==MultiIndexOrderStyle('C')

    nvs=VSZNamedVectorSpace{(:t,:U)}([1,2],[8.0,9.0])
    @test nvs|>keys==nvs|>typeof|>keys==(:t,:U)
    @test nvs|>values==([1,2],[8.0,9.0])
    @test nvs|>pairs|>collect==[:t=>[1,2],:U=>[8.0,9.0]]
    @test eltype(nvs,1)==eltype(nvs|>typeof,1)==Int
    @test eltype(nvs,2)==eltype(nvs|>typeof,2)==Float64
    @test nvs|>typeof|>rank==1
    @test dims(nvs)==(2,)
    elements=[(t=1,U=8.0),(t=2,U=9.0)]
    for i=1:dimension(nvs)
        @test NamedTuple(inds(elements[i],nvs),nvs)==elements[i]
    end
    @test nvs|>collect==elements

    nvs=VSPNamedVectorSpace{(:t,:U)}([1.0,2.0],[8.0,9.0])
    @test nvs|>typeof|>rank==2
    @test dims(nvs)==(2,2)
    elements=[(t=1.0,U=8.0),(t=1.0,U=9.0),(t=2.0,U=8.0),(t=2.0,U=9.0)]
    for i=1:dimension(nvs)
        @test NamedTuple(inds(elements[i],nvs),nvs)==elements[i]
    end
    @test nvs|>collect==elements
end


text:
using Polynomials

function mypolyval(p::Poly,x::Number)
    s=p[0]
    t=one(x)
    for i=1:length(p)-1
        t*=x
        s+=p[i]*t
    end
    s
end

function myhorner(p::Poly,x::Number)
    s=p[end]
    for i=length(p)-2:-1:0
        s=s*x+p[i]
    end
    s
end

n=10001
pbig=Poly(rand(n))
x=0.12345;

max_stars_repo_path: src/Module A - Short Julia Course/myfunctions.jl

max_stars_repo_name: ivanslapnicar/GIAN-Applied-NLA-Course

max_issues_repo_name: ivanslapnicar/GIAN-Applied-NLA-Course

max_forks_repo_name: ivanslapnicar/GIAN-Applied-NLA-Course


text:
module TestPackage

# Write your package code here.

using LinearAlgebra

function addition(a, b)
    return a+b
end

# Useless comment

export addition, eigvals

end