text:
using SparseArrays
function equilibriumConditions(vars)

    #----------------------------------------------------------------
    # Housekeeping
    #----------------------------------------------------------------
    # Unpack variables
    V						= reshape(vars[1:n_v] .+ vars_SS[1:n_v],I,J,N)  # value function
    g						= vars[n_v+1:n_v+n_g] .+ vars_SS[n_v+1:n_v+n_g] # distribution
    dab_aux					= reshape(dab,I*J*N,1)
    dab_g_aux               = reshape(dab_g,I_g*J_g*N,1)
    g_end					= (1 - sum(g .* dab_g_aux[1:end-1])) / dab_g[I_g,J_g,N]
    gg						= [g;g_end]
    K						= vars[n_v+n_g+1] + vars_SS[n_v+n_g+1]     # aggregate capital
    r_b                     = vars[n_v+n_g+2] + vars_SS[n_v+n_g+2]

    if aggregate_variables == 1
        aggY                    = vars[n_v+n_g+3] + vars_SS[n_v+n_g+3] # aggregate output
        aggC                    = vars[n_v+n_g+4] + vars_SS[n_v+n_g+4] # aggregate consumption
    elseif distributional_variables == 1
        C_Var                   = vars[n_v+n_g+3] + vars_SS[n_v+n_g+3] # consumption inequality
	    earn_Var                = vars[n_v+n_g+4] + vars_SS[n_v+n_g+4] # earnings inequality
    elseif distributional_variables_1 == 1
        C_WHTM                  = vars[n_v+n_g+3] + vars_SS[n_v+n_g+3] # consumption of wealthy hand-to-mouth
	    C_PHTM                  = vars[n_v+n_g+4] + vars_SS[n_v+n_g+4] # consumption of poor hand-to-mouth
        #C_NHTM                  = vars[n_v+n_g+3] + vars_SS[n_v+n_g+3]
    end

    aggZ      				= vars[n_v+n_g+n_p+1] + vars_SS[n_v+n_g+n_p+1]      # aggregate Z

    V_Dot					= vars[nVars+1:nVars+n_v]
    g_Dot					= vars[nVars+n_v+1:nVars+n_v+n_g]
    aggZ_Dot     			= vars[nVars+n_v+n_g+n_p+1]

    VEErrors				= vars[2*nVars+1:2*nVars+n_v]
    aggZ_Shock   			= vars[2*nVars+nEErrors+1]

    # Prices
    if permanent == 0
        w                   = (1 - aalpha) * (K ^ aalpha) * exp(aggZ) ^ (1-aalpha) * n_SS ^ (-aalpha)
        r_a                 = aalpha * (K ^ (aalpha - 1)) * (exp(aggZ) * n_SS) ^ (1 - aalpha) - ddelta
    elseif permanent == 1
        w                   = (1 - aalpha) * (K ^ aalpha) * (n_SS) ^ (-aalpha)
        r_a                 = aalpha * (K ^ (aalpha - 1)) * (n_SS) ^ (1 - aalpha) - ddelta
    end

    # Auxiliary variables
    r_b_borr				= r_b .+ borrwedge_SS

    #----------------------------------------------------------------
    # HJB Equation
    #----------------------------------------------------------------

    # Set of grids (calls external script)
    include("Subroutines/set_grids.jl")

    # Other necessary objects
    r_a_grid	 = repeat([r_a],I,J,N)
    l_grid		 = permutedims(repeat(ones(N,1),1,I,J), [2 3 1])
    y_shock      = y .* exp.(kappa * aggZ * (y .- y_mean) ./ std(y))
    y_shock_mean = dot(y_shock, y_dist) #y_shock * y_dist
    y_shock      = y_shock ./ y_shock_mean .* y_mean
    y_grid       = permutedims(repeat(y_shock',1,I,J), [2 3 1])

    ###
    # Compute derivatives w.r.t. illiquid assets a
    ###

    # Preparations
    VaF 			= 0*V
    VaB 			= 0*V
    Vamin 			= 0

    # Forward difference
    VaF[:,1:J-1,:] 	= (V[:,2:J,:]-V[:,1:J-1,:])./daf_grid[:,1:J-1,:]
    VaF[:,1:J-1,:] 	= max.(VaF[:,1:J-1,:],Vamin)

    # Backward difference
    VaB[:,2:J,:] 	= (V[:,2:J,:]-V[:,1:J-1,:])./dab_grid[:,2:J,:]
    VaB[:,2:J,:] 	= max.(VaB[:,2:J,:],Vamin)

    ###
    # Compute derivatives w.r.t. liquid assets b
    ###

    # Preparations (necessary to ensure that everything is a dual number, required by derivative software)
    VbF 			= 0*V
    VbB 			= 0*V
    Vbmin 			= 1e-8

    # Forward difference
    VbF[1:I-1,:,:]	= (V[2:I,:,:]-V[1:I-1,:,:])./dbf_grid[1:I-1,:,:]
    VbF[1:I-1,:,:] 	= max.(VbF[1:I-1,:,:],Vbmin)

    # Backward difference
    VbB[2:I,:,:] 	= (V[2:I,:,:]-V[1:I-1,:,:])./dbb_grid[2:I,:,:]
    VbB[2:I,:,:] 	= max.(VbB[2:I,:,:],Vbmin)

    ###
    # Consumption decision
    ###

    # Preparations
    cF 				= 0 * V
    sF 				= 0 * V
    HcF 			= 0 * V

    cB 				= 0 * V
    sB 				= 0 * V
    HcB 			= 0 * V

    c0 				= 0 * V
    s0 				= 0 * V
    Hc0 			= 0 * V

    # Decisions conditional on a particular direction of derivative
    cF[1:I-1,:,:] 	= VbF[1:I-1,:,:].^(-1/ggamma)
    cF[I,:,:] 		= zeros(1,J,N)
    if permanent == 1
        sF[1:I-1,:,:] 	= ((1-xxi)-tau_I) * w * l_grid[1:I-1,:,:] .* y_grid[1:I-1,:,:] .+ b_grid[1:I-1,:,:] .* (r_b_grid[1:I-1,:,:] .+ ddeath*pam - aggZ) .+ trans_grid[1:I-1,:,:] - cF[1:I-1,:,:]
    elseif permanent == 0
        sF[1:I-1,:,:] 	= ((1-xxi)-tau_I) * w * l_grid[1:I-1,:,:] .* y_grid[1:I-1,:,:] .+ b_grid[1:I-1,:,:] .* (r_b_grid[1:I-1,:,:] .+ ddeath*pam) .+ trans_grid[1:I-1,:,:] - cF[1:I-1,:,:]
    end
    sF[I,:,:] 		= zeros(1,J,N)
    HcF[1:I-1,:,:] 	= u_fn(cF[1:I-1,:,:], ggamma) .+ VbF[1:I-1,:,:] .* sF[1:I-1,:,:]
    HcF[I,:,:] 		= -1e12*ones(1,J,N)
    validF 			= (sF .> 0)

    cB[2:I,:,:] 	= VbB[2:I,:,:].^(-1/ggamma)
    if permanent == 1
        cB[1,:,:] 		= ((1-xxi)-tau_I) * w * l_grid[1,:,:] .* y_grid[1,:,:] .+ b_grid[1,:,:] .* (r_b_grid[1,:,:] .+ ddeath*pam - aggZ) .+ trans_grid[1,:,:]
        sB[2:I,:,:] 	= ((1-xxi)-tau_I) * w * l_grid[2:I,:,:] .* y_grid[2:I,:,:] .+ b_grid[2:I,:,:] .* (r_b_grid[2:I,:,:] .+ ddeath*pam - aggZ) .+ trans_grid[2:I,:,:] - cB[2:I,:,:]
    elseif permanent == 0
        cB[1,:,:] 	= ((1-xxi)-tau_I) * w * l_grid[1,:,:] .* y_grid[1,:,:] .+
            b_grid[1,:,:] .* (r_b_grid[1,:,:] .+ ddeath*pam) .+ trans_grid[1,:,:]
        sB[2:I,:,:] = ((1-xxi)-tau_I) * w * l_grid[2:I,:,:] .*
            y_grid[2:I,:,:] .+ b_grid[2:I,:,:] .* (r_b_grid[2:I,:,:] .+ ddeath*pam) .+
            trans_grid[2:I,:,:] - cB[2:I,:,:]
    end
    sB[1,:,:] 		= zeros(1,J,N)
    HcB[:,:,:] 		= u_fn(cB,ggamma) .+ VbB .* sB
    validB 			= (sB .< 0)

if permanent == 1
    c0[:,:,:] 		= ((1-xxi)-tau_I) * w * l_grid[:,:,:] .* y_grid[:,:,:] .+ b_grid[:,:,:] .* (r_b_grid[:,:,:] .+ ddeath*pam - aggZ) .+ trans_grid[:,:,:]
elseif permanent == 0
    c0[:,:,:] 		= ((1-xxi)-tau_I) * w * l_grid[:,:,:] .* y_grid[:,:,:] .+ b_grid[:,:,:] .* (r_b_grid[:,:,:] .+ ddeath*pam) .+ trans_grid[:,:,:]
end
s0[:,:,:] 		= zeros(I,J,N)
Hc0[:,:,:] 		= u_fn(c0,ggamma)

# Which direction to use
IcF				= IcF_SS
IcB				= IcB_SS
Ic0				= Ic0_SS

# Optimal consumption and liquid savings
c 				= IcF .* cF .+ IcB .* cB .+ Ic0 .* c0
s 				= IcF .* sF .+ IcB .* sB .+ Ic0 .* s0
u 				= u_fn(c,ggamma)

###
# Deposit decision
###

# Preparations
dFB 			= 0*V
HdFB 			= 0*V
dBF 			= 0*V
HdBF 			= 0*V
dBB 			= 0*V
HdBB 			= 0*V

# Decisions conditional on a particular direction of derivative
dFB[2:I,1:J-1,:]	= opt_deposits(VaF[2:I,1:J-1,:], VbB[2:I,1:J-1,:], a_grid[2:I,1:J-1,:], chi0, chi1, chi2, a_lb)
dFB[:,J,:]			= zeros(I,1,N)
dFB[1,1:J-1,:] 		= zeros(1,J-1,N)
HdFB[2:I,1:J-1,:] 	= VaF[2:I,1:J-1,:] .* dFB[2:I,1:J-1,:] - VbB[2:I,1:J-1,:] .* (dFB[2:I,1:J-1,:] .+ adj_cost_fn(dFB[2:I,1:J-1,:],a_grid[2:I,1:J-1,:], chi0, chi1, chi2, a_lb))
HdFB[:,J,:] 		= -1.0e12 * ones(I,1,N)
HdFB[1,1:J-1,:] 	= -1.0e12 * ones(1,J-1,N)
validFB 			= (dFB .> 0) .* (HdFB .> 0)

dBF[1:I-1,2:J,:] 	= opt_deposits(VaB[1:I-1,2:J,:],VbF[1:I-1,2:J,:],a_grid[1:I-1,2:J,:], chi0, chi1, chi2, a_lb)
dBF[:,1,:] 			= zeros(I,1,N)
dBF[I,2:J,:]		= zeros(1,J-1,N)
HdBF[1:I-1,2:J,:] 	= VaB[1:I-1,2:J,:] .* dBF[1:I-1,2:J,:] - VbF[1:I-1,2:J,:] .* (dBF[1:I-1,2:J,:] .+ adj_cost_fn(dBF[1:I-1,2:J,:],a_grid[1:I-1,2:J,:], chi0, chi1, chi2, a_lb))
HdBF[:,1,:] 		= -1.0e12 * ones(I,1,N)
HdBF[I,2:J,:] 		= -1.0e12 * ones(1,J-1,N)
validBF 			= (dBF .<= -adj_cost_fn(dBF,a_grid, chi0, chi1, chi2, a_lb)) .* (HdBF .> 0)

VbB[1,2:J,:] 		= u_fn(cB[1,2:J,:],ggamma)
dBB[:,2:J,:]		= opt_deposits(VaB[:,2:J,:],VbB[:,2:J,:],a_grid[:,2:J,:], chi0, chi1, chi2, a_lb)
dBB[:,1,:] 			= zeros(I,1,N)
HdBB[:,2:J,:] 		= VaB[:,2:J,:] .* dBB[:,2:J,:] - VbB[:,2:J,:] .* (dBB[:,2:J,:] .+ adj_cost_fn(dBB[:,2:J,:],a_grid[:,2:J,:], chi0, chi1, chi2, a_lb))
HdBB[:,1,:] 		= -1.0e12 * ones(I,1,N)
validBB 			= (dBB .> -adj_cost_fn(dBB,a_grid, chi0, chi1, chi2, a_lb)) .*
    (dBB .<= 0) .* (HdBB .> 0)

# Which direction to use
IcFB				= IcFB_SS
IcBF				= IcBF_SS
IcBB				= IcBB_SS
Ic00				= Ic00_SS

# Optimal deposit decision
d = IcFB .* dFB .+ IcBF .* dBF .+ IcBB .* dBB .+ Ic00 .* zeros(I,J,N)

## Interpolate
d_g = reshape(interp_decision*d[:],I_g,J_g,N)
s_g = reshape(interp_decision*s[:],I_g,J_g,N)
c_g = reshape(interp_decision*c[:],I_g,J_g,N)

###
# Construct transition matrix
###

tmp = reshape(gg,I_g,J_g,N)
audriftB = 0*tmp
audriftF = 0*tmp
budriftB = 0*tmp
budriftF = 0*tmp

chi = 0*V
yy = 0*V
zeta = 0*V

X = 0*V
Y = 0*V
Z = 0*V

chiu = 0*tmp
yyu = 0*tmp
zetau = 0*tmp

Xu = 0*tmp
Yu = 0*tmp
Zu = 0*tmp

# Compute drifts for HJB
if permanent == 1
    adriftB = min.(d,0) .+ min.(a_grid .* (r_a_grid .+ ddeath*pam - aggZ) .+
                                xxi * w * l_grid .* y_grid,0)
    adriftF = max.(d,0) .+ max.(a_grid .* (r_a_grid .+ ddeath*pam - aggZ) .+
                                xxi * w * l_grid .* y_grid,0)
elseif permanent == 0
    adriftB = min.(d,0) .+ min.(a_grid .* (r_a_grid .+ ddeath*pam) .+
                                xxi * w * l_grid .* y_grid,0)
    adriftF = max.(d,0) .+ max.(a_grid .* (r_a_grid .+ ddeath*pam) .+
                                xxi * w * l_grid .* y_grid,0)
end

bdriftB = min.(-d - adj_cost_fn(d,a_grid, chi0, chi1, chi2, a_lb),0) .+ min.(s,0)
bdriftF = max.(-d - adj_cost_fn(d,a_grid, chi0, chi1, chi2, a_lb),0) .+ max.(s,0)

# Compute drifts for KFE
if permanent == 0
    audriftB[1:I_g-1,:,:] = min.(d_g[1:I_g-1,:,:] .+ a_g_grid[1:I_g-1,:,:] .*
                                 (r_a_g_grid[1:I_g-1,:,:] .+ ddeath*pam) .+ xxi *
                                 w * l_g_grid[1:I_g-1,:,:] .* y_g_grid[1:I_g-1,:,:],0)
    audriftB[I_g,:,:] = min.(d_g[I_g,:,:] .+ a_g_grid[I_g,:,:] .*
                             (r_a_g_grid[I_g,:,:] .+ ddeath*pam) .+ xxi * w *
                             l_g_grid[I_g,:,:] .* y_g_grid[I_g,:,:],0)
    audriftF[1:I_g-1,:,:] = max.(d_g[1:I_g-1,:,:] .+ a_g_grid[1:I_g-1,:,:] .*
                                 (r_a_g_grid[1:I_g-1,:,:] .+ ddeath*pam) .+
                                 xxi * w * l_g_grid[1:I_g-1,:,:] .*
                                 y_g_grid[1:I_g-1,:,:],0)
    audriftF[I_g,:,:] = max.(d_g[I_g,:,:] .+ a_g_grid[I_g,:,:] .*
                             (r_a_g_grid[I_g,:,:] .+ ddeath*pam) .+
                             xxi * w * l_g_grid[I_g,:,:] .* y_g_grid[I_g,:,:],0)

    budriftB[1:I_g-1,:,:] = min.(s_g[1:I_g-1,:,:] - d_g[1:I_g-1,:,:] -
                                 adj_cost_fn(d_g[1:I_g-1,:,:], a_g_grid[1:I_g-1,:,:],
                                             chi0, chi1, chi2, a_lb),0)
    budriftB[I_g,:,:] = min.(s_g[I_g,:,:] - d_g[I_g,:,:] -
                             adj_cost_fn(d_g[I_g,:,:],a_g_grid[I_g,:,:],
                                         chi0, chi1, chi2, a_lb),0)
    budriftF[1:I_g-1,:,:] = max.(s_g[1:I_g-1,:,:] - d_g[1:I_g-1,:,:] -
                                 adj_cost_fn(d_g[1:I_g-1,:,:], a_g_grid[1:I_g-1,:,:],
                                             chi0, chi1, chi2, a_lb),0)
    budriftF[I_g,:,:] = max.(s_g[I_g,:,:] - d_g[I_g,:,:] -
                             adj_cost_fn(d_g[I_g,:,:],a_g_grid[I_g,:,:],
                                         chi0, chi1, chi2, a_lb),0)
elseif permanent == 1
    audriftB[1:I_g-1,:,:] = min.(d_g[1:I_g-1,:,:] .+ a_g_grid[1:I_g-1,:,:] .*
                                 (r_a_g_grid[1:I_g-1,:,:] .+ ddeath*pam) .+ xxi *
                                 w * l_g_grid[1:I_g-1,:,:] .* y_g_grid[1:I_g-1,:,:]
                                 - aggZ * a_g_grid[1:I_g-1,:,:], 0)
    audriftB[I_g,:,:] = min.(d_g[I_g,:,:] .+ a_g_grid[I_g,:,:] .* (r_a_g_grid[I_g,:,:] .+ ddeath*pam) .+ xxi * w * l_g_grid[I_g,:,:] .* y_g_grid[I_g,:,:] - aggZ * a_g_grid[I_g,:,:],0)
    audriftF[1:I_g-1,:,:] = max.(d_g[1:I_g-1,:,:] .+ a_g_grid[1:I_g-1,:,:] .* (r_a_g_grid[1:I_g-1,:,:] .+ ddeath*pam) .+ xxi * w * l_g_grid[1:I_g-1,:,:] .* y_g_grid[1:I_g-1,:,:] - aggZ * a_g_grid[1:I_g-1,:,:],0)
    audriftF[I_g,:,:] = max.(d_g[I_g,:,:] .+ a_g_grid[I_g,:,:] .* (r_a_g_grid[I_g,:,:] .+ ddeath*pam) .+ xxi * w * l_g_grid[I_g,:,:] .* y_g_grid[I_g,:,:] - aggZ * a_g_grid[I_g,:,:],0)

    budriftB[1:I_g-1,:,:] = min.(s_g[1:I_g-1,:,:] - d_g[1:I_g-1,:,:] - adj_cost_fn(d_g[1:I_g-1,:,:],a_g_grid[1:I_g-1,:,:], chi0, chi1, chi2, a_lb) - aggZ * b_g_grid[1:I_g-1,:,:],0)
    budriftB[I_g,:,:] = min.(s_g[I_g,:,:] - d_g[I_g,:,:] - adj_cost_fn(d_g[I_g,:,:],a_g_grid[I_g,:,:], chi0, chi1, chi2, a_lb) - aggZ * b_g_grid[I_g,:,:],0)
    budriftF[1:I_g-1,:,:] = max.(s_g[1:I_g-1,:,:] - d_g[1:I_g-1,:,:] - adj_cost_fn(d_g[1:I_g-1,:,:],a_g_grid[1:I_g-1,:,:], chi0, chi1, chi2, a_lb) - aggZ * b_g_grid[1:I_g-1,:,:],0)
    budriftF[I_g,:,:] = max.(s_g[I_g,:,:] - d_g[I_g,:,:] -
                             adj_cost_fn(d_g[I_g,:,:],a_g_grid[I_g,:,:],
                                         chi0, chi1, chi2, a_lb) - aggZ *
                             b_g_grid[I_g,:,:],0)
end

# Derive transition matrices
include("Subroutines/transition_a_deriva.jl")
include("Subroutines/transition_b_deriva.jl")
include("Subroutines/transition_c_deriva.jl")

# full transition matrix
A = aa + bb + cc

#----------------------------------------------------------------
# KFE
#----------------------------------------------------------------

# KFE
AT = aau + bbu + ccu
AT = AT'
gg_tilde            = dab_g_tilde_mat * gg
gIntermediate       = AT * gg_tilde
dab_g_tilde_mat_inv = spdiagm(0 => vec(repeat(1.0 ./ dab_g_tilde,N,1)))
gIntermediate       = dab_g_tilde_mat_inv * gIntermediate

dab_g_small = reshape(dab_g[:,:,1],I_g*J_g,1)

loc = findall(b .== 0)
dab_g_small       = dab_g_small ./ dab_g_small[loc]*ddeath
dab_g_small[loc] .= 0.0
death_process         = -ddeath * my_speye(I_g*J_g)
death_process[loc,:]  = vec(dab_g_small)
death_process         = kron(my_speye(N), death_process)

gIntermediate = gIntermediate + death_process * gg

# find death-corrected savings

a_g_grid_aux = reshape(a_g_grid,I_g*J_g*N,1)
a_save = sum(gIntermediate .* dab_g_aux .* a_g_grid_aux)

b_g_grid_aux = reshape(b_g_grid,I_g*J_g*N,1)
b_save = sum(gIntermediate .* dab_g_aux .* b_g_grid_aux)

# consumption for low types and high types

c_low     = c[:,:,1]
dab_low   = dab[:,:,1]
c_high    = c[:,:,2]
dab_high  = dab[:,:,2]

#----------------------------------------------------------------
# Compute equilibrium conditions
#----------------------------------------------------------------

# HJB equation
if permanent == 0
    hjbResidual = reshape(u,I*J*N,1) + A * reshape(V,I*J*N,1) + V_Dot + VEErrors - (rrho + ddeath) * reshape(V,I*J*N,1)
elseif permanent == 1
    hjbResidual = reshape(u,I*J*N,1) + A * reshape(V,I*J*N,1) + V_Dot + VEErrors - (rrho + ddeath - (1 - ggamma) * aggZ) * reshape(V,I*J*N,1)
end

# KFE
gResidual 			= g_Dot - gIntermediate[1:n_g,1]

# Aggregate conditions
if permanent == 0

	if K_liquid == 1
        K_out           = sum((a_g_grid[:] .+ b_g_grid[:]) .* gg .* dab_g[:])
    else
        K_out           = sum(a_g_grid[:] .* gg .* dab_g[:])
    end
    if r_b_fix == 1
        r_b_out         = r_b_SS
    elseif r_b_phi == 1
        r_b_out			= sum(b_g_grid[:] .* gg .* dab_g[:])
    elseif B_fix == 1
        r_b_out         = 0
	elseif K_liquid == 1
		r_b_out			= r_a_out - illiquid_wedge
    end

    if aggregate_variables == 1
        aggY_out			= (K ^ aalpha) * (exp(aggZ) * n_SS) ^ (1 - aalpha)
        aggC_out			= sum(c_g[:] .* gg .* dab_g[:])
    elseif distributional_variables == 1
        C_Var_out           = sum(log(c_g[:]).^2 .* gg .* dab_g[:]) - sum(log(c_g[:]) .* gg .* dab_g[:])^2
        earn                = log((1-tau_I) * w * l_g_grid .* y_g_grid + b_g_grid .* (r_b_g_grid + ddeath*pam) + trans_grid + a_g_grid .* (r_a_g_grid + ddeath*pam))
        earn_Var_out        = sum(earn[:].^2 .* gg .* dab_g[:]) - sum(earn[:] .* gg .* dab_g[:])^2
    elseif distributional_variables_1 == 1
        WHTM_indicator      = zeros(I_g,J_g,N)
        WHTM_indicator[b_g_0pos:b_g_0pos+1,a_g_0pos+2:end,:] = 1
        WHTM_out            = sum(WHTM_indicator[:] .* gg .* dab_g[:])
        #C_WHTM_out          = sum(WHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])/WHTM_out
        C_WHTM_out          = sum(WHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])

        PHTM_indicator      = zeros(I_g,J_g,N)
        PHTM_indicator[b_g_0pos:b_g_0pos+1,a_g_0pos:a_g_0pos+2:end,:] = 1
        PHTM_out            = sum(PHTM_indicator[:] .* gg .* dab_g[:])
        #C_PHTM_out          = sum(PHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])/PHTM_out
        C_PHTM_out          = sum(PHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])

        NHTM_indicator      = zeros(I_g,J_g,N)
        NHTM_indicator[b_g_0pos+2:end,a_g_0pos+2:end,:] = 1
        #NHTM_indicator      = zeros(I_g,J_g,N) NHTM_indicator[b_g_0pos+2:end,:,:] = 1
        NHTM_indicator      = zeros(I_g,J_g,N)
        NHTM_indicator[b_g_0pos+3:end,2:end,:] = 1
        #NHTM_indicator(3:b_g_0pos-1,:,:) = 1
        NHTM_out            = sum(NHTM_indicator[:] .* gg .* dab_g[:])
        C_NHTM_out          = sum(NHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])/NHTM_out
    end

elseif permanent == 1

	if K_liquid == 1
	    K_out               = sum((a_g_grid[:] + b_g_grid[:]) .* gg .* dab_g[:])
	elseif K_liquid == 0
		K_out               = sum(a_g_grid[:] .* gg .* dab_g[:])
	end
    if r_b_fix == 1
        r_b_out         = r_b_SS
    elseif r_b_phi == 1
        r_b_out			= sum(b_g_grid[:] .* gg .* dab_g[:])
    elseif B_fix == 1
        r_b_out         = 0
    elseif K_liquid == 1
        r_b_out         = r_a_out - illiquid_wedge
    end

    if aggregate_variables == 1
        aggY_out			= (K ^ aalpha) * (n_SS ^ (1 - aalpha))
        aggC_out			= sum(c_g[:] .* gg .* dab_g[:])
    elseif distributional_variables == 1
        C_Var_out           = sum(log(c_g[:]).^2 .* gg .* dab_g[:]) - sum(log(c_g[:]) .* gg .* dab_g[:])^2
        earn                = log((1-tau_I) * w * l_g_grid .* y_g_grid + b_g_grid .* (r_b_g_grid + ddeath*pam) + trans_grid + a_g_grid .* (r_a_g_grid + ddeath*pam))
        earn_Var_out        = sum(earn[:].^2 .* gg .* dab_g[:]) - sum(earn[:] .* gg .* dab_g[:])^2
    elseif distributional_variables_1 == 1
        WHTM_indicator      = zeros(I_g,J_g,N)
        WHTM_indicator[b_g_0pos:b_g_0pos+1,a_g_0pos+2:end,:] = 1
        WHTM_out            = sum(WHTM_indicator[:] .* gg .* dab_g[:])
        #C_WHTM_out          = sum(WHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])/WHTM_out
        C_WHTM_out          = sum(WHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])

        PHTM_indicator      = zeros(I_g,J_g,N)
        PHTM_indicator[b_g_0pos:b_g_0pos+1,a_g_0pos:a_g_0pos+2:end,:] = 1
        PHTM_out            = sum(PHTM_indicator[:] .* gg .* dab_g[:])
        #C_PHTM_out          = sum(PHTM_indicator(:] .* c_g(:] .* gg .* dab_g(:])/PHTM_out
        C_PHTM_out          = sum(PHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])

        NHTM_indicator      = zeros(I_g,J_g,N)
        NHTM_indicator[b_g_0pos+2:end,:,:] = 1
        #NHTM_indicator(3:b_g_0pos-1,:,:] = 1
        NHTM_out            = sum(NHTM_indicator[:] .* gg .* dab_g[:])
        C_NHTM_out          = sum(NHTM_indicator[:] .* c_g[:] .* gg .* dab_g[:])/NHTM_out
    end
end

K_Residual			= K_out - K
if r_b_fix == 1
    r_b_Residual    = r_b_out - r_b
elseif r_b_phi == 1
    r_b_Residual    = r_b_out - B_SS * exp(1/pphi * (r_b - r_b_SS))
elseif B_fix == 1
    r_b_Residual    = r_b_out - b_save
elseif K_liquid == 1
	r_b_Residual	= r_b_out - r_b
end

if aggregate_variables == 1
    Y_Residual			= aggY_out - aggY
    C_Residual			= aggC_out - aggC
elseif distributional_variables == 1
    C_Var_Residual      = C_Var_out - C_Var
    earn_Var_Residual   = earn_Var_out - earn_Var
elseif distributional_variables_1 == 1
    C_WHTM_Residual     = C_WHTM_out - C_WHTM
	C_PHTM_Residual     = C_PHTM_out - C_PHTM
    #C_NHTM_Residual     = C_NHTM_out - C_NHTM
end

# Law of motion for aggregate tfp shock
aggZ_Residual 	= aggZ_Dot - (-nnu_aggZ * aggZ + ssigma_aggZ * aggZ_Shock)

    #  Package results
    if aggregate_variables == 1
        vResidual = [hjbResidual; gResidual; K_Residual; r_b_Residual; Y_Residual; C_Residual; aggZ_Residual]
    elseif distributional_variables == 1
        vResidual = [hjbResidual; gResidual; K_Residual; r_b_Residual; C_Var_Residual; earn_Var_Residual; aggZ_Residual]
    elseif distributional_variables_1 == 1
        vResidual = [hjbResidual; gResidual; K_Residual; r_b_Residual; C_WHTM_Residual; C_PHTM_Residual; aggZ_Residual]
    else
        vResidual = [hjbResidual; gResidual; K_Residual; r_b_Residual; aggZ_Residual]
    end
    return vResidual
end


text:
#!/usr/bin/env julia

using BSONify, Test, SafeTestsets

@time begin
@time @safetestset "Reconstitute" begin include("reconstitute_test.jl") end
end

ext: jl

max_stars_repo_name: OliverColeman/BSONify

max_forks_repo_name: OliverColeman/BSONify


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

if !isdefined(@__MODULE__, :DefsTopicPurposeCreator)
    const DefsTopicPurposeCreator = String
else
    @warn("Skipping redefinition of DefsTopicPurposeCreator to String")
end


text:
# Run set_board_size(N::Int) once you include go.jl

module AlphaGo
using CuArrays
using Flux
using Flux: crossentropy, back!, mse
using StatsBase: Weights

struct IllegalMove <:Exception end
abstract type Position end
abstract type GameEnv end

struct PositionWithContext
  position::Position
  next_move
  result::Int
end

export MCTSPlayer, NeuralNet, pick_move, play_move!,
      initialize_game!, set_result!,
      should_resign, is_done, result, train!, selfplay,
      train, play, load_model, GoEnv, Position, all_legal_moves,
      ChessEnv, result

include("game/go/go.jl")
include("game/env.jl")
include("mcts.jl")
include("mcts_play.jl")
include("features.jl")
include("neural_net.jl")
include("selfplay.jl")
include("train.jl")
include("play.jl")

end #module


text:
using Test
using PointerArithmetic

include("pointer.jl")
include("array_slice.jl")
include("slice.jl")


text:
# Compile-time constants

# Implementation limits:
const MPI_MAX_DATAREP_STRING = Cint(128)
const MPI_MAX_ERROR_STRING = Cint(1024)
const MPI_MAX_INFO_KEY = Cint(256)
const MPI_MAX_INFO_VAL = Cint(1024)
const MPI_MAX_LIBRARY_VERSION_STRING = Cint(8192)
const MPI_MAX_OBJECT_NAME = Cint(128)
const MPI_MAX_PORT_NAME = Cint(1024)
const MPI_MAX_PROCESSOR_NAME = Cint(256)

# Types

# Various (signed) integer types:
const MPI_Aint = Int64
const MPI_Count = Int64
const MPI_Fint = Int32
const MPI_Offset = Int64

# Status:
struct MPI_Status
    _private0::Cint
    _private1::Cint
    _private2::Cint
    _private3::Cint
    _private4::Csize_t
    MPI_SOURCE::Cint
    MPI_TAG::Cint
    MPI_ERROR::Cint
end

# Opaque handles:
const MPI_Comm = UInt
const MPI_Datatype = UInt
const MPI_Errhandler = UInt
const MPI_File = UInt
const MPI_Group = UInt
const MPI_Info = UInt
const MPI_Message = UInt
const MPI_Op = UInt
const MPI_Request = UInt
const MPI_Win = UInt

# Function pointers:
const MPI_Comm_copy_attr_function = Ptr{Cvoid}
const MPI_Comm_delete_attr_function = Ptr{Cvoid}
const MPI_Comm_errhandler_function = Ptr{Cvoid}
const MPI_Comm_errhandler_fn = MPI_Comm_errhandler_function
const MPI_Copy_function = MPI_Comm_copy_attr_function
const MPI_Datarep_conversion_function = Ptr{Cvoid}
const MPI_Datarep_extent_function = Ptr{Cvoid}
const MPI_Delete_function = Ptr{Cvoid}
const MPI_File_errhandler_function = Ptr{Cvoid}
const MPI_File_errhandler_fn = Ptr{Cvoid}
const MPI_Grequest_cancel_function = Ptr{Cvoid}
const MPI_Grequest_free_function = Ptr{Cvoid}
const MPI_Grequest_query_function = Ptr{Cvoid}
const MPI_Type_copy_attr_function = Ptr{Cvoid}
const MPI_Type_delete_attr_function = Ptr{Cvoid}
const MPI_User_function = Ptr{Cvoid}
const MPI_Win_copy_attr_function = Ptr{Cvoid}
const MPI_Win_delete_attr_function = Ptr{Cvoid}
const MPI_Win_errhandler_function = Ptr{Cvoid}
const MPI_Win_errhandler_fn = MPI_Win_errhandler_function

@const_ref MPI_ANY_SOURCE Cint unsafe_load(cglobal((:MPICONSTANTS_ANY_SOURCE, libmpiconstants), Cint))
@const_ref MPI_ANY_TAG Cint unsafe_load(cglobal((:MPICONSTANTS_ANY_TAG, libmpiconstants), Cint))
@const_ref MPI_PROC_NULL Cint unsafe_load(cglobal((:MPICONSTANTS_PROC_NULL, libmpiconstants), Cint))
@const_ref MPI_ROOT Cint unsafe_load(cglobal((:MPICONSTANTS_ROOT, libmpiconstants), Cint))
@const_ref MPI_CART Cint unsafe_load(cglobal((:MPICONSTANTS_CART, libmpiconstants), Cint))
@const_ref MPI_DIST_GRAPH Cint unsafe_load(cglobal((:MPICONSTANTS_DIST_GRAPH, libmpiconstants), Cint))
@const_ref MPI_GRAPH Cint unsafe_load(cglobal((:MPICONSTANTS_GRAPH, libmpiconstants), Cint))
@const_ref MPI_CONGRUENT Cint unsafe_load(cglobal((:MPICONSTANTS_CONGRUENT, libmpiconstants), Cint))
@const_ref MPI_IDENT Cint unsafe_load(cglobal((:MPICONSTANTS_IDENT, libmpiconstants), Cint))
@const_ref MPI_SIMILAR Cint unsafe_load(cglobal((:MPICONSTANTS_SIMILAR, libmpiconstants), Cint))
@const_ref MPI_UNEQUAL Cint unsafe_load(cglobal((:MPICONSTANTS_UNEQUAL, libmpiconstants), Cint))
@const_ref MPI_KEYVAL_INVALID Cint unsafe_load(cglobal((:MPICONSTANTS_KEYVAL_INVALID, libmpiconstants), Cint))
@const_ref MPI_UNDEFINED Cint unsafe_load(cglobal((:MPICONSTANTS_UNDEFINED, libmpiconstants), Cint))
@const_ref MPI_APPNUM Cint unsafe_load(cglobal((:MPICONSTANTS_APPNUM, libmpiconstants), Cint))
@const_ref MPI_HOST Cint unsafe_load(cglobal((:MPICONSTANTS_HOST, libmpiconstants), Cint))
@const_ref MPI_IO Cint unsafe_load(cglobal((:MPICONSTANTS_IO, libmpiconstants), Cint))
@const_ref MPI_LASTUSEDCODE Cint unsafe_load(cglobal((:MPICONSTANTS_LASTUSEDCODE, libmpiconstants), Cint))
@const_ref MPI_TAG_UB Cint unsafe_load(cglobal((:MPICONSTANTS_TAG_UB, libmpiconstants), Cint))
@const_ref MPI_UNIVERSE_SIZE Cint unsafe_load(cglobal((:MPICONSTANTS_UNIVERSE_SIZE, libmpiconstants), Cint))
@const_ref MPI_WIN_BASE Cint unsafe_load(cglobal((:MPICONSTANTS_WIN_BASE, libmpiconstants), Cint))
@const_ref MPI_WIN_CREATE_FLAVOR Cint unsafe_load(cglobal((:MPICONSTANTS_WIN_CREATE_FLAVOR, libmpiconstants), Cint))
@const_ref MPI_WIN_DISP_UNIT Cint unsafe_load(cglobal((:MPICONSTANTS_WIN_DISP_UNIT, libmpiconstants), Cint))
@const_ref MPI_WIN_MODEL Cint unsafe_load(cglobal((:MPICONSTANTS_WIN_MODEL, libmpiconstants), Cint))
@const_ref MPI_WIN_SIZE Cint unsafe_load(cglobal((:MPICONSTANTS_WIN_SIZE, libmpiconstants), Cint))
@const_ref MPI_WTIME_IS_GLOBAL Cint unsafe_load(cglobal((:MPICONSTANTS_WTIME_IS_GLOBAL, libmpiconstants), Cint))
@const_ref MPI_COMBINER_CONTIGUOUS Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_CONTIGUOUS, libmpiconstants), Cint))
@const_ref MPI_COMBINER_DARRAY Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_DARRAY, libmpiconstants), Cint))
@const_ref MPI_COMBINER_DUP Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_DUP, libmpiconstants), Cint))
@const_ref MPI_COMBINER_F90_COMPLEX Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_F90_COMPLEX, libmpiconstants), Cint))
@const_ref MPI_COMBINER_F90_INTEGER Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_F90_INTEGER, libmpiconstants), Cint))
@const_ref MPI_COMBINER_F90_REAL Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_F90_REAL, libmpiconstants), Cint))
@const_ref MPI_COMBINER_HINDEXED Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_HINDEXED, libmpiconstants), Cint))
@const_ref MPI_COMBINER_HINDEXED_BLOCK Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_HINDEXED_BLOCK, libmpiconstants), Cint))
@const_ref MPI_COMBINER_HVECTOR Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_HVECTOR, libmpiconstants), Cint))
@const_ref MPI_COMBINER_INDEXED Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_INDEXED, libmpiconstants), Cint))
@const_ref MPI_COMBINER_INDEXED_BLOCK Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_INDEXED_BLOCK, libmpiconstants), Cint))
@const_ref MPI_COMBINER_NAMED Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_NAMED, libmpiconstants), Cint))
@const_ref MPI_COMBINER_RESIZED Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_RESIZED, libmpiconstants), Cint))
@const_ref MPI_COMBINER_STRUCT Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_STRUCT, libmpiconstants), Cint))
@const_ref MPI_COMBINER_SUBARRAY Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_SUBARRAY, libmpiconstants), Cint))
@const_ref MPI_COMBINER_VECTOR Cint unsafe_load(cglobal((:MPICONSTANTS_COMBINER_VECTOR, libmpiconstants), Cint))
@const_ref MPI_COMM_TYPE_SHARED Cint unsafe_load(cglobal((:MPICONSTANTS_COMM_TYPE_SHARED, libmpiconstants), Cint))
@const_ref MPI_DISTRIBUTE_BLOCK Cint unsafe_load(cglobal((:MPICONSTANTS_DISTRIBUTE_BLOCK, libmpiconstants), Cint))
@const_ref MPI_DISTRIBUTE_CYCLIC Cint unsafe_load(cglobal((:MPICONSTANTS_DISTRIBUTE_CYCLIC, libmpiconstants), Cint))
@const_ref MPI_DISTRIBUTE_NONE Cint unsafe_load(cglobal((:MPICONSTANTS_DISTRIBUTE_NONE, libmpiconstants), Cint))
@const_ref MPI_ERR_ACCESS Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_ACCESS, libmpiconstants), Cint))
@const_ref MPI_ERR_AMODE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_AMODE, libmpiconstants), Cint))
@const_ref MPI_ERR_ARG Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_ARG, libmpiconstants), Cint))
@const_ref MPI_ERR_ASSERT Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_ASSERT, libmpiconstants), Cint))
@const_ref MPI_ERR_BAD_FILE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_BAD_FILE, libmpiconstants), Cint))
@const_ref MPI_ERR_BASE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_BASE, libmpiconstants), Cint))
@const_ref MPI_ERR_BUFFER Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_BUFFER, libmpiconstants), Cint))
@const_ref MPI_ERR_COMM Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_COMM, libmpiconstants), Cint))
@const_ref MPI_ERR_CONVERSION Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_CONVERSION, libmpiconstants), Cint))
@const_ref MPI_ERR_COUNT Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_COUNT, libmpiconstants), Cint))
@const_ref MPI_ERR_DIMS Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_DIMS, libmpiconstants), Cint))
@const_ref MPI_ERR_DISP Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_DISP, libmpiconstants), Cint))
@const_ref MPI_ERR_DUP_DATAREP Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_DUP_DATAREP, libmpiconstants), Cint))
@const_ref MPI_ERR_FILE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_FILE, libmpiconstants), Cint))
@const_ref MPI_ERR_FILE_EXISTS Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_FILE_EXISTS, libmpiconstants), Cint))
@const_ref MPI_ERR_FILE_IN_USE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_FILE_IN_USE, libmpiconstants), Cint))
@const_ref MPI_ERR_GROUP Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_GROUP, libmpiconstants), Cint))
@const_ref MPI_ERR_INFO Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_INFO, libmpiconstants), Cint))
@const_ref MPI_ERR_INFO_KEY Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_INFO_KEY, libmpiconstants), Cint))
@const_ref MPI_ERR_INFO_NOKEY Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_INFO_NOKEY, libmpiconstants), Cint))
@const_ref MPI_ERR_INFO_VALUE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_INFO_VALUE, libmpiconstants), Cint))
@const_ref MPI_ERR_INTERN Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_INTERN, libmpiconstants), Cint))
@const_ref MPI_ERR_IN_STATUS Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_IN_STATUS, libmpiconstants), Cint))
@const_ref MPI_ERR_IO Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_IO, libmpiconstants), Cint))
@const_ref MPI_ERR_KEYVAL Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_KEYVAL, libmpiconstants), Cint))
@const_ref MPI_ERR_LASTCODE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_LASTCODE, libmpiconstants), Cint))
@const_ref MPI_ERR_LOCKTYPE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_LOCKTYPE, libmpiconstants), Cint))
@const_ref MPI_ERR_NAME Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_NAME, libmpiconstants), Cint))
@const_ref MPI_ERR_NOT_SAME Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_NOT_SAME, libmpiconstants), Cint))
@const_ref MPI_ERR_NO_MEM Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_NO_MEM, libmpiconstants), Cint))
@const_ref MPI_ERR_NO_SPACE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_NO_SPACE, libmpiconstants), Cint))
@const_ref MPI_ERR_NO_SUCH_FILE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_NO_SUCH_FILE, libmpiconstants), Cint))
@const_ref MPI_ERR_OP Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_OP, libmpiconstants), Cint))
@const_ref MPI_ERR_OTHER Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_OTHER, libmpiconstants), Cint))
@const_ref MPI_ERR_PENDING Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_PENDING, libmpiconstants), Cint))
@const_ref MPI_ERR_PORT Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_PORT, libmpiconstants), Cint))
@const_ref MPI_ERR_QUOTA Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_QUOTA, libmpiconstants), Cint))
@const_ref MPI_ERR_RANK Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_RANK, libmpiconstants), Cint))
@const_ref MPI_ERR_READ_ONLY Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_READ_ONLY, libmpiconstants), Cint))
@const_ref MPI_ERR_REQUEST Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_REQUEST, libmpiconstants), Cint))
@const_ref MPI_ERR_RMA_ATTACH Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_RMA_ATTACH, libmpiconstants), Cint))
@const_ref MPI_ERR_RMA_CONFLICT Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_RMA_CONFLICT, libmpiconstants), Cint))
@const_ref MPI_ERR_RMA_FLAVOR Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_RMA_FLAVOR, libmpiconstants), Cint))
@const_ref MPI_ERR_RMA_RANGE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_RMA_RANGE, libmpiconstants), Cint))
@const_ref MPI_ERR_RMA_SHARED Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_RMA_SHARED, libmpiconstants), Cint))
@const_ref MPI_ERR_RMA_SYNC Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_RMA_SYNC, libmpiconstants), Cint))
@const_ref MPI_ERR_ROOT Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_ROOT, libmpiconstants), Cint))
@const_ref MPI_ERR_SERVICE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_SERVICE, libmpiconstants), Cint))
@const_ref MPI_ERR_SIZE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_SIZE, libmpiconstants), Cint))
@const_ref MPI_ERR_SPAWN Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_SPAWN, libmpiconstants), Cint))
@const_ref MPI_ERR_TAG Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_TAG, libmpiconstants), Cint))
@const_ref MPI_ERR_TOPOLOGY Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_TOPOLOGY, libmpiconstants), Cint))
@const_ref MPI_ERR_TRUNCATE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_TRUNCATE, libmpiconstants), Cint))
@const_ref MPI_ERR_TYPE Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_TYPE, libmpiconstants), Cint))
@const_ref MPI_ERR_UNKNOWN Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_UNKNOWN, libmpiconstants), Cint))
@const_ref MPI_ERR_UNSUPPORTED_DATAREP Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_UNSUPPORTED_DATAREP, libmpiconstants), Cint))
@const_ref MPI_ERR_UNSUPPORTED_OPERATION Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_UNSUPPORTED_OPERATION, libmpiconstants), Cint))
@const_ref MPI_ERR_WIN Cint unsafe_load(cglobal((:MPICONSTANTS_ERR_WIN, libmpiconstants), Cint))

@const_ref MPI_SUCCESS Cint unsafe_load(cglobal((:MPICONSTANTS_SUCCESS, libmpiconstants), Cint))
@const_ref MPI_LOCK_EXCLUSIVE Cint unsafe_load(cglobal((:MPICONSTANTS_LOCK_EXCLUSIVE, libmpiconstants), Cint))
@const_ref MPI_LOCK_SHARED Cint unsafe_load(cglobal((:MPICONSTANTS_LOCK_SHARED, libmpiconstants), Cint))
@const_ref MPI_MODE_APPEND Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_APPEND, libmpiconstants), Cint))
@const_ref MPI_MODE_CREATE Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_CREATE, libmpiconstants), Cint))
@const_ref MPI_MODE_DELETE_ON_CLOSE Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_DELETE_ON_CLOSE, libmpiconstants), Cint))
@const_ref MPI_MODE_EXCL Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_EXCL, libmpiconstants), Cint))
@const_ref MPI_MODE_NOCHECK Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_NOCHECK, libmpiconstants), Cint))
@const_ref MPI_MODE_NOPRECEDE Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_NOPRECEDE, libmpiconstants), Cint))
@const_ref MPI_MODE_NOPUT Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_NOPUT, libmpiconstants), Cint))
@const_ref MPI_MODE_NOSTORE Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_NOSTORE, libmpiconstants), Cint))
@const_ref MPI_MODE_NOSUCCEED Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_NOSUCCEED, libmpiconstants), Cint))
@const_ref MPI_MODE_RDONLY Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_RDONLY, libmpiconstants), Cint))
@const_ref MPI_MODE_RDWR Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_RDWR, libmpiconstants), Cint))
@const_ref MPI_MODE_SEQUENTIAL Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_SEQUENTIAL, libmpiconstants), Cint))
@const_ref MPI_MODE_UNIQUE_OPEN Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_UNIQUE_OPEN, libmpiconstants), Cint))
@const_ref MPI_MODE_WRONLY Cint unsafe_load(cglobal((:MPICONSTANTS_MODE_WRONLY, libmpiconstants), Cint))
@const_ref MPI_ORDER_C Cint unsafe_load(cglobal((:MPICONSTANTS_ORDER_C, libmpiconstants), Cint))
@const_ref MPI_ORDER_FORTRAN Cint unsafe_load(cglobal((:MPICONSTANTS_ORDER_FORTRAN, libmpiconstants), Cint))
@const_ref MPI_SEEK_CUR Cint unsafe_load(cglobal((:MPICONSTANTS_SEEK_CUR, libmpiconstants), Cint))
@const_ref MPI_SEEK_END Cint unsafe_load(cglobal((:MPICONSTANTS_SEEK_END, libmpiconstants), Cint))
@const_ref MPI_SEEK_SET Cint unsafe_load(cglobal((:MPICONSTANTS_SEEK_SET, libmpiconstants), Cint))
@const_ref MPI_THREAD_SINGLE Cint unsafe_load(cglobal((:MPICONSTANTS_THREAD_SINGLE, libmpiconstants), Cint))
@const_ref MPI_THREAD_FUNNELED Cint unsafe_load(cglobal((:MPICONSTANTS_THREAD_FUNNELED, libmpiconstants), Cint))
@const_ref MPI_THREAD_SERIALIZED Cint unsafe_load(cglobal((:MPICONSTANTS_THREAD_SERIALIZED, libmpiconstants), Cint))
@const_ref MPI_THREAD_MULTIPLE Cint unsafe_load(cglobal((:MPICONSTANTS_THREAD_MULTIPLE, libmpiconstants), Cint))
@const_ref MPI_TYPECLASS_COMPLEX Cint unsafe_load(cglobal((:MPICONSTANTS_TYPECLASS_COMPLEX, libmpiconstants), Cint))
@const_ref MPI_TYPECLASS_INTEGER Cint unsafe_load(cglobal((:MPICONSTANTS_TYPECLASS_INTEGER, libmpiconstants), Cint))
@const_ref MPI_TYPECLASS_REAL Cint unsafe_load(cglobal((:MPICONSTANTS_TYPECLASS_REAL, libmpiconstants), Cint))

@const_ref MPI_ARGV_NULL Ptr{Cchar} unsafe_load(cglobal((:MPICONSTANTS_ARGV_NULL, libmpiconstants), Ptr{Ptr{Cchar}}))
@const_ref MPI_ARGVS_NULL Ptr{Cchar} unsafe_load(cglobal((:MPICONSTANTS_ARGVS_NULL, libmpiconstants), Ptr{Ptr{Ptr{Cchar}}}))
@const_ref MPI_UNWEIGHTED Ptr{Cint} unsafe_load(cglobal((:MPICONSTANTS_UNWEIGHTED, libmpiconstants), Ptr{Cint}))
@const_ref MPI_WEIGHTS_EMPTY Ptr{Cint} unsafe_load(cglobal((:MPICONSTANTS_WEIGHTS_EMPTY, libmpiconstants), Ptr{Cint}))
@const_ref MPI_BOTTOM Ptr{Cvoid} unsafe_load(cglobal((:MPICONSTANTS_BOTTOM, libmpiconstants), Ptr{Cvoid}))
@const_ref MPI_IN_PLACE Ptr{Cvoid} unsafe_load(cglobal((:MPICONSTANTS_IN_PLACE, libmpiconstants), Ptr{Cvoid}))

@const_ref MPI_COMM_NULL MPI_Comm unsafe_load(cglobal((:MPICONSTANTS_COMM_NULL , libmpiconstants), MPI_Comm))
@const_ref MPI_COMM_SELF MPI_Comm unsafe_load(cglobal((:MPICONSTANTS_COMM_SELF , libmpiconstants), MPI_Comm))
@const_ref MPI_COMM_WORLD MPI_Comm unsafe_load(cglobal((:MPICONSTANTS_COMM_WORLD, libmpiconstants), MPI_Comm))

@const_ref MPI_COMM_DUP_FN MPI_Comm_copy_attr_function unsafe_load(cglobal((:MPICONSTANTS_COMM_DUP_FN, libmpiconstants), MPI_Comm_copy_attr_function))
@const_ref MPI_COMM_NULL_COPY_FN MPI_Comm_copy_attr_function unsafe_load(cglobal((:MPICONSTANTS_COMM_NULL_COPY_FN, libmpiconstants), MPI_Comm_copy_attr_function))
@const_ref MPI_COMM_NULL_DELETE_FN MPI_Comm_delete_attr_function unsafe_load(cglobal((:MPICONSTANTS_COMM_NULL_DELETE_FN, libmpiconstants), MPI_Comm_delete_attr_function))

@const_ref MPI_NULL_COPY_FN MPI_Copy_function unsafe_load(cglobal((:MPICONSTANTS_NULL_COPY_FN, libmpiconstants), MPI_Copy_function))

@const_ref MPI_2DOUBLE_PRECISION MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_2DOUBLE_PRECISION, libmpiconstants), MPI_Datatype))
@const_ref MPI_2INT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_2INT, libmpiconstants), MPI_Datatype))
@const_ref MPI_2INTEGER MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_2INTEGER, libmpiconstants), MPI_Datatype))
@const_ref MPI_2REAL MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_2REAL, libmpiconstants), MPI_Datatype))
@const_ref MPI_AINT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_AINT, libmpiconstants), MPI_Datatype))
@const_ref MPI_BYTE MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_BYTE, libmpiconstants), MPI_Datatype))
@const_ref MPI_CHAR MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_CHAR, libmpiconstants), MPI_Datatype))
@const_ref MPI_CHARACTER MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_CHARACTER, libmpiconstants), MPI_Datatype))
@const_ref MPI_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_COMPLEX16 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_COMPLEX16, libmpiconstants), MPI_Datatype))
# MPI_COMPLEX32 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_COMPLEX32, libmpiconstants), MPI_Datatype))
@const_ref MPI_COMPLEX8 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_COMPLEX8, libmpiconstants), MPI_Datatype))
@const_ref MPI_COUNT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_COUNT, libmpiconstants), MPI_Datatype))
@const_ref MPI_CXX_BOOL MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_CXX_BOOL, libmpiconstants), MPI_Datatype))
@const_ref MPI_CXX_DOUBLE_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_CXX_DOUBLE_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_CXX_FLOAT_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_CXX_FLOAT_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_CXX_LONG_DOUBLE_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_CXX_LONG_DOUBLE_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_C_BOOL MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_C_BOOL, libmpiconstants), MPI_Datatype))
@const_ref MPI_C_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_C_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_C_DOUBLE_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_C_DOUBLE_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_C_FLOAT_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_C_FLOAT_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_C_LONG_DOUBLE_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_C_LONG_DOUBLE_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_DATATYPE_NULL MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_DATATYPE_NULL, libmpiconstants), MPI_Datatype))
@const_ref MPI_DOUBLE MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_DOUBLE, libmpiconstants), MPI_Datatype))
@const_ref MPI_DOUBLE_COMPLEX MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_DOUBLE_COMPLEX, libmpiconstants), MPI_Datatype))
@const_ref MPI_DOUBLE_INT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_DOUBLE_INT, libmpiconstants), MPI_Datatype))
@const_ref MPI_DOUBLE_PRECISION MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_DOUBLE_PRECISION, libmpiconstants), MPI_Datatype))
@const_ref MPI_FLOAT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_FLOAT, libmpiconstants), MPI_Datatype))
@const_ref MPI_FLOAT_INT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_FLOAT_INT, libmpiconstants), MPI_Datatype))
@const_ref MPI_INT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INT, libmpiconstants), MPI_Datatype))
@const_ref MPI_INT16_T MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INT16_T, libmpiconstants), MPI_Datatype))
@const_ref MPI_INT32_T MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INT32_T, libmpiconstants), MPI_Datatype))
@const_ref MPI_INT64_T MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INT64_T, libmpiconstants), MPI_Datatype))
@const_ref MPI_INT8_T MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INT8_T, libmpiconstants), MPI_Datatype))
@const_ref MPI_INTEGER MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INTEGER, libmpiconstants), MPI_Datatype))
@const_ref MPI_INTEGER1 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INTEGER1, libmpiconstants), MPI_Datatype))
@const_ref MPI_INTEGER2 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INTEGER2, libmpiconstants), MPI_Datatype))
@const_ref MPI_INTEGER4 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INTEGER4, libmpiconstants), MPI_Datatype))
@const_ref MPI_INTEGER8 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_INTEGER8, libmpiconstants), MPI_Datatype))
@const_ref MPI_LOGICAL MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_LOGICAL, libmpiconstants), MPI_Datatype))
@const_ref MPI_LONG MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_LONG, libmpiconstants), MPI_Datatype))
@const_ref MPI_LONG_DOUBLE MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_LONG_DOUBLE, libmpiconstants), MPI_Datatype))
@const_ref MPI_LONG_DOUBLE_INT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_LONG_DOUBLE_INT, libmpiconstants), MPI_Datatype))
@const_ref MPI_LONG_INT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_LONG_INT, libmpiconstants), MPI_Datatype))
@const_ref MPI_LONG_LONG MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_LONG_LONG, libmpiconstants), MPI_Datatype))
@const_ref MPI_LONG_LONG_INT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_LONG_LONG_INT, libmpiconstants), MPI_Datatype))
@const_ref MPI_OFFSET MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_OFFSET, libmpiconstants), MPI_Datatype))
@const_ref MPI_PACKED MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_PACKED, libmpiconstants), MPI_Datatype))
@const_ref MPI_REAL MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_REAL, libmpiconstants), MPI_Datatype))
# MPI_REAL16 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_REAL16, libmpiconstants), MPI_Datatype))
@const_ref MPI_REAL4 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_REAL4, libmpiconstants), MPI_Datatype))
@const_ref MPI_REAL8 MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_REAL8, libmpiconstants), MPI_Datatype))
@const_ref MPI_SHORT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_SHORT, libmpiconstants), MPI_Datatype))
@const_ref MPI_SHORT_INT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_SHORT_INT, libmpiconstants), MPI_Datatype))
@const_ref MPI_SIGNED_CHAR MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_SIGNED_CHAR, libmpiconstants), MPI_Datatype))
@const_ref MPI_UINT16_T MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UINT16_T, libmpiconstants), MPI_Datatype))
@const_ref MPI_UINT32_T MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UINT32_T, libmpiconstants), MPI_Datatype))
@const_ref MPI_UINT64_T MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UINT64_T, libmpiconstants), MPI_Datatype))
@const_ref MPI_UINT8_T MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UINT8_T, libmpiconstants), MPI_Datatype))
@const_ref MPI_UNSIGNED MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UNSIGNED, libmpiconstants), MPI_Datatype))
@const_ref MPI_UNSIGNED_CHAR MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UNSIGNED_CHAR, libmpiconstants), MPI_Datatype))
@const_ref MPI_UNSIGNED_LONG MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UNSIGNED_LONG, libmpiconstants), MPI_Datatype))
@const_ref MPI_UNSIGNED_LONG_LONG MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UNSIGNED_LONG_LONG, libmpiconstants), MPI_Datatype))
@const_ref MPI_UNSIGNED_SHORT MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_UNSIGNED_SHORT, libmpiconstants), MPI_Datatype))
@const_ref MPI_WCHAR MPI_Datatype unsafe_load(cglobal((:MPICONSTANTS_WCHAR, libmpiconstants), MPI_Datatype))

@const_ref MPI_NULL_DELETE_FN MPI_Delete_function unsafe_load(cglobal((:MPICONSTANTS_NULL_DELETE_FN, libmpiconstants), MPI_Delete_function))

@const_ref MPI_ERRHANDLER_NULL MPI_Errhandler unsafe_load(cglobal((:MPICONSTANTS_ERRHANDLER_NULL, libmpiconstants), MPI_Errhandler))
@const_ref MPI_ERRORS_ARE_FATAL MPI_Errhandler unsafe_load(cglobal((:MPICONSTANTS_ERRORS_ARE_FATAL, libmpiconstants), MPI_Errhandler))
@const_ref MPI_ERRORS_RETURN MPI_Errhandler unsafe_load(cglobal((:MPICONSTANTS_ERRORS_RETURN, libmpiconstants), MPI_Errhandler))

@const_ref MPI_FILE_NULL MPI_File unsafe_load(cglobal((:MPICONSTANTS_FILE_NULL, libmpiconstants), MPI_File))

@const_ref MPI_GROUP_EMPTY MPI_Group unsafe_load(cglobal((:MPICONSTANTS_GROUP_EMPTY, libmpiconstants), MPI_Group))
@const_ref MPI_GROUP_NULL MPI_Group unsafe_load(cglobal((:MPICONSTANTS_GROUP_NULL, libmpiconstants), MPI_Group))

@const_ref MPI_INFO_ENV MPI_Info unsafe_load(cglobal((:MPICONSTANTS_INFO_ENV, libmpiconstants), MPI_Info))
@const_ref MPI_INFO_NULL MPI_Info unsafe_load(cglobal((:MPICONSTANTS_INFO_NULL, libmpiconstants), MPI_Info))

@const_ref MPI_MESSAGE_NO_PROC MPI_Message unsafe_load(cglobal((:MPICONSTANTS_MESSAGE_NO_PROC, libmpiconstants), MPI_Message))
@const_ref MPI_MESSAGE_NULL MPI_Message unsafe_load(cglobal((:MPICONSTANTS_MESSAGE_NULL, libmpiconstants), MPI_Message))

@const_ref MPI_DISPLACEMENT_CURRENT MPI_Offset unsafe_load(cglobal((:MPICONSTANTS_DISPLACEMENT_CURRENT, libmpiconstants), MPI_Offset))

@const_ref MPI_BAND MPI_Op unsafe_load(cglobal((:MPICONSTANTS_BAND, libmpiconstants), MPI_Op))
@const_ref MPI_BOR MPI_Op unsafe_load(cglobal((:MPICONSTANTS_BOR, libmpiconstants), MPI_Op))
@const_ref MPI_BXOR MPI_Op unsafe_load(cglobal((:MPICONSTANTS_BXOR, libmpiconstants), MPI_Op))
@const_ref MPI_LAND MPI_Op unsafe_load(cglobal((:MPICONSTANTS_LAND, libmpiconstants), MPI_Op))
@const_ref MPI_LOR MPI_Op unsafe_load(cglobal((:MPICONSTANTS_LOR, libmpiconstants), MPI_Op))
@const_ref MPI_LXOR MPI_Op unsafe_load(cglobal((:MPICONSTANTS_LXOR, libmpiconstants), MPI_Op))
@const_ref MPI_MAX MPI_Op unsafe_load(cglobal((:MPICONSTANTS_MAX, libmpiconstants), MPI_Op))
@const_ref MPI_MAXLOC MPI_Op unsafe_load(cglobal((:MPICONSTANTS_MAXLOC, libmpiconstants), MPI_Op))
@const_ref MPI_MIN MPI_Op unsafe_load(cglobal((:MPICONSTANTS_MIN, libmpiconstants), MPI_Op))
@const_ref MPI_MINLOC MPI_Op unsafe_load(cglobal((:MPICONSTANTS_MINLOC, libmpiconstants), MPI_Op))
@const_ref MPI_NO_OP MPI_Op unsafe_load(cglobal((:MPICONSTANTS_NO_OP, libmpiconstants), MPI_Op))
@const_ref MPI_OP_NULL MPI_Op unsafe_load(cglobal((:MPICONSTANTS_OP_NULL, libmpiconstants), MPI_Op))
@const_ref MPI_PROD MPI_Op unsafe_load(cglobal((:MPICONSTANTS_PROD, libmpiconstants), MPI_Op))
@const_ref MPI_REPLACE MPI_Op unsafe_load(cglobal((:MPICONSTANTS_REPLACE, libmpiconstants), MPI_Op))
@const_ref MPI_SUM MPI_Op unsafe_load(cglobal((:MPICONSTANTS_SUM, libmpiconstants), MPI_Op))

@const_ref MPI_REQUEST_NULL MPI_Request unsafe_load(cglobal((:MPICONSTANTS_REQUEST_NULL, libmpiconstants), MPI_Request))

@const_ref MPI_STATUS_IGNORE Ptr{MPI_Status} unsafe_load(cglobal((:MPICONSTANTS_STATUS_IGNORE, libmpiconstants), Ptr{MPI_Status}))
@const_ref MPI_STATUSES_IGNORE Ptr{MPI_Status} unsafe_load(cglobal((:MPICONSTANTS_STATUSES_IGNORE, libmpiconstants), Ptr{MPI_Status}))

@const_ref MPI_TYPE_DUP_FN MPI_Type_copy_attr_function unsafe_load(cglobal((:MPICONSTANTS_TYPE_DUP_FN, libmpiconstants), MPI_Type_copy_attr_function))
@const_ref MPI_TYPE_NULL_COPY_FN MPI_Type_copy_attr_function unsafe_load(cglobal((:MPICONSTANTS_TYPE_NULL_COPY_FN, libmpiconstants), MPI_Type_copy_attr_function))
@const_ref MPI_TYPE_NULL_DELETE_FN MPI_Type_delete_attr_function unsafe_load(cglobal((:MPICONSTANTS_TYPE_NULL_DELETE_FN, libmpiconstants), MPI_Type_delete_attr_function))

@const_ref MPI_WIN_NULL MPI_Win unsafe_load(cglobal((:MPICONSTANTS_WIN_NULL, libmpiconstants), MPI_Win))

@const_ref MPI_WIN_DUP_FN MPI_Win_copy_attr_function unsafe_load(cglobal((:MPICONSTANTS_WIN_DUP_FN, libmpiconstants), MPI_Win_copy_attr_function))
@const_ref MPI_WIN_NULL_COPY_FN MPI_Win_copy_attr_function unsafe_load(cglobal((:MPICONSTANTS_WIN_NULL_COPY_FN, libmpiconstants), MPI_Win_copy_attr_function))

@const_ref MPI_WIN_NULL_DELETE_FN MPI_Win_delete_attr_function unsafe_load(cglobal((:MPICONSTANTS_WIN_NULL_DELETE_FN, libmpiconstants), MPI_Win_delete_attr_function))


text:
function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    precompile(Tuple{typeof(StructuredMatrices.binomial2),Int64})
    precompile(Tuple{typeof(StructuredMatrices.muladd_quote),Int64,Type{T} where T,Int64,Int64,Symbol})
    precompile(Tuple{typeof(StructuredMatrices.row_sum_add_quote),Int64,Type{T} where T,Symbol})
end


text:
# Autogenerated wrapper script for gdk_pixbuf_jll for x86_64-w64-mingw32
export gdk_pixbuf_loaders_dir, gdk_pixbuf_query_loaders, libgdkpixbuf

using Glib_jll
using JpegTurbo_jll
using libpng_jll
using Libtiff_jll
JLLWrappers.@generate_wrapper_header("gdk_pixbuf")
JLLWrappers.@declare_file_product(gdk_pixbuf_loaders_dir)
JLLWrappers.@declare_library_product(libgdkpixbuf, "libgdk_pixbuf-2.0-0.dll")
JLLWrappers.@declare_executable_product(gdk_pixbuf_query_loaders)
function __init__()
    JLLWrappers.@generate_init_header(Glib_jll, JpegTurbo_jll, libpng_jll, Libtiff_jll)
    JLLWrappers.@init_file_product(
        gdk_pixbuf_loaders_dir,
        "lib\\gdk-pixbuf-2.0\\2.10.0\\loaders",
    )

    JLLWrappers.@init_library_product(
        libgdkpixbuf,
        "bin\\libgdk_pixbuf-2.0-0.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_executable_product(
        gdk_pixbuf_query_loaders,
        "bin\\gdk-pixbuf-query-loaders.exe",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
###################################################
## SchoolBusRouting.jl
##      Module root
## Authors: Arthur Delarue, Sébastien Martin, 2018
###################################################

module SchoolBusRouting

using DataFrames, CSV
using LightGraphs, NearestNeighbors, ProgressMeter
using Geodesy, Colors
# using JuMP, Gurobi
using JuMP, Cbc
import JLD
import Base: convert
using SFML, Plots

include("problem.jl")
include("load.jl")
include("scenarios.jl")
include("selection.jl")
# include("tests.jl")
# include("output.jl")
# include("lbh.jl")
#include("viz.jl")
#include("synthetic.jl")

end


text:
# See also fastmath_able.jl for where rules are defined simple base functions
# that also have FastMath versions.

@scalar_rule one(x) Zero()
@scalar_rule zero(x) Zero()
@scalar_rule adjoint(x::Real) One()
@scalar_rule transpose(x) One()
@scalar_rule imag(x::Real) Zero()
@scalar_rule hypot(x::Real) sign(x)

@scalar_rule fma(x, y, z) (y, x, One())
@scalar_rule muladd(x, y, z) (y, x, One())
@scalar_rule real(x::Real) One()
@scalar_rule rem2pi(x, r::RoundingMode) (One(), DoesNotExist())
@scalar_rule(
    mod(x, y),
    @setup((u, nan) = promote(x / y, NaN16), isint = isinteger(x / y)),
    (ifelse(isint, nan, one(u)), ifelse(isint, nan, -floor(u))),
)

@scalar_rule deg2rad(x) π / oftype(x, 180)
@scalar_rule rad2deg(x) oftype(x, 180) / π

# Can't multiply though sqrt in acosh because of negative complex case for x
@scalar_rule acosh(x) inv(sqrt(x - 1) * sqrt(x + 1))
@scalar_rule acoth(x) inv(1 - x ^ 2)
@scalar_rule acsch(x) -(inv(x ^ 2 * sqrt(1 + x ^ -2)))
@scalar_rule acsch(x::Real) -(inv(abs(x) * sqrt(1 + x ^ 2)))
@scalar_rule asech(x) -(inv(x * sqrt(1 - x ^ 2)))
@scalar_rule asinh(x) inv(sqrt(x ^ 2 + 1))
@scalar_rule atanh(x) inv(1 - x ^ 2)

@scalar_rule acosd(x) (-(oftype(x, 180)) / π) / sqrt(1 - x ^ 2)
@scalar_rule acotd(x) (-(oftype(x, 180)) / π) / (1 + x ^ 2)
@scalar_rule acscd(x) ((-(oftype(x, 180)) / π) / x ^ 2) / sqrt(1 - x ^ -2)
@scalar_rule acscd(x::Real) ((-(oftype(x, 180)) / π) / abs(x)) / sqrt(x ^ 2 - 1)
@scalar_rule asecd(x) ((oftype(x, 180) / π) / x ^ 2) / sqrt(1 - x ^ -2)
@scalar_rule asecd(x::Real) ((oftype(x, 180) / π) / abs(x)) / sqrt(x ^ 2 - 1)
@scalar_rule asind(x) (oftype(x, 180) / π) / sqrt(1 - x ^ 2)
@scalar_rule atand(x) (oftype(x, 180) / π) / (1 + x ^ 2)

@scalar_rule cot(x) -((1 + Ω ^ 2))
@scalar_rule coth(x) -(csch(x) ^ 2)
@scalar_rule cotd(x) -(π / oftype(x, 180)) * (1 + Ω ^ 2)
@scalar_rule csc(x) -Ω * cot(x)
@scalar_rule cscd(x) -(π / oftype(x, 180)) * Ω * cotd(x)
@scalar_rule csch(x) -(coth(x)) * Ω
@scalar_rule sec(x) Ω * tan(x)
@scalar_rule secd(x) (π / oftype(x, 180)) * Ω * tand(x)
@scalar_rule sech(x) -(tanh(x)) * Ω

@scalar_rule acot(x) -(inv(1 + x ^ 2))
@scalar_rule acsc(x) -(inv(x ^ 2 * sqrt(1 - x ^ -2)))
@scalar_rule acsc(x::Real) -(inv(abs(x) * sqrt(x ^ 2 - 1)))
@scalar_rule asec(x) inv(x ^ 2 * sqrt(1 - x ^ -2))
@scalar_rule asec(x::Real) inv(abs(x) * sqrt(x ^ 2 - 1))

@scalar_rule cosd(x) -(π / oftype(x, 180)) * sind(x)
@scalar_rule cospi(x) -π * sinpi(x)
@scalar_rule sind(x) (π / oftype(x, 180)) * cosd(x)
@scalar_rule sinpi(x) π * cospi(x)
@scalar_rule tand(x) (π / oftype(x, 180)) * (1 + Ω ^ 2)

@scalar_rule x \ y (-((y / x) / x), inv(x))

function frule((_, ẏ), ::typeof(identity), x)
    return (x, ẏ)
end

function rrule(::typeof(identity), x)
    function identity_pullback(ȳ)
        return (NO_FIELDS, ȳ)
    end
    return (x, identity_pullback)
end


text:
module JobScript

using ClusterManagers, Distributed

addprocs_slurm(parse(Int, ENV["SLURM_NTASKS"]));

@everywhere begin
   using Pkg
   Pkg.activate("$(ENV["HOME"])/HelioseismicKernels")
end

using HelioseismicKernels

# angles are in degrees
ϕ_low = 35
ϕ_high = 65
nϕ = 10
ℓ_range = 1:100

_, _, D = HelioseismicKernels.δτ_Δϕ(nothing,
   HelioseismicKernels.TravelTimes(),
   HelioseismicKernels.Flow(), ϕ_low = ϕ_low, ϕ_high = ϕ_high, nϕ = nϕ,
   ℓ_range = ℓ_range, save = false)

show(stdout, MIME"text/plain"(), D)
println()

end


text:
module TestMeasures
using SimString
using Test
using Faker
using Suppressor

@testset "Test Dice Search" begin
    db = DictDB(CharacterNGrams(2, " "));
    append!(db, ["foo", "bar", "fooo"]);

    res = search(Dice(), db, "foo"; α=0.8, ranked=true)
    @test res == [("foo", 1.0), ("fooo", 0.8888888888888888)]
end

@testset "Test Jaccard Search" begin
    db = DictDB(CharacterNGrams(2, " "));
    append!(db, ["foo", "bar", "fooo"]);

    res = search(Jaccard(), db, "foo"; α=0.8, ranked=true)
    @test res == [("foo", 1.0), ("fooo", 0.8)]

end

@testset "Test Cosine Search" begin
    db = DictDB(CharacterNGrams(2, " "));
    append!(db, ["foo", "bar", "fooo"]);

    res = search(Cosine(), db, "foo"; α=0.8, ranked=true)
    @test res == [("foo", 1.0), ("fooo", 0.8944271909999159)]

end

@testset "Test Overlap Search" begin
    db = DictDB(CharacterNGrams(2, " "));
    append!(db, ["foo", "bar", "fooo"]);

    res = search(Overlap(), db, "foo"; α=0.8, ranked=true)
    @test res == [("foo", 1.0), ("fooo", 1.0)]

end

@testset "Test ExactMatch Search" begin
    db = DictDB(CharacterNGrams(2, " "));
    append!(db, ["foo", "bar", "fooo"]);

    @test search(ExactMatch(), db, "foo"; α=0.1, ranked=true) == [("foo", 1.0)]
    @test search(ExactMatch(), db, "foo"; α=0.5, ranked=true) == [("foo", 1.0)]
    @test search(ExactMatch(), db, "foo"; α=0.9, ranked=true) == [("foo", 1.0)]
    @test search(ExactMatch(), db, "foo"; α=1.0, ranked=true) == [("foo", 1.0)]

end

@testset "Test Micro Deep Dive Search" begin
    db = DictDB(CharacterNGrams(2, " "));
    append!(db, ["a", "ab", "abc", "abcd", "abcde"]);

    @test search(Cosine(), db, "a", α=1., ranked=true) == [("a", 1.0)]
    @test search(Cosine(), db, "ab", α=1., ranked=true) == [("ab", 1.0)]
    @test search(Cosine(), db, "abc", α=1., ranked=true) == [("abc", 1.0)]
    @test search(Cosine(), db, "abcd", α=1., ranked=true) == [("abcd", 1.0)]
    @test search(Cosine(), db, "abcde", α=1., ranked=true) == [("abcde", 1.0)]

    @test search(Cosine(), db, "a", α=0.5, ranked=true) == [("a", 1.0)]
    @test search(Cosine(), db, "ab", α=0.5, ranked=true) == [("ab", 1.0), ("abc", 0.5773502691896258), ("abcd", 0.5163977794943222)]
    @test search(Cosine(), db, "abc", α=0.6, ranked=false) == [("abc", 1.0), ("abcd", 0.6708203932499369), ("abcde", 0.6123724356957946)]

    @test search(Cosine(), db, "a", α=0.9, ranked=true) == [("a", 1.0)]
    @test search(Cosine(), db, "ab", α=0.9, ranked=true) == [("ab", 1.0)]
    @test search(Cosine(), db, "abc", α=0.9, ranked=true) == [("abc", 1.0)]
    @test search(Cosine(), db, "abcd", α=0.9, ranked=true) == [("abcd", 1.0)]
    @test search(Cosine(), db, "abcde", α=0.9, ranked=true) == [("abcde", 1.0)]
end

@testset "Test output from show" begin
    db = DictDB(CharacterNGrams(2, " "));
    append!(db, ["foo", "bar", "fooo"]);

    expected_out = "DictDB(SimString.CharacterNGrams{Int64, String}(2, \" \"))\nTotal collection: 3\nAverage number of ngram features: 4.5\nTotal number of ngram features: 13\n"
    r = @capture_out show(db)
    @test r == expected_out
end

end  # module


text:
module ArbNumerics

export ArbFloat, ArbReal, ArbComplex,
       interval, setinterval, lowerbound, upperbound,
       ball, setball, midpoint, radius,
       bounds_abs, lowerbound_abs, upperbound_abs,
       increase_radius, decrease_radius,
       bits4digits, digits4bits,
       workingprecision, setworkingprecision,
       extrabits, setextrabits,

       stringall, showall,

       ispos, isneg, isnonpos, isnonneg,

       isspecial,   # zero, infinite or NaN
       isnonfinite,
       isinf, isposinf, isneginf,
       isnonzero,
       isnormal,    # nonzero finite
       isexact,     # zero radius
       isinexact,   # nonzero radius
       isint,       # integer valued

       inf, posinf, neginf, nan,
       typemax, typemin, floatmax, floatmin,

       signs, signbits,
       significand_bits, relerror_bits, relaccuracy_bits,
       trim_bits, ulp, ulps, eps, epss,

       # other functions
       add2!, sub2!, mul2!, div2!,
       addmul, submul, mulsub,
       square, cube, rsqrt, rcbrt, pow, root, loghypot,
       risingfactorial, doublefactorial,

       # special functions
       agm1, agm,
       logsinpi, barnesg, logbarnesg,
       ei, si, ci, shi, chi,
       airyai, airyaiprime, airybi, airybiprime,
       besselj, besselj0, besselj1, bessely, bessely0, bessely1, besseli, besselk,
       elliptick, elliptice, ellipticpi, ellipticp,
       ellipticzeta, ellipticsigma,
       zeta, eta, xi,                  # Reimann
       lambertw,
       π, ℯ, γ, φ, catalan

import Base: IEEEFloat,
       hash, promote_rule, promote_type, convert,
       copy, deepcopy, string, show,

       zero, one,

       Float16, Float32, Float64,
       UInt8, UInt16, UInt32, UInt64, UInt128,
       Int8, Int16, Int32, Int64, Int128,
       BigInt, BigFloat, Rational, Complex, real, imag,
       floatmax, floatmin, typemax, typemin,

       iszero, isone, isinteger, isfinite, isinf, isnan, issubnormal,
       zero, one,
       precision, setprecision, eps,

       abs, abs2, signbit, sign, copysign, flipsign,

       (==), (!=), (<), (<=), (>=), (>), isequal, isless,
       (+), (-), (*), (/), (\), inv,
       div, fld, cld, rem, mod, divrem, fldmod,
       ceil, floor, trunc, round,
       muladd, fma,
       factorial, binomial

import Base.Math:  max, min, minmax,
       exponent, significand,
       ldexp, frexp, modf,

       mod2pi, rem2pi,
       sqrt, cbrt, hypot,

       (^), exp, log, expm1, log1p, log2, log10,
       sin, cos, sincos, tan, csc, sec, cot, sinc,
       asin, acos, atan, acsc, asec, acot,
       sinh, cosh, tanh, csch, sech, coth,
       asinh, acosh, atanh, acsch, asech, acoth,

       clamp, clamp!

import Random.rand

import SpecialFunctions: gamma, lgamma, lfact, digamma, invdigamma, polygamma, trigamma,
     beta, lbeta, sinint, cosint,
     erf, erfc, erfcinv, erfcx, erfi, erfinv,
     airyai, airyaiprime, airybi, airybiprime,
     besselj, besselj0, besselj1, bessely, bessely0, bessely1, besseli, besselk,
     eta, zeta

import Base.MathConstants: π, ℯ, γ, φ, catalan

using Random

include("support/arblib.jl")
include("support/abstractions.jl")

include("libarb/roundingmodes.jl")
include("libarb/Mag.jl")
include("libarb/ArbFloat.jl")
include("libarb/ArbReal.jl")
include("libarb/ArbComplex.jl")
include("libarb/Flint2.jl")
include("libarb/promote.jl")
include("libarb/string.jl")
include("libarb/show.jl")

include("values/bitsdigits.jl")
include("values/intraconvert.jl")
include("values/interconvert.jl")
include("values/constructors.jl")
include("values/specialvals.jl")
include("values/compare.jl")
include("values/rounding.jl")
include("values/random.jl")

include("float/prearith.jl")
include("float/arith.jl")
include("float/arith_inplace.jl")
include("float/morearith.jl")
include("float/elementary.jl")
include("float/special.jl")
include("float/special2.jl")
include("float/export_fallbacks.jl")

include("intervals/intervalparts.jl")
include("intervals/eps_ulp.jl")

include("support/helptext.jl")

end # ArbNumerics


text:
using Documenter
using JModels
using PlutoStaticHTML

notebooks = [
    "GLM",
    "Logo"
]

include("build.jl")

# In most cases during development, building the notebooks is not necessary.
if get(ENV, "CI", "false") == "true"
    build()
end
md_files = markdown_files()
T = [t => f for (t, f) in zip(notebooks, md_files)]

sitename = "JModels.jl"
pages = [
    "JModels" => "index.md",
    "Details" => T
]

prettyurls = get(ENV, "CI", nothing) == "true"
assets = [ "assets/favicon.ico" ]
format = Documenter.HTML(; assets, prettyurls)
modules = [JModels]
strict = true
checkdocs = :none
makedocs(; sitename, pages, format, modules, strict, checkdocs)

deploydocs(;
    devbranch="main",
    repo="github.com/JuliaModels/JModels.jl.git",
    push_preview=false
)


text:
mutable struct body_motion_data_t <: LCMType
    timestamp::Int64
    body_or_frame_name::String
    spline::piecewise_polynomial_t
    quat_task_to_world::SVector{4, Float64}
    translation_task_to_world::SVector{3, Float64}
    xyz_kp_multiplier::SVector{3, Float64}
    xyz_damping_ratio_multiplier::SVector{3, Float64}
    expmap_kp_multiplier::Float64
    expmap_damping_ratio_multiplier::Float64
    weight_multiplier::SVector{6, Float64}
    in_floating_base_nullspace::Bool
    control_pose_when_in_contact::Bool
end

@lcmtypesetup(body_motion_data_t)


text:
#==== Moves ===================================================================#

function rjmove(Y, C::Constants, S::State, X::Auxiliary, J::Jumps, U::Counts)
    k,bprob,dprob = S.k, J.bprob, J.dprob

    p = rand()
    b = bprob(k)
    if p < b
        bmove(Y,C,S,X,J,U)
    elseif p < b + dprob(k)
        dmove(Y,C,S,X,J,U)
    end
end

function bmove(Y, C::Constants, S::State, X::Auxiliary, J::Jumps, U::Counts)
    k,R,λ,α,β,lλ,αlβ = S.k, C.R, C.λ, C.α, C.β, C.lλ, C.αlβ

    s = rand()*R
    @views j = searchsortedlast(S.locs[1:k+2],s)
    s1,s2 = S.locs[j], S.locs[j+1]
    w,w1,w2 = s2-s1, s-s1, s2-s
    h,u = S.hts[j], rand()
    h1 = h * (u/(1-u))^(w2/w)
    h2 = h1 * ((1-u)/u)

    lratio = llhdratio(Y,s1,s2,s,h1,h2,h) +
             lpriorratio(k,h1,h2,h,w1,w2,w,C) +
             lproposalratio(J.bprob,J.dprob,k,C.R) +
             ljacobian(h1,h2,h)
    ratio = exp(clamp(lratio,-30,0))

    if rand() < ratio
        S.locs[k+3] = S.locs[k+2]
        for i = k+2:-1:j+2
            S.locs[i] = S.locs[i-1] # this can't be done
            S.hts[i] = S.hts[i-1]   # using .=, as in 'dmove'.
        end
        S.hts[j] = h1
        S.hts[j+1] = h2
        S.locs[j+1] = s
        S.k += 1
        U.baccepts += 1
        aux_init(Y,C,S,X) # leave the aux. variables in a consistent state.
    end
    U.bprops += 1
end

function dmove(Y, C::Constants, S::State, X::Auxiliary, J::Jumps, U::Counts)
    k,R,λ,α,β,lλ,αlβ = S.k, C.R, C.λ, C.α, C.β, C.lλ, C.αlβ

    j = rand(2:k+1)
    s1,s,s2 = S.locs[j-1], S.locs[j], S.locs[j+1]
    w,w1,w2 = s2-s1, s-s1, s2-s
    h1,h2 = S.hts[j-1], S.hts[j]
    h = h1^(w1/w) * h2^(w2/w)

    lratio = llhdratio(Y,s1,s2,s,h1,h2,h) +
             lpriorratio(k-1,h1,h2,h,w1,w2,w,C) +
             lproposalratio(J.bprob,J.dprob,k,C.R) +
             ljacobian(h1,h2,h)
    ratio = exp(clamp(-lratio,-30,0)) # note the negation.

    if rand() < ratio
        @views S.locs[j:k+1] .= S.locs[j+1:k+2]
        @views S.hts[j:k] .= S.hts[j+1:k+1]
        S.locs[k+2] = NaN
        S.hts[k+1] = NaN
        S.hts[j-1] = h
        S.k -= 1
        U.daccepts += 1
        aux_init(Y,C,S,X)
    end
    U.dprops += 1
end

#==== Probability ratios ======================================================#

"""
Returns the ratio p(k+1)/p(k) of two Poisson(λ) probabilities.
"""
poissonratio(λ,k) = λ/(k+1)
rpoissonratio(λ,k) = (k+1)/λ
lpoissonratio(lλ,k) = lλ - log(k+1)

"""
Returns the ratio p(w1,w2,...|k+1)/p(w,...|k) of the probabilities of two
even-numbered order statistics.
"""
lstatsratio(R,k,w1,w2,w) = log((2k+2)*(2k+3)/R^2 * w1*w2/w)

"""
Returns the natural logarithm of the ratio p(h1,h2,...|k+1)/p(h,...|k) of two
Beta(α,β) probabilities.
"""
lbetaratio(α,β,αlβ,h1,h2,h) = αlβ + (α-1)*log(h1*h2/h) - (h1+h2-h)β

"""
Returns the natural log-likelihood ratio required for a birth move.

# Arguments
  - `s1`, `s2`, `s`: two existing, ordered step locations and a new one that
        lies between them.
  - `h1`, `h2`, `h`: the heights of the new steps adjacent to `s`, as well as
        the height of the step that they are replacing.
"""
function llhdratio(Y,s1,s2,s,h1,h2,h)
    n1,n2,n3 = [searchsortedfirst(Y,s) for s in (s1,s,s2)]
    return (n2-n1)*log(h1/h) - (h1-h)*(s-s1) +
           (n3-n2)*log(h2/h) - (h2-h)*(s2-s)
end

"""
Returns the natural logarithm of the prior ratio for a birth move.

# Arguments
  - `h1`, `h2`, `h`: the heights of two new adjacent steps, along with the
        height `h` of the step that they are replacing.
  - `w1`, `w2`, `w`: the widths of the steps of heights `h1`, `h2`, and `h`,
        respectively.
"""
function lpriorratio(k,h1,h2,h,w1,w2,w,C::Constants)
    return lpoissonratio(C.lλ,k) +
           lstatsratio(C.R,k,w1,w2,w) +
           lbetaratio(C.α,C.β,C.αlβ,h1,h2,h)
end

"""
Returns the natural logarithm of the proposal ratio for a birth move.
"""
lproposalratio(b,d,k,R) = log(d(k+1) * R/(b(k)*(k+1)))

"""
Returns the natural logarithm of the Jacobian factor for a birth move.
"""
ljacobian(h1,h2,h) = log((h1+h2)^2 / h)

#==== I/O =====================================================================#

function k_println(S::State)
    println("S: k = $S.k,",
              " locs = $(string(S.locs[1:k+2])),",
              " hts = $(string(S.hts[1:k+1]))\n")
end

function k_println(k, X::Auxiliary)
    println("X: locs = $(string(X.locs[1:k+2])),",
              " hts = $(string(X.hts[1:k+1]))\n",
            "   widths = $(string(X.widths[1:k+1])),",
              " counts = $(X.counts[1:k+1])\n",
            "   tlocs = $(string(X.tlocs[1:k])),",
              " lhts = $(string(X.lhts[1:k+1]))\n",
            "   ix = $(X.ix[1:k])\n")
end

function string(A::Vector{Float64})
    io = IOBuffer()
    write(io, "[")
    for a in @view(A[1:end-1])
        write(io, @sprintf("%g, ", a))
    end
    write(io, @sprintf("%g]", A[end]))
    return String(take!(io))
end

max_stars_repo_name: kevdur/rjcp

max_issues_repo_name: kevdur/rjcp

max_forks_repo_name: kevdur/rjcp


text:
function soft_step(x; halfwidth=0.1)
    α = 1/sqrt(halfwidth)
    return 1 / (1 + exp(-α*(x+5halfwidth)))
    # if x < -halfwidth
    #     zero(x)
    # elseif x > halfwidth
    #     one(x)
    # else
    #     typeof(x)((sinpi(x/halfwidth/2) + 1)/2)
    # end
end
# soft_step(x, α=1e2) = 1 / (1 + exp(-α*x))

≤ₛ(x, y) = soft_step(y - x)

function soft_clamp(x, lo, hi; kwargs...)
    sgn_lo = soft_step(lo-x; kwargs...)
    sgn_hi = soft_step(x-hi; kwargs...)
    lo_part = lo * sgn_lo
    hi_part = hi * sgn_hi
    mid_part = x * (1-sgn_lo) * (1-sgn_hi)
    return lo_part + mid_part + hi_part
end

function soft_between(x, lo, hi; kwargs...)
    sgn_lo = soft_step(x-lo; kwargs...)
    sgn_hi = soft_step(hi-x; kwargs...)
    return sgn_lo * sgn_hi
end


text:
using Flux, Metalhead, Images, CUDA, NNlib, BSON, Random

CUDA.allowscalar(false)

include("..\\src\\utils.jl")
include("..\\src\\layers.jl")
include("..\\src\\vgg.jl")
include("..\\src\\transformer_net.jl")
include("..\\src\\neural_style.jl")

training_data = "C:\\Users\\michael\\Desktop\\mscoco\\train2017\\train2017"
style_folder = "C:\\Users\\michael\\Desktop\\Julia\\FastStyleTransfer.jl\\images"
style_image = "georges-lemmen_the-beach-at-heist_1891.jpg"
style_path = joinpath(style_folder, style_image)

model_path = "C:\\Users\\michael\\Desktop\\Julia\\FastStyleTransfer.jl\\models"
batch_size = 128
η = 0.01
epochs = 1

content_weight = 1.0
style_weight = 1.0

nimages = 100

train(training_data, batch_size, η, style_path, epochs, model_path, content_weight, style_weight, TransformerNet; images = nimages)


text:
module TestBigDTree
using PatternDispatch

@pattern f(1,1) = 11
@pattern f(1,2) = 12
@pattern f(2,1) = 21
@pattern f(2,2) = 21
@pattern f(1,y::Int) = 1
@pattern f(2,y::Int) = 2
@pattern f(x::Int,1) = 1
@pattern f(x::Int,2) = 2
@pattern f(x::Int,y::Int) = 0

show_dispatch(f)

end # module


text:
# Sema
function PrintStats(x::Sema)
    @check_ptrs x
    return clang_Sema_PrintStats(x)
end

function RestoreNestedNameSpecifierAnnotation(x::Sema, v::AnnotationValue, rng::SourceRange,
                                              spec::CXXScopeSpec)
    @check_ptrs x
    rb = getBeginLoc(rng)
    re = getEndLoc(rng)
    return clang_Sema_RestoreNestedNameSpecifierAnnotation(x, v, rb, re, spec)
end

function LookupResult(sema::Sema, name::DeclarationName, loc::SourceLocation,
                      kind::CXLookupNameKind)
    @check_ptrs sema
    status = Ref{CXInit_Error}(CXInit_NoError)
    result = clang_LookupResult_create(sema, name, loc, kind, status)
    @assert status[] == CXInit_NoError
    return LookupResult(result)
end

function LookupParsedName(x::Sema, r::LookupResult, sp::Scope, ss::CXXScopeSpec,
                          allow_builtin_creation=false, entering_context=false)
    @check_ptrs x r sp ss
    return clang_Sema_LookupParsedName(x, r, sp, ss, allow_builtin_creation,
                                       entering_context)
end

function LookupName(x::Sema, r::LookupResult, sp::Scope, allow_builtin_creation=false)
    @check_ptrs x r sp
    return clang_Sema_LookupName(x, r, sp, allow_builtin_creation)
end

function processWeakTopLevelDecls(sema::Sema, cg::CodeGenerator)
    @check_ptrs sema cg
    clang_Sema_processWeakTopLevelDecls(sema, cg)
    return nothing
end


text:
include("new_engine.jl")
using .ID: AssetId, FieldId
using .Engine: CalcLattice, newbar!, addfield!
using .AbstractFields: AbstractFieldOperation
using .ConcreteFields: Open, SMA

function main()
    openid = FieldId("Open")
    smaid = FieldId("SMA-Open-15")
    smawindow = 15
    fields = Array{T}([
        Open(openid),
        SMA(smaid, openid, smawindow)
    ]) where T <: AbstractFieldOperation
    println(fields)
end

main() # run the main function

max_stars_repo_name: maxholloway/backtest

max_issues_repo_name: maxholloway/backtest

max_forks_repo_name: maxholloway/backtest


text:
"""
    SEIso <: Isotropic{SqEuclidean}

Isotropic Squared Exponential kernel (covariance)
```math
k(x,x') = σ²\\exp(- (x - x')ᵀ(x - x')/(2ℓ²))
```
with length scale ``ℓ`` and signal standard deviation ``σ``.
"""
mutable struct SEIso <: Isotropic{SqEuclidean}
    "Squared length scale"
    ℓ2::Float64
    "Signal variance"
    σ2::Float64
    "Priors for kernel parameters"
    priors::Array

    """
        SEIso(ll::Float64, lσ::Float64)

    Create `SEIso` with length scale `exp(ll)` and signal standard deviation `exp(lσ)`.
    """
    SEIso(ll::Float64, lσ::Float64) = new(exp(2 * ll), exp(2 * lσ), [])
end

function set_params!(se::SEIso, hyp::VecF64)
    length(hyp) == 2 || throw(ArgumentError("Squared exponential only has two parameters"))
    se.ℓ2, se.σ2 = exp(2 * hyp[1]), exp(2 * hyp[2])
end

get_params(se::SEIso) = Float64[log(se.ℓ2) / 2, log(se.σ2) / 2]
get_param_names(se::SEIso) = [:ll, :lσ]
num_params(se::SEIso) = 2

Statistics.cov(se::SEIso, r::Float64) = se.σ2*exp(-0.5*r/se.ℓ2)

@inline dk_dll(se::SEIso, r::Float64) = r/se.ℓ2*cov(se,r)
@inline function dk_dθp(se::SEIso, r::Float64, p::Int)
    if p==1
        return dk_dll(se, r)
    elseif p==2
        return dk_dlσ(se, r)
    else
        return NaN
    end
end


text:
function __init__()
    @require SymPy="24249f21-da20-56a4-8eb1-6a02cf4ae2e6" begin

        using Symbolics
        using Symbolics: value
        using SymbolicUtils: istree, operation, arguments, symtype,
                             FnType, Symbolic
        function symbolics_to_sympy(expr, symbols::Dict=Dict())
            expr = value(expr)
            expr isa Symbolic || return expr
            if istree(expr)
                sop = symbolics_to_sympy(operation(expr), symbols)
                sargs = map(a->symbolics_to_sympy(a, symbols), arguments(expr))
                if sop === (^) && length(sargs) == 2 && sargs[2] isa Number
                    return Base.literal_pow(^, sargs[1], Val(sargs[2]))
                else
                    return sop(sargs...)
                end
            else # isa Symbolics.Sym
                name = string(nameof(expr))
                return symtype(expr) <: FnType ? SymPy.SymFunction(name) : get(symbols, name, SymPy.Sym(name))
            end
        end

        function symbolics_to_sympy(expr, symbols)
            d = Dict(string(symbol) => symbol for symbol in symbols)
            return symbolics_to_sympy(expr,d)
        end

    end # SymPy
end


text:
# This file is part of the IntervalArithmetic.jl package; MIT licensed

## Comparisons

"""
    ==(a,b)

Checks if the intervals `a` and `b` are equal.
"""
function ==(a::Interval, b::Interval)
    isempty(a) && isempty(b) && return true
    a.lo == b.lo && a.hi == b.hi
end
!=(a::Interval, b::Interval) = !(a==b)

# Auxiliary functions: equivalent to </<=, but Inf <,<= Inf returning true
function islessprime(a::T, b::T) where T<:Real
    (isinf(a) || isinf(b)) && a==b && return true
    a < b
end

# Weakly less, \le, <=
function <=(a::Interval, b::Interval)
    isempty(a) && isempty(b) && return true
    (isempty(a) || isempty(b)) && return false
    (a.lo ≤ b.lo) && (a.hi ≤ b.hi)
end

# Strict less: <
function <(a::Interval, b::Interval)
    isempty(a) && isempty(b) && return true
    (isempty(a) || isempty(b)) && return false
    islessprime(a.lo, b.lo) && islessprime(a.hi, b.hi)
end

# precedes
function precedes(a::Interval, b::Interval)
    (isempty(a) || isempty(b)) && return true
    a.hi ≤ b.lo
end

# strictpreceds
function strictprecedes(a::Interval, b::Interval)
    (isempty(a) || isempty(b)) && return true
    # islessprime(a.hi, b.lo)
    a.hi < b.lo
end
const ≺ = strictprecedes # \prec

# zero, one, typemin, typemax
zero(a::Interval{T}) where T<:Real = Interval(zero(T))
zero(::Type{Interval{T}}) where T<:Real = Interval(zero(T))
one(a::Interval{T}) where T<:Real = Interval(one(T))
one(::Type{Interval{T}}) where T<:Real = Interval(one(T))
typemin(::Type{Interval{T}}) where T<:AbstractFloat = wideinterval(typemin(T))
typemax(::Type{Interval{T}}) where T<:AbstractFloat = wideinterval(typemax(T))
typemin(::Type{Interval{T}}) where T<:Integer = Interval(typemin(T))
typemax(::Type{Interval{T}}) where T<:Integer = Interval(typemax(T))

## Addition and subtraction

+(a::Interval) = a
-(a::Interval) = Interval(-a.hi, -a.lo)

function +(a::Interval{T}, b::T) where {T<:Real}
    isempty(a) && return emptyinterval(T)
    @round(a.lo + b, a.hi + b)
end
+(b::T, a::Interval{T}) where {T<:Real} = a+b

function -(a::Interval{T}, b::T) where {T<:Real}
    isempty(a) && return emptyinterval(T)
    @round(a.lo - b, a.hi - b)
end
function -(b::T, a::Interval{T}) where {T<:Real}
    isempty(a) && return emptyinterval(T)
    @round(b - a.hi, b - a.lo)
end

function +(a::Interval{T}, b::Interval{T}) where T<:Real
    (isempty(a) || isempty(b)) && return emptyinterval(T)
    @round(a.lo + b.lo, a.hi + b.hi)
end

function -(a::Interval{T}, b::Interval{T}) where T<:Real
    (isempty(a) || isempty(b)) && return emptyinterval(T)
    @round(a.lo - b.hi, a.hi - b.lo)
end

## Multiplication
function *(x::T, a::Interval{T}) where {T<:Real}
    isempty(a) && return emptyinterval(T)
    (iszero(a) || iszero(x)) && return zero(Interval{T})

    if x ≥ 0.0
        return @round(a.lo*x, a.hi*x)
    else
        return @round(a.hi*x, a.lo*x)
    end
end
*(a::Interval{T}, x::T) where {T<:Real} = x*a

function *(a::Interval{T}, b::Interval{T}) where T<:Real
    (isempty(a) || isempty(b)) && return emptyinterval(T)

    (iszero(a) || iszero(b)) && return zero(Interval{T})

    if b.lo >= zero(T)
        a.lo >= zero(T) && return @round(a.lo*b.lo, a.hi*b.hi)
        a.hi <= zero(T) && return @round(a.lo*b.hi, a.hi*b.lo)
        return @round(a.lo*b.hi, a.hi*b.hi)   # zero(T) ∈ a
    elseif b.hi <= zero(T)
        a.lo >= zero(T) && return @round(a.hi*b.lo, a.lo*b.hi)
        a.hi <= zero(T) && return @round(a.hi*b.hi, a.lo*b.lo)
        return @round(a.hi*b.lo, a.lo*b.lo)   # zero(T) ∈ a
    else
        a.lo > zero(T) && return @round(a.hi*b.lo, a.hi*b.hi)
        a.hi < zero(T) && return @round(a.lo*b.hi, a.lo*b.lo)
        return @round(min(a.lo*b.hi, a.hi*b.lo), max(a.lo*b.lo, a.hi*b.hi))
    end
end

## Division
function /(a::Interval{T}, x::T) where {T<:Real}
    isempty(a) && return emptyinterval(T)
    iszero(x) && return emptyinterval(T)
    iszero(a) && return zero(Interval{T})

    if x ≥ 0.0
        return @round(a.lo/x, a.hi/x)
    else
        return @round(a.hi/x, a.lo/x)
    end
end

function inv(a::Interval{T}) where T<:Real
    isempty(a) && return emptyinterval(a)

    if zero(T) ∈ a
        a.lo < zero(T) == a.hi && return @round(-Inf, inv(a.lo))
        a.lo == zero(T) < a.hi && return @round(inv(a.hi), Inf)
        a.lo < zero(T) < a.hi && return entireinterval(T)
        a == zero(a) && return emptyinterval(T)
    end

    @round(inv(a.hi), inv(a.lo))
end

function /(a::Interval{T}, b::Interval{T}) where T<:Real

    S = typeof(a.lo / b.lo)
    (isempty(a) || isempty(b)) && return emptyinterval(S)
    iszero(b) && return emptyinterval(S)

    if b.lo > zero(T) # b strictly positive

        a.lo >= zero(T) && return @round(a.lo/b.hi, a.hi/b.lo)
        a.hi <= zero(T) && return @round(a.lo/b.lo, a.hi/b.hi)
        return @round(a.lo/b.lo, a.hi/b.lo)  # zero(T) ∈ a

    elseif b.hi < zero(T) # b strictly negative

        a.lo >= zero(T) && return @round(a.hi/b.hi, a.lo/b.lo)
        a.hi <= zero(T) && return @round(a.hi/b.lo, a.lo/b.hi)
        return @round(a.hi/b.hi, a.lo/b.hi)  # zero(T) ∈ a

    else   # b contains zero, but is not zero(b)

        iszero(a) && return zero(Interval{S})

        if iszero(b.lo)

            a.lo >= zero(T) && return @round(a.lo/b.hi, Inf)
            a.hi <= zero(T) && return @round(-Inf, a.hi/b.hi)
            return entireinterval(S)

        elseif iszero(b.hi)

            a.lo >= zero(T) && return @round(-Inf, a.lo/b.lo)
            a.hi <= zero(T) && return @round(a.hi/b.lo, Inf)
            return entireinterval(S)

        else

            return entireinterval(S)

        end
    end
end

function extended_div(a::Interval{T}, b::Interval{T}) where T<:Real

    S = typeof(a.lo / b.lo)
    if 0 < b.hi && 0 > b.lo && 0 ∉ a
        if a.hi < 0
            return (Interval(-Inf, a.hi / b.hi), Interval(a.hi / b.lo, Inf))

        elseif a.lo > 0
            return (Interval(-Inf, a.lo / b.lo), Interval(a.lo / b.hi, Inf))

        end
    elseif 0 ∈ a && 0 ∈ b
        return (entireinterval(S), emptyinterval(S))
    else
        return (a / b, emptyinterval(S))
    end
end

//(a::Interval, b::Interval) = a / b    # to deal with rationals

function min_ignore_nans(args...)
    min(Iterators.filter(x->!isnan(x), args)...)
end

function max_ignore_nans(args...)
    max(Iterators.filter(x->!isnan(x), args)...)
end

## fma: fused multiply-add
function fma(a::Interval{T}, b::Interval{T}, c::Interval{T}) where T
    #T = promote_type(eltype(a), eltype(b), eltype(c))

    (isempty(a) || isempty(b) || isempty(c)) && return emptyinterval(T)

    if isentire(a)
        b == zero(b) && return c
        return entireinterval(T)

    elseif isentire(b)
        a == zero(a) && return c
        return entireinterval(T)

    end

    lo = setrounding(T, RoundDown) do
        lo1 = fma(a.lo, b.lo, c.lo)
        lo2 = fma(a.lo, b.hi, c.lo)
        lo3 = fma(a.hi, b.lo, c.lo)
        lo4 = fma(a.hi, b.hi, c.lo)
        min_ignore_nans(lo1, lo2, lo3, lo4)
    end

    hi = setrounding(T, RoundUp) do
        hi1 = fma(a.lo, b.lo, c.hi)
        hi2 = fma(a.lo, b.hi, c.hi)
        hi3 = fma(a.hi, b.lo, c.hi)
        hi4 = fma(a.hi, b.hi, c.hi)
        max_ignore_nans(hi1, hi2, hi3, hi4)
    end

    Interval(lo, hi)
end

## Scalar functions on intervals (no directed rounding used)

function mag(a::Interval{T}) where T<:Real
    isempty(a) && return convert(eltype(a), NaN)
    # r1, r2 = setrounding(T, RoundUp) do
    #     abs(a.lo), abs(a.hi)
    # end
    max( abs(a.lo), abs(a.hi) )
end

function mig(a::Interval{T}) where T<:Real
    isempty(a) && return convert(eltype(a), NaN)
    zero(a.lo) ∈ a && return zero(a.lo)
    r1, r2 = setrounding(T, RoundDown) do
        abs(a.lo), abs(a.hi)
    end
    min( r1, r2 )
end

# Infimum and supremum of an interval
inf(a::Interval) = a.lo
sup(a::Interval) = a.hi

## Functions needed for generic linear algebra routines to work
real(a::Interval) = a

function abs(a::Interval)
    isempty(a) && return emptyinterval(a)
    Interval(mig(a), mag(a))
end

function abs2(a::Interval)
    sqr(a)
end

function min(a::Interval, b::Interval)
    (isempty(a) || isempty(b)) && return emptyinterval(a)
    Interval( min(a.lo, b.lo), min(a.hi, b.hi))
end

function max(a::Interval, b::Interval)
    (isempty(a) || isempty(b)) && return emptyinterval(a)
    Interval( max(a.lo, b.lo), max(a.hi, b.hi))
end

dist(a::Interval, b::Interval) = max(abs(a.lo-b.lo), abs(a.hi-b.hi))
eps(a::Interval) = Interval(max(eps(a.lo), eps(a.hi)))
eps(::Type{Interval{T}}) where T<:Real = Interval(eps(T))

## floor, ceil, trunc, sign, roundTiesToEven, roundTiesToAway
function floor(a::Interval)
    isempty(a) && return emptyinterval(a)
    Interval(floor(a.lo), floor(a.hi))
end

function ceil(a::Interval)
    isempty(a) && return emptyinterval(a)
    Interval(ceil(a.lo), ceil(a.hi))
end

function trunc(a::Interval)
    isempty(a) && return emptyinterval(a)
    Interval(trunc(a.lo), trunc(a.hi))
end

function sign(a::Interval)
    isempty(a) && return emptyinterval(a)
    return Interval(sign(a.lo), sign(a.hi))
end

# RoundTiesToEven is an alias of `RoundNearest`
const RoundTiesToEven = RoundNearest
# RoundTiesToAway is an alias of `RoundNearestTiesAway`
const RoundTiesToAway = RoundNearestTiesAway

"""
    round(a::Interval[, RoundingMode])

Returns the interval with rounded to an interger limits.

For compliance with the IEEE Std 1788-2015, "roundTiesToEven" corresponds
to `round(a)` or `round(a, RoundNearest)`, and "roundTiesToAway"
to `round(a, RoundNearestTiesAway)`.
"""
round(a::Interval) = round(a, RoundNearest)
round(a::Interval, ::RoundingMode{:ToZero}) = trunc(a)
round(a::Interval, ::RoundingMode{:Up}) = ceil(a)
round(a::Interval, ::RoundingMode{:Down}) = floor(a)

function round(a::Interval, ::RoundingMode{:Nearest})
    isempty(a) && return emptyinterval(a)
    Interval(round(a.lo), round(a.hi))
end

function round(a::Interval, ::RoundingMode{:NearestTiesAway})
    isempty(a) && return emptyinterval(a)
    Interval(round(a.lo, RoundNearestTiesAway), round(a.hi, RoundNearestTiesAway))
end

# mid, diam, radius

# Compare pg. 64 of the IEEE 1788-2015 standard:
"""
    mid(a::Interval, α=0.5)

Find an intermediate point at a relative position `α`` in the interval `a`.
The default is the true midpoint at `α = 0.5`.

Assumes 0 ≤ α ≤ 1.

Warning: if the parameter `α = 0.5` is explicitely set, the behavior differs
from the default case if the provided `Interval` is not finite, since when
`α` is provided `mid` simply replaces `+∞` (respectively `-∞`) by `prevfloat(+∞)`
(respecively `nextfloat(-∞)`) for the computation of the intermediate point.
"""
function mid(a::Interval{T}, α) where T

    isempty(a) && return convert(T, NaN)

    lo = (a.lo == -∞ ? nextfloat(-∞) : a.lo)
    hi = (a.hi == +∞ ? prevfloat(+∞) : a.hi)

    midpoint = α * (hi - lo) + lo
    isfinite(midpoint) && return midpoint
    #= Fallback in case of overflow: hi - lo == +∞.
       This case can not be the default one as it does not pass several
       IEEE1788-2015 tests for small floats.
    =#
    return (1-α) * lo + α * hi
end

"""
    mid(a::Interval)

Find the midpoint of interval `a`.

For intervals of the form `[-∞, x]` or `[x, +∞]` where `x` is finite, return
respectively `nextfloat(-∞)` and `prevfloat(+∞)`. Note that it differs from the
behavior of `mid(a, α=0.5)`.
"""
function mid(a::Interval{T}) where T

    isempty(a) && return convert(T, NaN)
    isentire(a) && return zero(a.lo)

    a.lo == -∞ && return nextfloat(a.lo)
    a.hi == +∞ && return prevfloat(a.hi)

    midpoint = 0.5 * (a.lo + a.hi)
    isfinite(midpoint) && return midpoint
    #= Fallback in case of overflow: a.hi + a.lo == +∞ or a.hi + a.lo == -∞.
       This case can not be the default one as it does not pass several
       IEEE1788-2015 tests for small floats.
    =#
    return 0.5 * a.lo + 0.5 * a.hi
end

mid(a::Interval{Rational{T}}) where T = (1//2) * (a.lo + a.hi)

"""
    diam(a::Interval)

Return the diameter (length) of the `Interval` `a`.
"""
function diam(a::Interval{T}) where T<:Real
    isempty(a) && return convert(T, NaN)

    @round_up(a.hi - a.lo) # cf page 64 of IEEE1788
end

# Should `radius` this yield diam(a)/2? This affects other functions!
"""
    radius(a::Interval)

Return the radius of the `Interval` `a`, such that
`a ⊆ m ± radius`, where `m = mid(a)` is the midpoint.
"""
function radius(a::Interval)
    isempty(a) && return convert(eltype(a), NaN)
    m = mid(a)
    return max(m - a.lo, a.hi - m)
end

function radius(a::Interval{Rational{T}}) where T
    m = (a.lo + a.hi) / 2
    return max(m - a.lo, a.hi - m)
end

# cancelplus and cancelminus
"""
    cancelminus(a, b)

Return the unique interval `c` such that `b+c=a`.

See Section 12.12.5 of the IEEE-1788 Standard for
Interval Arithmetic.
"""
function cancelminus(a::Interval{T}, b::Interval{T}) where T<:Real
    (isempty(a) && (isempty(b) || !isunbounded(b))) && return emptyinterval(T)

    (isunbounded(a) || isunbounded(b) || isempty(b)) && return entireinterval(T)

    diam(a) < diam(b) && return entireinterval(T)

    c_lo = @round_down(a.lo - b.lo)
    c_hi = @round_up(a.hi - b.hi)

    c_lo > c_hi && return entireinterval(T)

    c_lo == Inf && return Interval(prevfloat(c_lo), c_hi)
    c_hi == -Inf && return Interval(c_lo, nextfloat(c_hi))

    a_lo = @round_down(b.lo + c_lo)
    a_hi = @round_up(b.hi + c_hi)

    if a_lo ≤ a.lo ≤ a.hi ≤ a_hi
        (nextfloat(a.hi) < a_hi || prevfloat(a.lo) > a_hi) &&
            return entireinterval(T)
        return Interval(c_lo, c_hi)
     end

    return entireinterval(T)
end
cancelminus(a::Interval, b::Interval) = cancelminus(promote(a, b)...)

"""
    cancelplus(a, b)

Returns the unique interval `c` such that `b-c=a`;
it is equivalent to `cancelminus(a, −b)`.
"""
cancelplus(a::Interval, b::Interval) = cancelminus(a, -b)

# midpoint-radius forms
midpoint_radius(a::Interval) = (mid(a), radius(a))

interval_from_midpoint_radius(midpoint, radius) = Interval(midpoint-radius, midpoint+radius)

isinteger(a::Interval) = (a.lo == a.hi) && isinteger(a.lo)

convert(::Type{Integer}, a::Interval) = isinteger(a) ?
        convert(Integer, a.lo) : throw(ArgumentError("Cannot convert $a to integer"))


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

@testset "skipchars for IOStream" begin
    mktemp() do path, file
        function append_to_file(str)
            mark(file)
            print(file, str)
            flush(file)
            reset(file)
        end
        # test it doesn't error on eof
        @test eof(skipchars(isspace, file))

        # test it correctly skips
        append_to_file("    ")
        @test eof(skipchars(isspace, file))

        # test it correctly detects comment lines
        append_to_file("#    \n   ")
        @test eof(skipchars(isspace, file, linecomment='#'))

        # test it stops at the appropriate time
        append_to_file("   not a space")
        @test !eof(skipchars(isspace, file))
        @test read(file, Char) == 'n'

        # test it correctly ignores the contents of comment lines
        append_to_file("  #not a space \n   not a space")
        @test !eof(skipchars(isspace, file, linecomment='#'))
        @test read(file, Char) == 'n'

        # test it correctly handles unicode
        for (byte, char) in zip(1:4, ('@','߷','࿊','𐋺'))
            append_to_file("abcdef$char")
            @test ncodeunits(char) == byte
            @test !eof(skipchars(isletter, file))
            @test read(file, Char) == char
        end
    end
end

@testset "readbytes_some! via readbytes!" begin
    mktemp() do path, file
        function append_to_file(str)
            mark(file)
            print(file, str)
            flush(file)
            reset(file)
        end
        append_to_file("aaaaaaaaaaaaaaaaa")
        b = UInt8[0]
        readbytes!(file, b, all=false)
        @test String(b) == "a"
        # with resizing of b
        b = UInt8[]
        readbytes!(file, b, 2, all=false)
        @test String(b) == "aa"
        # readbytes_all with resizing
        b = UInt8[]
        readbytes!(file, b, 15)
        @test String(b) == "aaaaaaaaaaaaaa"
    end
end
@testset "issue #18755" begin
    mktemp() do path, io
        write(io, zeros(UInt8, 131073))
        @test position(io) == 131073
        write(io, zeros(UInt8, 131073))
        @test position(io) == 262146
    end
end

@testset "issue #27951" begin
    a = UInt8[1 3; 2 4]
    s = view(a, [1,2], :)
    mktemp() do path, io
        write(io, s)
        seek(io, 0)
        b = Vector{UInt8}(undef, 4)
        @test readbytes!(io, b) == 4
        @test b == 0x01:0x04
    end
end

@test Base.open_flags(read=false, write=true, append=false) == (read=false, write=true, create=true, truncate=true, append=false)

@testset "issue #30978" begin
    mktemp() do path, io
        x = rand(UInt8, 100)
        write(path, x)
        # Should not throw OutOfMemoryError
        y = open(f -> read(f, typemax(Int)), path)
        @test x == y

        # Should resize y to right length
        y = zeros(UInt8, 99)
        open(f -> readbytes!(f, y, 101, all=true), path)
        @test x == y
        y = zeros(UInt8, 99)
        open(f -> readbytes!(f, y, 101, all=false), path)
        @test x == y

        # Should never shrink y below original size
        y = zeros(UInt8, 101)
        open(f -> readbytes!(f, y, 102, all=true), path)
        @test y == [x; 0]
        y = zeros(UInt8, 101)
        open(f -> readbytes!(f, y, 102, all=false), path)
        @test y == [x; 0]
    end
end

@testset "peek(::IOStream)" begin
    mktemp() do _, file
        @test_throws EOFError peek(file)
        mark(file)
        write(file, "Lávate las manos")
        flush(file)
        reset(file)
        @test peek(file) == 0x4c
    end
end

@testset "issue #36004" begin
    f = tempname()
    open(f, "w") do io
        write(io, "test")
    end
    open(f, "r") do io
        @test length(readavailable(io)) > 0
    end
end

max_stars_repo_name: TimoLarson/julia

max_issues_repo_name: TimoLarson/julia

max_forks_repo_name: TimoLarson/julia