text:
# adapted from
# https://github.com/TEOS-10/GSW-C/blob/95a9caeb128e4793b538b5ded889c83c913584fb/gsw_check_functions.c
#
# Copyright (c) 2011, SCOR/IAPSO WG127 (Scientific Committee on Oceanic Research/
# International Association for the Physical Sciences of the Oceans, Working Group 127).
# https://github.com/TEOS-10/GSW-C/blob/95a9caeb128e4793b538b5ded889c83c913584fb/LICENSE

using GibbsSeaWater
using Test

# load test data
include("gsw_check_data.jl")

# test if value is equal to reference upto a precession of the
# variable reference_ca
# non-finite values in reference are ignored
macro gswtest(value,reference)
    return quote
        mask = isfinite.($reference)
        @test $value[mask] ≈ $reference[mask]  atol=$(Symbol(reference,:_ca))
    end
end

macro gswtest(value,reference...)
    return Expr(:block, [
    quote
        @test map(vab -> vab[$ii],$value) ≈ $(reference[ii]) nans=true atol=$(Symbol(reference[ii],:_ca))
    end for ii in 1:length(reference)]...)
end

# first dimension is the depth and the
# second dimension is the station
# transpose lat_cast and long_cast so that the
# last dimension is the station
lat = lat_cast'
lon = long_cast'

# check gsw functions
c = gsw_c_from_sp.(sp,t,p)
@testset "Practical Salinity, PSS-78" begin
    @gswtest gsw_c_from_sp.(sp,t,p) c_from_sp
    @gswtest gsw_sp_from_c.(c,t,p) sp_from_c
    @gswtest gsw_sp_from_sk.(sk) sp_from_sk
end

@testset "Absolute Salinity, Preformed Salinity and Conservative Temperature" begin
    @gswtest gsw_sa_from_sp.(sp,p,lon,lat) sa_from_sp
    @gswtest gsw_sstar_from_sp.(sp,p,lon,lat) sstar_from_sp
    @gswtest gsw_ct_from_t.(sa,t,p) ct_from_t
end

sr = gsw_sr_from_sp.(sp)
#issue see issue #3
#z = gsw_z_from_p.(p,lat,0.,0.)
sstar = gsw_sstar_from_sa.(sa,p,lon,lat)
pt = gsw_pt_from_ct.(sa,ct)
entropy = gsw_entropy_from_pt.(sa,pt)
@testset "Other conversions between Temperatures, Salinities, Entropy, Pressure and Height" begin
	@gswtest gsw_deltasa_from_sp.(sp,p,lon,lat)  deltasa_from_sp
	@gswtest gsw_sr_from_sp.(sp) sr_from_sp
	@gswtest gsw_sp_from_sr.(sr) sp_from_sr
	@gswtest gsw_sp_from_sa.(sa,p,lon,lat) sp_from_sa
	@gswtest gsw_sstar_from_sa.(sa,p,lon,lat) sstar_from_sa
	@gswtest gsw_sa_from_sstar.(sstar,p,lon,lat)  sa_from_sstar
	@gswtest gsw_sp_from_sstar.(sstar,p,lon,lat)  sp_from_sstar
	@gswtest gsw_pt_from_ct.(sa,ct) pt_from_ct
	@gswtest gsw_t_from_ct.(sa,ct,p) t_from_ct
	@gswtest gsw_ct_from_pt.(sa,pt) ct_from_pt
	@gswtest gsw_pt0_from_t.(sa,t,p) pt0_from_t
	@gswtest gsw_pt_from_t.(sa,t,p,pref[1]) pt_from_t
#	@gswtest gsw_z_from_p.(p,lat,0.,0.) z_from_p
#	@gswtest gsw_p_from_z.(z,lat,0.,0.) p_from_z
	@gswtest gsw_entropy_from_pt.(sa,pt) entropy_from_pt
	@gswtest gsw_pt_from_entropy.(sa,entropy) pt_from_entropy
	@gswtest gsw_ct_from_entropy.(sa,entropy) ct_from_entropy
	@gswtest gsw_entropy_from_ct.(sa,ct) entropy_from_ct
	@gswtest gsw_entropy_from_t.(sa,t,p) entropy_from_t
	@gswtest gsw_adiabatic_lapse_rate_from_ct.(sa,ct,p)  adiabatic_lapse_rate_from_ct
end

@testset "Specific Volume, Density and Enthalpy" begin
    @gswtest gsw_specvol.(sa,ct,p) specvol
	@gswtest gsw_alpha.(sa,ct,p) alpha
	@gswtest gsw_beta.(sa,ct,p) beta
	@gswtest gsw_alpha_on_beta.(sa,ct,p) alpha_on_beta
    @gswtest gsw_specvol_alpha_beta.(sa,ct,p) v_vab alpha_vab beta_vab
	@gswtest gsw_specvol_first_derivatives.(sa,ct,p) v_sa v_ct v_p
	@gswtest gsw_specvol_second_derivatives.(sa,ct,p) v_sa_sa v_sa_ct v_ct_ct v_sa_p v_ct_p
	@gswtest gsw_specvol_first_derivatives_wrt_enthalpy.(sa,ct,p) v_sa_wrt_h v_h
	@gswtest gsw_specvol_second_derivatives_wrt_enthalpy.(sa,ct,p) v_sa_sa_wrt_h  v_sa_h v_h_h
	@gswtest gsw_specvol_anom_standard.(sa,ct,p) specvol_anom_standard
	@gswtest gsw_rho.(sa,ct,p) rho
	@gswtest gsw_rho_alpha_beta.(sa,ct,p) rho_rab alpha_rab beta_rab
	@gswtest gsw_rho_first_derivatives.(sa,ct,p) rho_sa rho_ct rho_p
	@gswtest gsw_rho_second_derivatives.(sa,ct,p) rho_sa_sa rho_sa_ct rho_ct_ct rho_sa_p rho_ct_p
	@gswtest gsw_rho_first_derivatives_wrt_enthalpy.(sa,ct,p) rho_sa_wrt_h rho_h
	@gswtest gsw_rho_second_derivatives_wrt_enthalpy.(sa,ct,p) rho_sa_sa_wrt_h rho_sa_h rho_h_h
#=
	@gswtest gsw_sigma0.(sa,ct), value,sigma0);
	@gswtest gsw_sigma1.(sa,ct), value,sigma1);
	@gswtest gsw_sigma2.(sa,ct), value,sigma2);
	@gswtest gsw_sigma3.(sa,ct), value,sigma3);
	@gswtest gsw_sigma4.(sa,ct), value,sigma4);
	@gswtest gsw_sound_speed.(sa,ct,p), value,sound_speed);
	@gswtest gsw_kappa.(sa,ct,p), value,kappa);
	@gswtest gsw_cabbeling.(sa,ct,p), value,cabbeling);
	@gswtest gsw_thermobaric.(sa,ct,p), value,thermobaric);
	@gswtest gsw_sa_from_rho.(rho,ct,p), value,sa_from_rho);
	test_sub1(ct_from_rho, (rho,sa,p,VALS1,NULL),val1,ct_from_rho);
	@gswtest gsw_ct_maxdensity.(sa,p), value,ct_maxdensity);
	@gswtest gsw_internal_energy.(sa,ct,p), value,internal_energy);
	@gswtest gsw_enthalpy.(sa,ct,p), h,enthalpy);
	@gswtest gsw_enthalpy_diff,
	    (sa,ct,p_shallow,p_deep), value,enthalpy_diff);
	@gswtest gsw_ct_from_enthalpy.(sa,h,p), value,ct_from_enthalpy);
	@gswtest gsw_dynamic_enthalpy.(sa,ct,p), value,dynamic_enthalpy);
	test_sub2(enthalpy_first_derivatives, (sa,ct,p,VALS2),
	    val1,h_sa, val2,h_ct);
	test_sub3(enthalpy_second_derivatives,(sa,ct,p,VALS3),
	    val1,h_sa_sa,val2,h_sa_ct, val3,h_ct_ct);
=#
end
#=
	@testset "Derivatives of entropy, CT and pt" begin

	test_sub2(ct_first_derivatives, (sa,pt,VALS2),
	    val1,ct_sa, val2,ct_pt);
	test_sub3(ct_second_derivatives, (sa,pt,VALS3),
	    val1,ct_sa_sa, val2,ct_sa_pt, val3,ct_pt_pt);
	test_sub2(entropy_first_derivatives, (sa,ct,VALS2),
	    val1,eta_sa, val2,eta_ct);
	test_sub3(entropy_second_derivatives, (sa,ct,VALS3),
	    val1,eta_sa_sa, val2,eta_sa_ct, val3,eta_ct_ct);
	test_sub2(pt_first_derivatives, (sa,ct,VALS2),
	    val1,pt_sa, val2,pt_ct);
	test_sub3(pt_second_derivatives, (sa,ct,VALS3),
	    val1,pt_sa_sa,val2,pt_sa_ct,val3,pt_ct_ct);
end

	@testset "Freezing temperatures" begin

	saturation_fraction = 0.5;

	@gswtest gsw_ct_freezing,(sa,p,saturation_fraction),
	    ctf,ct_freezing);
	@gswtest gsw_ct_freezing_poly.(sa,p,saturation_fraction), ctf_poly,
	    ct_freezing_poly);
	@gswtest gsw_t_freezing.(sa,p,saturation_fraction), tf,
	    t_freezing);
	@gswtest gsw_t_freezing_poly.(sa,p,saturation_fraction), tf_poly,
	    t_freezing_poly);
	@gswtest gsw_pot_enthalpy_ice_freezing.(sa,p), value,
	    pot_enthalpy_ice_freezing);
	@gswtest gsw_pot_enthalpy_ice_freezing_poly.(sa,p), value,
	    pot_enthalpy_ice_freezing_poly);
	@gswtest gsw_sa_freezing_from_ct.(ctf,p,saturation_fraction),value,
	    sa_freezing_from_ct);
	@gswtest gsw_sa_freezing_from_ct_poly,
	    (ctf_poly,p,saturation_fraction),value,
	    sa_freezing_from_ct_poly);
	@gswtest gsw_sa_freezing_from_t.(tf,p,saturation_fraction),value,
	    sa_freezing_from_t);
	@gswtest gsw_sa_freezing_from_t_poly,
	    (tf_poly,p,saturation_fraction),value,
	    sa_freezing_from_t_poly);
	test_sub2(ct_freezing_first_derivatives,
	    (sa,p,saturation_fraction,VALS2),
		val1,ctfreezing_sa,val2,ctfreezing_p);
	test_sub2(ct_freezing_first_derivatives_poly,
	    (sa,p,saturation_fraction,VALS2),val1,ctfreezing_sa_poly,
		val2,ctfreezing_p_poly);
	test_sub2(t_freezing_first_derivatives,
	    (sa,p,saturation_fraction,VALS2),
	    val1,tfreezing_sa,val2,tfreezing_p);
	test_sub2(t_freezing_first_derivatives_poly,
	    (sa,p,saturation_fraction,VALS2),
	    val1,tfreezing_sa_poly,val2,tfreezing_p_poly);
	test_sub2(pot_enthalpy_ice_freezing_first_derivatives,
		(sa,p,VALS2),
		val1, pot_enthalpy_ice_freezing_sa,
		val2, pot_enthalpy_ice_freezing_p);
	test_sub2(pot_enthalpy_ice_freezing_first_derivatives_poly,
		(sa,p,VALS2),
		val1, pot_enthalpy_ice_freezing_sa_poly,
		val2, pot_enthalpy_ice_freezing_p_poly);

	end

	@testset "Isobaric Melting Enthalpy and Isobaric Evaporation Enthalpy" begin

	@gswtest gsw_latentheat_melting.(sa,p), value,latentheat_melting);
	@gswtest gsw_latentheat_evap_ct.(sa,ct), value,latentheat_evap_ct);
	@gswtest gsw_latentheat_evap_t.(sa,t), value,latentheat_evap_t);

	end

	@testset "Planet Earth properties" begin

	@gswtest gsw_grav.(lat,p), value,grav);

	end

	@testset "Density and enthalpy in terms of CT, derived from the exact Gibbs function" begin

	@gswtest gsw_enthalpy_ct_exact,(sa,ct,p),value,enthalpy_ct_exact);
	test_sub2(enthalpy_first_derivatives_ct_exact, (sa,ct,p,VALS2),
	    val1,h_sa_ct_exact,val2,h_ct_ct_exact);
	test_sub3(enthalpy_second_derivatives_ct_exact, (sa,ct,p,VALS3),
	    val1,h_sa_sa_ct_exact, val2,h_sa_ct_ct_exact,val3,h_ct_ct_ct_exact);

	end

	@testset "Basic thermodynamic properties in terms of in-situ t, based on the exact Gibbs function" begin

	@gswtest gsw_rho_t_exact.(sa,t,p),value,rho_t_exact);
	@gswtest gsw_pot_rho_t_exact.(sa,t,p,pref[0]),value,
	    pot_rho_t_exact);
	@gswtest gsw_alpha_wrt_t_exact.(sa,t,p),value,alpha_wrt_t_exact);
	@gswtest gsw_beta_const_t_exact.(sa,t,p),value,
	    beta_const_t_exact);
	@gswtest gsw_specvol_t_exact.(sa,t,p),value,specvol_t_exact);
	@gswtest gsw_sound_speed_t_exact.(sa,t,p),value,
	    sound_speed_t_exact);
	@gswtest gsw_kappa_t_exact.(sa,t,p),value,kappa_t_exact);
	@gswtest gsw_enthalpy_t_exact.(sa,t,p),value,enthalpy_t_exact);
	test_sub3(ct_first_derivatives_wrt_t_exact, (sa,t,p,VALS3),
	    val1,ct_sa_wrt_t, val2,ct_t_wrt_t,val3,ct_p_wrt_t);
	@gswtest gsw_chem_potential_water_t_exact.(sa,t,p),value,
	    chem_potential_water_t_exact);
	@gswtest gsw_t_deriv_chem_potential_water_t_exact.(sa,t,p),
	    value,t_deriv_chem_potential_water_t_exact);
	@gswtest gsw_dilution_coefficient_t_exact.(sa,t,p),value,
	    dilution_coefficient_t_exact);

	end

	@testset "Library functions of the GSW Toolbox" begin

	@gswtest gsw_deltasa_atlas.(p,lon,lat),value,deltasa_atlas);
	@gswtest gsw_fdelta.(p,lon,lat),value,fdelta);

	end

	@testset "Water column properties, based on the 75-term polynomial " *
	    "for specific volume" begin

	count	= cast_mpres_m*cast_mpres_n;
	for (j = 0; j<cast_mpres_n; j++) {
	    k = j*cast_m; l = j*cast_mpres_m;
    	    gsw_nsquared(&sa[k],&ct[k],&p[k],&lat[k],cast_m,&val1[l],&val2[l]);
	}
	check_accuracy("nsquared",n2_ca,"n2",count, val1, n2);
	check_accuracy("nsquared",p_mid_n2_ca,"p_mid_n2",count, val2, p_mid_n2);

	for (j = 0; j<cast_mpres_n; j++) {
	    k = j*cast_m; l = j*cast_mpres_m;
	    gsw_turner_rsubrho(&sa[k],&ct[k],&p[k],cast_m,&val1[l],&val2[l],
				&val3[l]);
	}
	check_accuracy("turner_rsubrho",tu_ca,"tu",count, val1, tu);
	check_accuracy("rsubrhorner_rsubrho",rsubrho_ca,"rsubrho",count, val2,
		rsubrho);
	check_accuracy("p_mid_tursrrner_rsubrho",p_mid_tursr_ca,"p_mid_tursr",
		count, val3, p_mid_tursr);

	for (j = 0; j<cast_mpres_n; j++) {
	    k = j*cast_m; l = j*cast_mpres_m;
	    gsw_ipv_vs_fnsquared_ratio(&sa[k],&ct[k],&p[k],pref[0],cast_m,
		&val1[l], &val2[l]);
	}
	check_accuracy("ipv_vs_fnsquared_ratio",ipvfn2_ca,"ipvfn2",count,
		val1, ipvfn2);
	check_accuracy("ipv_vs_fnsquared_ratio",p_mid_ipvfn2_ca,"p_mid_ipvfn2",
		count, val2, p_mid_ipvfn2);

	for (j = 0; j<cast_mpres_n; j++) {
	    k = j*cast_m;
	    for (n=0; n<cast_m; n++)
		if (isnan(sa[k+n]) || fabs(sa[k+n]) >= GSW_ERROR_LIMIT)
		    break;
	    if (gsw_geo_strf_dyn_height(&sa[k],&ct[k],&p[k],pref[0],n,
		&val1[k]) == NULL)
		printf("geo_strf_dyn_height returned NULL.\n");
	}
	check_accuracy("geo_strf_dyn_height",geo_strf_dyn_height_ca,
		"geo_strf_dyn_height",count, val1, geo_strf_dyn_height);

	for (j = 0; j<cast_mpres_n; j++) {
	    k = j*cast_m;
	    for (n=0; n<cast_m; n++)
		if (isnan(sa[k+n]) || fabs(sa[k+n]) >= GSW_ERROR_LIMIT)
		    break;
	    gsw_geo_strf_dyn_height_pc(&sa[k],&ct[k],&delta_p[k],n,
		&val1[k], &val2[k]);
	}
	check_accuracy("geo_strf_dyn_height_pc",geo_strf_dyn_height_pc_ca,
		"geo_strf_dyn_height_pc",count, val1, geo_strf_dyn_height_pc);
	check_accuracy("geo_strf_dyn_height_pc",geo_strf_dyn_height_pc_p_mid_ca,
		"geo_strf_dyn_height_pc_p_mid",count, val2,
		geo_strf_dyn_height_pc_p_mid);

	end

	@testset "Thermodynamic properties of ice Ih" begin

	count = cast_ice_m*cast_ice_n;

	@gswtest gsw_rho_ice.(t_seaice,p_arctic),value,rho_ice);
	@gswtest gsw_alpha_wrt_t_ice.(t_seaice,p_arctic),value,
	    alpha_wrt_t_ice);
	@gswtest gsw_specvol_ice.(t_seaice,p_arctic),value,specvol_ice);
	@gswtest gsw_pressure_coefficient_ice.(t_seaice,p_arctic),value,
	    pressure_coefficient_ice);
	@gswtest gsw_sound_speed_ice.(t_seaice,p_arctic),value,
	    sound_speed_ice);
	@gswtest gsw_kappa_ice.(t_seaice,p_arctic),value,kappa_ice);
	@gswtest gsw_kappa_const_t_ice.(t_seaice,p_arctic),value,
	    kappa_const_t_ice);
	@gswtest gsw_internal_energy_ice.(t_seaice,p_arctic),value,
	    internal_energy_ice);
	@gswtest gsw_enthalpy_ice.(t_seaice,p_arctic),value,enthalpy_ice);
	@gswtest gsw_entropy_ice.(t_seaice,p_arctic),value,entropy_ice);
	@gswtest gsw_cp_ice.(t_seaice,p_arctic),value,cp_ice);
	@gswtest gsw_chem_potential_water_ice,
	    (t_seaice,p_arctic),value,chem_potential_water_ice);
	@gswtest gsw_helmholtz_energy_ice.(t_seaice,p_arctic),value,
	    helmholtz_energy_ice);
	@gswtest gsw_adiabatic_lapse_rate_ice,
	    (t_seaice,p_arctic),value,adiabatic_lapse_rate_ice);
	@gswtest gsw_pt0_from_t_ice,(t_seaice,p_arctic),pt0, pt0_from_t_ice);
	@gswtest gsw_pt_from_t_ice.(t_seaice,p_arctic,pref[0]),value,
	    pt_from_t_ice);
	@gswtest gsw_t_from_pt0_ice.(pt0,p_arctic),value,t_from_pt0_ice);
	@gswtest gsw_pot_enthalpy_from_pt_ice.(pt0), h,
	    pot_enthalpy_from_pt_ice);
	@gswtest gsw_pt_from_pot_enthalpy_ice.(h), value,
	    pt_from_pot_enthalpy_ice);
	@gswtest gsw_pot_enthalpy_from_pt_ice_poly.(pt0), h,
	    pot_enthalpy_from_pt_ice_poly);
	@gswtest gsw_pt_from_pot_enthalpy_ice_poly.(h),value,
	    pt_from_pot_enthalpy_ice_poly);

	saturation_fraction = 0.5;

	@gswtest gsw_pressure_freezing_ct,
	    (sa_arctic,ct_arctic-1.0,saturation_fraction),value,
	    pressure_freezing_ct);

	end

	@testset "Thermodynamic interaction between ice and seawater" begin

	@gswtest gsw_melting_ice_sa_ct_ratio,
	    (sa_arctic,ct_arctic,p_arctic,t_ice),value,
	    melting_ice_sa_ct_ratio);
	@gswtest gsw_melting_ice_sa_ct_ratio_poly,
	    (sa_arctic,ct_arctic,p_arctic,t_ice),value,
	    melting_ice_sa_ct_ratio_poly);
	@gswtest gsw_melting_ice_equilibrium_sa_ct_ratio,
	    (sa_arctic,p_arctic),value,
	    melting_ice_equilibrium_sa_ct_ratio);
	@gswtest gsw_melting_ice_equilibrium_sa_ct_ratio_poly,
	    (sa_arctic,p_arctic),value,
	    melting_ice_equilibrium_sa_ct_ratio_poly);
	test_sub2(melting_ice_into_seawater,
	    (sa_arctic,ct_arctic+0.1,p_arctic,w_ice,t_ice,VALS3),
	    val1, melting_ice_into_seawater_sa_final,
	    val2, melting_ice_into_seawater_ct_final);
	    /*val3, melting_ice_into_seawater_w_ih);*/
	test_sub3(ice_fraction_to_freeze_seawater,
	    (sa_arctic,ct_arctic,p_arctic,t_ice,VALS3),
	    val1, ice_fraction_to_freeze_seawater_sa_freeze,
	    val2, ice_fraction_to_freeze_seawater_ct_freeze,
	    val3, ice_fraction_to_freeze_seawater_w_ih);
	test_sub3(frazil_ratios_adiabatic,
	    (sa_arctic,p_arctic,w_ice,VALS3),
	    val1,dsa_dct_frazil, val2,dsa_dp_frazil,
	    val3,dct_dp_frazil);
	test_sub3(frazil_ratios_adiabatic_poly,
	    (sa_arctic,p_arctic,w_ice,VALS3),
	    val1,dsa_dct_frazil_poly, val2,dsa_dp_frazil_poly,
	    val3,dct_dp_frazil_poly);
	test_sub3(frazil_properties_potential,
	    (sa_bulk,h_pot_bulk,p_arctic, VALS3),
	    val1, frazil_properties_potential_sa_final,
	    val2, frazil_properties_potential_ct_final,
	    val3, frazil_properties_potential_w_ih_final);
	test_sub3(frazil_properties_potential_poly,
	    (sa_bulk,h_pot_bulk, p_arctic,VALS3),
	    val1, frazil_properties_potential_poly_sa_final,
	    val2, frazil_properties_potential_poly_ct_final,
	    val3, frazil_properties_potential_poly_w_ih_final);
	test_sub3(frazil_properties,
	    (sa_bulk,h_bulk,p_arctic,VALS3),
	    val1,frazil_properties_sa_final,
	    val2,frazil_properties_ct_final,
	    val3,frazil_properties_w_ih_final);

	end

	@testset "Thermodynamic interaction between seaice and seawater" begin

	@gswtest gsw_melting_seaice_sa_ct_ratio,
	    (sa_arctic,ct_arctic,p_arctic, sa_seaice,t_seaice),
	    value,melting_seaice_sa_ct_ratio);
	@gswtest gsw_melting_seaice_sa_ct_ratio_poly,
	    (sa_arctic,ct_arctic,p_arctic, sa_seaice,t_seaice),
	    value,melting_seaice_sa_ct_ratio_poly);
	@gswtest gsw_melting_seaice_equilibrium_sa_ct_ratio,
	    (sa_arctic,p_arctic),value,
	    melting_seaice_equilibrium_sa_ct_ratio);
	@gswtest gsw_melting_seaice_equilibrium_sa_ct_ratio_poly,
	    (sa_arctic,p_arctic),value,
	    melting_seaice_equilibrium_sa_ct_ratio_poly);
	test_sub2(melting_seaice_into_seawater, (sa_arctic,ct_arctic,
	    p_arctic, w_seaice,sa_seaice,t_seaice,VALS2),
	    val1, melting_seaice_into_seawater_sa_final,
	    val2, melting_seaice_into_seawater_ct_final);
	test_sub3(seaice_fraction_to_freeze_seawater,(sa_arctic,ct_arctic,
	    p_arctic, sa_seaice,t_seaice,VALS3),
	    val1, seaice_fraction_to_freeze_seawater_sa_freeze,
	    val2, seaice_fraction_to_freeze_seawater_ct_freeze,
	    val3, seaice_fraction_to_freeze_seawater_w_ih);

end
=#


text:
function _bump(records::AbstractVector{R}, b::Int) where {T, R<:Record{T}}

    new_records = Vector{R}(undef, length(records))

    for (i, record) in enumerate(records)
        new_record  = Record{T}(record.chrom, record.first + b, record.last + b, record.value)
        new_records[i] = new_record
    end

    return new_records
end

_bump_forward(records::AbstractVector{<:Record}) = _bump(records, 1)
_bump_back(records::AbstractVector{<:Record}) = _bump(records, -1)

function _range(record::Record; right_open=true)

    pos_start = right_open ? record.first : record.first + 1
    pos_end = right_open ? record.last - 1 : record.last

    return pos_start : pos_end
end

function _range(records::AbstractVector{<:Record}; right_open=true)

    pos_start = _range(records[1], right_open=right_open)[1]
    pos_end = _range(records[end], right_open=right_open)[end]

    return  pos_start : pos_end
end

ext: jl


text:
using ModuleDocstrings
using Example   # test error on a non-devved package
using Pkg
using Test

@testset "ModuleDocstrings.jl" begin
    str = ModuleDocstrings.generate(ModuleDocstrings)
    @test occursin("ModuleDocstrings.generate", str)
    @test occursin("ModuleDocstrings.write", str)

    m = @eval Module() begin
        """
            foo1()

        `foo1` is pretty useful.
        """
        foo1() = 0

        """
        `foo2` doesn't show the signature.
        """
        foo2() = 0

        """
            foo3()

        `foo3` contains a [`$(string(@__MODULE__)).foo1`](@ref) that contains a period.
        """
        foo3()

        @__MODULE__
    end
    str = ModuleDocstrings.generate(m)
    @test occursin("- `Main.anonymous.foo1`: `foo1` is pretty useful.", str)
    @test occursin("- `Main.anonymous.foo2`: `foo2` doesn't show the signature.", str)
    @test occursin("- `Main.anonymous.foo3`: `foo3` contains a [`Main.anonymous.foo1`](@ref) that contains a period.", str)

    if Base.VERSION >= v"1.8.0-DEV.363"   # use strings in @test_throws; we don't care what type of error this is
        @test_throws "must be a writable package, but there is no corresponding file" ModuleDocstrings.write(m)
        @test_throws r"must be a writable package, but the path \".*\" is not writable" ModuleDocstrings.write(Example)
    else
        @test_throws Exception ModuleDocstrings.write(m)
        @test_throws Exception ModuleDocstrings.write(Example)
    end

    mktempdir() do pkgs
        push!(LOAD_PATH, pkgs)
        newpkgdir = joinpath(pkgs, "DevDummy")
        Pkg.generate(newpkgdir)
        open(joinpath(newpkgdir, "src", "DevDummy.jl"), "w") do io
            print(io,
"""
module DevDummy

\"\"\"
    greet()

Print a delightful greeting.
\"\"\"
greet() = print("Hello World!")

end # module
"""
            )
        end
        @eval using DevDummy
        ModuleDocstrings.write(DevDummy)
        str = read(joinpath(newpkgdir, "src", "DevDummy.jl"), String)
        @test occursin(
"""
\"\"\"
- `DevDummy.greet`: Print a delightful greeting.
\"\"\"
module DevDummy
""", str)
    end
end

max_stars_repo_name: JuliaDocs/ModuleDocstrings

max_issues_repo_name: JuliaDocs/ModuleDocstrings

max_forks_repo_name: JuliaDocs/ModuleDocstrings


text:
function sequence_diff(seq, step=1)
    return [seq[i+step]-seq[i] for i = 1:length(seq)-step]
end

function day01a(numbers)
    diffs = sequence_diff(numbers)
    sum(diffs .> 0)
end

function day01b(numbers)
    diffs = sequence_diff(numbers, 3)
    sum(diffs .> 0)
end

function day01(fpath)
    numbers = parseints(fpath)
    return (day01a(numbers), day01b(numbers))
end


text:
using JuMP
using Clp

using ASTInterpreter2

#
# All credits for this piece of software to Yin Zhang
#

function solve_chebyshev(A::Array{Float64,2},b::Array{Float64,1})
# Use a hyperplane representation of the polyhedron
# i.e. P = { x | Ax ≤ b }
# m = 4
#A = [ 2. 1 ; 2 -1 ; -1 2 ; -1 -2]
#b = ones(4)
(sm,sn) = size(A)

# Build JuMP model
m = Model(solver=ClpSolver())
@variable(m, r)
@variable(m, x[1:sn])
@objective(m, Max, r)
sA = sparse(A)
@constraint( m , sA * x + sqrt.(sum(sA.^2,2)) * r .<= b )
#@addConstraint(m, P[i=1:4], dot(A[i],x) + norm(A[i])*r <= b[i])

# Solve with any available LP solver
solve(m)

# Where is the center?
#print(getvalue(x))
return getvalue(x)

end

#%  MVE_RUN  Find the maximum volume ellipsoid of a polytope.
#%
#%     [f,E] = MVE_RUN(A, b) finds the maximum volume inscribed ellipsoid of
#%     the polytope {x: A*x <= b}. The polytope is assumed to be full-
#%     volume. The ellipse is returned as the pair (f,E) such that
#%         Ell = {E^(-1)*x + f: norm(x) <= 1}
#%     or equivalently as
#%         Ell = {x:  norm(E*(x-f)) <= 1},
#%     The matrix E is upper triangular.
#%
#%     NOTE: An ellipsoid can be represented as:
#%     (1) {x: (x-f)'*(E'*E)*(x-f) <= 1}  , or
#%     (2) {x: {E^(-1)*x + f, norm(x) <= 1}
#%
#%
#%     [f,E] = MVE_RUN(A, b, x0) finds the maximum volume inscribed
#%     ellipsoid using the starting point x0. It must be an interior point,
#%     i.e. b - A*x0 > 0.
#
#%--------------------------------------
#% Yin Zhang, Rice University, 07/29/02
#%--------------------------------------
#% Markus Uhr, ETH Zurich, 10/04/11
#%--------------------------------------
 # Thomas Liphardt, June 2018
 #--------------------------------------

function mve_run(A::Array{Float64,2},b::Array{Float64,1} ; x_internal=[] )
    tol = 1.e-8
    maxiter = 200

    x0 = NaN * ones(size(A,2))
    if(isempty(x_internal))
        x0 = solve_chebyshev(A,b)
    else
        x0 = x_internal
    end
    (f,E,msg,y,z,iter) = mve_solver( A , b , x0 ; maxiter=maxiter , tol=tol )
    return(f,E)
end

#function [x,E,msg,y,z,iter] = mve_solver(A,b,x0,maxiter,tol)
#  MVE_SOLVER  Driver for solving the maximum volume ellipsoid problem
#%
#%  See also: MVE_RUN
#
#%    {v:  v = x + E^(-1)*s, ||s|| <= 1}
#%  inscribing a full-dimensional polytope
#%          {v:  Av <= b}
#%  Input:  A, b --- defining the polytope
#%          x0 --- interior point (Ax0 < b)
#%  Output: x --- center of the ellipsoid
#%          E2 --- E'*E
#%--------------------------------------
#% Yin Zhang, Rice University, 07/29/02
#%--------------------------------------
#% Markus Uhr, ETH Zurich, 10/04/11
#%--------------------------------------
#% Thomas Liphardt, June 2018
#%--------------------------------------

function mve_solver(A_p::Array{Float64,2},b::Array{Float64,1},x0::Array{Float64,1}; maxiter::Int64=50 , tol::Float64=1.e-4 )
    (m, n) = size(A_p);
    bnrm = norm(b);

    #if ~exist('maxiter', 'var')
    #    maxiter = 50;
    #end;
    #if ~exist('tol', 'var')
    #    tol = 1.e-4;
    #end;

    minmu::Float64 = 1.e-8
    tau0::Float64 = .75

    bmAx::Array{Float64,1} = b - A_p*x0
    if any(bmAx .<= 0)
        error("x0 not interior")
    end

    A = sparse(1:m,1:m,1./bmAx)*A_p
    b = ones(m)

    x = zeros(n)
    y = ones(m)
    bmAx = b

    z::Array{Float64,1} = NaN * ones(n)

    R::Array{Float64,2} = NaN * ones(n,n)

    print("\n  Residuals:   Primal     Dual    Duality  logdet(E)\n");
    print("  --------------------------------------------------\n");

    msg = 0

    Adx::Array{Float64,1} = NaN * ones(n)# init Adx
    astep::Float64 = NaN # init astep

    iter::Int64 = 0

    #%----- loop starts -----
    for iter = 1:maxiter

        if (iter > 1)
            bmAx = bmAx .- (astep*Adx) # TODO check if this is the same..
        end

        Y = sparse(1:m,1:m,y)
        #E2 = inv(full(transpose(A)*Y*A));
        #Q = A*E2*A';
        furz = 7
        #R = chol( transpose(A) *Y*A)
        R = chol( Hermitian( transpose(A) *Y*A ) )
        Q = A*(R\( transpose(R) \ transpose(A) ))

        h = sqrt.(diag(Q))
        if (iter == 1)
            t = minimum(bmAx./h)
            y = y/t^2
            h = t*h
            z = bmAx-h
            z[z.<1.e-1] = 1.e-1
            Q = t^2*Q
            Y = Y/t^2
        end
        yz = y.*z
        yh = y.*h
        gap = sum(yz)/m
        rmu = minimum([.5; gap])*gap
        rmu = maximum([rmu;minmu])

        R1 = - transpose(A) * yh
        R2 = bmAx - h - z
        R3 = rmu - yz

        r1 = norm(R1,Inf)
        r2 = norm(R2,Inf)
        r3 = norm(R3,Inf)
        res = maximum([r1;r2;r3])
    #%     objval = log(det(E2))/2;
        #objval = full(-sum(log.(diag(R))))
        objval = (-sum(log.(diag(R))))

        @printf("  iter %3i  ", iter);
        #fprintf('%9.1e %9.1e %9.1e  %9.3e\n', r2,r1,r3,objval);
        @printf("%9.1e %9.1e %9.1e  %9.3e\n", r2,r1,r3,objval);
        if ( res < tol*(1+bnrm) && rmu <= minmu )
            #fprintf('  Converged!\n');
            x = x + x0
            msg=1
            break
        end

        #print("\nCHECK 01\n");

        YQ = Y*Q;
        YQQY = YQ.*YQ'
        y2h = 2*yh
        YA = Y*A
        G  = YQQY + sparse(1:m,1:m,max.(1.e-12,y2h.*z))
        T = G \ (sparse(1:m,1:m,h+z)*YA)
        ATP = (sparse(1:m,1:m,y2h)*T-YA)'

        #print("\nCHECK 02\n");

        R3Dy = R3./y;
        R23 = R2 - R3Dy;
        dx = (ATP*A)\(R1 + ATP*R23)
        Adx = A*dx

        dyDy = G\(y2h.*(Adx - R23))
        dy = y.*dyDy
        dz = R3Dy - z.*dyDy

        ax = -1/minimum([-Adx./bmAx; -.5])
        ay = -1/minimum([ dyDy; -.5])
        az = -1/minimum([dz./z; -.5])
        tau = maximum( [tau0; 1 - res])
        astep = tau*minimum([1;ax;ay;az])

        #print("\nCHECK 03\n");

        x = x + astep*dx
        y = y + astep*dy
        z = z + astep*dz
    end

    E = R

    return (x,E,msg,y,z,iter)
end

##


text:
# Generic code for discharge modeling

"""
DischargeModel is a subtype of StatsBase's RegressionModel.

Each should thus attempt to implement the following methods:

- coef(model)
- coeftable(model)
- confint(model,prob)
- deviance(model)
- fit(Type{Model},X,y,params...)
- fit(Type{Model},X,params...) :: fit using a concatenated data-response matrix
- loglikelihood(model)
- stderr(model)
- vcov(model)
- nobs(model)
- model_response(model)
- predict(model)
- predict(model,H) :: using the new design matrix H, predict the fitted values
- residuals(model)
- residuals(model,H,Q) :: using the new design matrix H, predict fitted values and
calculate the residuals from the new values

Some models will not be able to implement all of these easily.

We implement two helper functions

- `estfun(model,H,Q,range)` which fits a model to a stage and discharge record over
the range given
- `evalfun(model,H,Q,range)` which evaluates a model's performance over the range given
"""
abstract type DischargeModel <: RegressionModel end

function estfun!(model::DischargeModel,H::Matrix{Nullable{Float64}},Q::Vector{Float64},range)
    Ht = validate(H,range,model.M)
    Qt = validate(Q,range,model.M)
    fit!(model,Ht,Qt)
end

estfun!(model::DischargeModel,H::Matrix{Nullable{Float64}},Q::Vector{Float64}) = estfun!(model,H,Q,1:length(Q))

function estfun(model::DischargeModel,H::Matrix{Nullable{Float64}},Q::Vector{Float64},range)
    Ht = validate(H,range,model.M)
    Qt = validate(Q,range,model.M)
    fit(model,Ht,Qt)
end

estfun(model::DischargeModel,H::Matrix{Nullable{Float64}},Q::Vector{Float64}) = estfun(model,H,Q,1:length(Q))

function evalfun(model::DischargeModel,H::Matrix{Nullable{Float64}},Q::Vector{Float64},range)
    Ht = validate(H,range,model.M)
    Qt = validate(Q,range,model.M)
    sumabs2(residuals(model,Ht,Qt))
end

evalfun(model::DischargeModel,H::Matrix{Nullable{Float64}},Q::Vector{Float64}) = evalfun(model,H,Q,1:length(Q))

function evalmodel(model::DischargeModel,H::Matrix{Nullable{Float64}},range)
    Ht = validate(H,range,model.M)
    predict(model,Ht)
end

evalmodel(model::DischargeModel,H::Matrix{Nullable{Float64}},Q::Vector{Float64}) = evalmodel(model,H,Q,1:length(Q))

"""
This is  the one argument form of fitting a discharge model
"""
StatsBase.fit(M::DischargeModel, Y::Matrix{Float64}) = fit(M,Y[1:end-1,:],vec(Y[end,:]))

StatsBase.fit!(M::DischargeModel,Y::Matrix{Float64}) = fit!(M,Y[1:end-1,:],vec(Y[end,:]))

# Functions for fitting from a Discharge type

estfun!(M::DischargeModel,h::Stage,dd::Discharge,range) = estfun!(M,makelagmatrix(h),quantity(dd),range)
estfun!(M::DischargeModel,h::Stage,dd::Discharge) = estfun!(M,makelagmatrix(h),quantity(dd),1:length(dd))

estfun(M::DischargeModel,h::Stage,dd::Discharge,range) = estfun(M,makelagmatrix(h),quantity(dd),range)
estfun(M::DischargeModel,h::Stage,dd::Discharge) = estfun(M,makelagmatrix(h),quantity(dd),1:length(dd))

evalfun(M::DischargeModel,h::Stage,dd::Discharge,range) = evalfun(M,makelagmatrix(h),quantity(dd),range)
evalfun(M::DischargeModel,h::Stage,dd::Discharge) = evalfun(M,makelagmatrix(h),quantity(dd),1:length(dd))

evalmodel(M::DischargeModel,h::Stage,dd::Discharge,range) = evalmodel(M,makelagmatrix(h),range)
evalmodel(M::DischargeModel,h::Stage,dd::Discharge) = evalmodel(M,makelagmatrix(h),quantity(dd),1:length(dd))

# Add in all the possible models
const _models = ["lti",
                 "rlti",
                 "kmeans",
                 "volterra",
                 "threshold",
                 "boon"]
for m in _models
    include(joinpath("models",m*".jl"))
end


text:
module IO

# Types
import RIOPA: TagBase, DataSet
import OrderedCollections: LittleDict

abstract type IOTag <: TagBase end

function perform_step end

tagmap = LittleDict{String,IOTag}()

function add(key::String, tag::IOTag)
    tagmap[key] = tag
end

function get_tag(key::String)
    try
        return tagmap[key]
    catch
        println("Invalid IO backend: ", key)
        rethrow()
    end
end

struct DefaultIOTag <: IOTag end

get_tag(::Nothing) = DefaultIOTag()

function perform_step(::DefaultIOTag, ::DataSet)
    # error ?
end

end


text:
using ITensors
using ITensorInfiniteMPS

##############################################################################
# VUMPS parameters
#

maxdim = 100 # Maximum bond dimension
cutoff = 1e-8 # Singular value cutoff when increasing the bond dimension
max_vumps_iters = 100 # Maximum number of iterations of the VUMPS algorithm at each bond dimension
vumps_tol = 1e-6
outer_iters = 8 # Number of times to increase the bond dimension

##############################################################################
# CODE BELOW HERE DOES NOT NEED TO BE MODIFIED
#

N = 2 # Number of sites in the unit cell

heisenberg_space_shift(q̃nf, q̃sz) = [QN("Sz", 1 - q̃sz) => 1, QN("Sz", -1 - q̃sz) => 1]

heisenberg_space = fill(heisenberg_space_shift(1, 0), N)
s = infsiteinds("S=1/2", N; space=heisenberg_space)
initstate(n) = isodd(n) ? "↑" : "↓"
ψ = InfMPS(s, initstate)

model = Model("heisenberg")

# Form the Hamiltonian
H = InfiniteSum{MPO}(model, s)

# Check translational invariance
@show norm(contract(ψ.AL[1:N]..., ψ.C[N]) - contract(ψ.C[0], ψ.AR[1:N]...))

vumps_kwargs = (tol=vumps_tol, maxiter=max_vumps_iters, eigsolve_tol=(x -> x / 1000))
subspace_expansion_kwargs = (cutoff=cutoff, maxdim=maxdim)
ψ = vumps(H, ψ; vumps_kwargs...)

# Alternate steps of running VUMPS and increasing the bond dimension
for _ in 1:outer_iters
  println("\nIncrease bond dimension")
  global ψ = subspace_expansion(ψ, H; subspace_expansion_kwargs...)
  println("Run VUMPS with new bond dimension")
  global ψ = vumps(H, ψ; vumps_kwargs...)
end

# Check translational invariance
@show norm(contract(ψ.AL[1:N]..., ψ.C[N]) - contract(ψ.C[0], ψ.AR[1:N]...))

function ITensors.expect(ψ::InfiniteCanonicalMPS, o, n)
  return (noprime(ψ.AL[n] * ψ.C[n] * op(o, s[n])) * dag(ψ.AL[n] * ψ.C[n]))[]
end

function expect_two_site(ψ::InfiniteCanonicalMPS, h::ITensor, n1n2)
  n1, n2 = n1n2
  ϕ = ψ.AL[n1] * ψ.AL[n2] * ψ.C[n2]
  return (noprime(ϕ * h) * dag(ϕ))[]
end

Sz = [expect(ψ, "Sz", n) for n in 1:N]

bs = [(1, 2), (2, 3)]
energy_infinite = map(b -> expect_two_site(ψ, H[b], b), bs)

energy_exact = reference(model, Observable("energy"))

@show energy_infinite
@show energy_exact
@show Sz

#
# Compare to DMRG
#

Nfinite = 100
sfinite = siteinds("S=1/2", Nfinite; conserve_szparity=true)
Hfinite = MPO(model, sfinite)
ψfinite = randomMPS(sfinite, initstate; linkdims=10)
@show flux(ψfinite)
sweeps = Sweeps(15)
setmaxdim!(sweeps, maxdim)
setcutoff!(sweeps, cutoff)
energy_finite_total, ψfinite = dmrg(Hfinite, ψfinite, sweeps)
@show energy_finite_total / Nfinite

energy_exact_finite = reference(model, Observable("energy"); N=Nfinite)
@show energy_exact_finite

function ITensors.expect(ψ, o)
  return (noprime(ψ * op(o, filterinds(ψ, "Site")...)) * dag(ψ))[]
end

nfinite = Nfinite ÷ 2
orthogonalize!(ψfinite, nfinite)
Sz1_finite = expect(ψfinite[nfinite], "Sz")
orthogonalize!(ψfinite, nfinite + 1)
Sz2_finite = expect(ψfinite[nfinite + 1], "Sz")

@show Sz1_finite, Sz2_finite


text:
"""
Download the C STREAM benchmark source code from https://www.cs.virginia.edu/stream into a new folder "stream".
"""
function download_original_STREAM()
    println("- Creating folder \"stream\"")
    mkdir("stream")
    println("- Downloading C STREAM benchmark")
    Downloads.download(
        "https://www.cs.virginia.edu/stream/FTP/Code/stream.c", "stream/stream.c"
    )
    Downloads.download(
        "https://www.cs.virginia.edu/stream/FTP/Code/mysecond.c", "stream/mysecond.c"
    )
    println("- Done.")
    return nothing
end

_default_compiler() = Sys.islinux() ? (:gcc) : (:clang)

"""
    compile_original_STREAM(; compiler=_default_compiler(), multithreading=false)

Compile the source code of the C STREAM benchmark ("stream/stream.c") into a binary "stream/stream".
"""
function compile_original_STREAM(; compiler=_default_compiler(), multithreading=false)
    if !isfile("stream/stream.c")
        @warn(
            "Couldn't find source code \"stream/stream.c\". Have you run STREAMBenchmark.download_original_STREAM()?"
        )
        return nothing
    end

    println("- Trying to compile \"stream.c\" using $(string(compiler))")
    if compiler == :clang
        options = [
            "-Ofast", "-march=native", "-DSTREAM_ARRAY_SIZE=$(default_vector_length())"
        ] # "-DNTIMES=30"
    elseif compiler == :(gcc - 10) || compiler == :gcc
        options = ["-O3", "-DSTREAM_ARRAY_SIZE=$(default_vector_length())"]
    else
        error("Unknown compiler option: $compiler.")
    end
    multithreading && push!(options, "-fopenmp")
    println("  Using options: $(join(options, " "))")
    cd("stream") do
        run(`$compiler $options stream.c -o stream`)
    end
    println("- Done.")
    return nothing
end

"""
Execute the binary of the C STREAM benchmark (i.e. "stream/stream").
"""
function execute_original_STREAM()
    if !isfile("stream/stream")
        @warn(
            "Couldn't find executable \"stream/stream\". Have you run STREAMBenchmark.compile_original_STREAM()?"
        )
    else
        run(`stream/stream`)
    end
    return nothing
end


text:
# push!(LOAD_PATH, "../src/")
using Documenter, NumericalEFT

makedocs(
    modules=[NumericalEFT],
    sitename="NumericalEFT.jl",
    repo="https://github.com/numericalEFT/NumericalEFT.jl/blob/{commit}{path}#{line}",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://numericaleft.github.io/NumericalEFT.jl",
        assets=String[]
    ),
    pages=[
        "Home" => "index.md",
        "Module ReadMe" => Any[
            "Lehmann"=>"readme/Lehmann.md",
            "FeynmanDiagram"=>"readme/FeynmanDiagram.md",
            "MCIntegration"=>"readme/MCIntegration.md",
            "CompositeGrids"=>"readme/CompositeGrids.md",
            "GreenFunc"=>"readme/GreenFunc.md",
            "Atom"=>"readme/Atom.md",
        ],
        "Manual" => Any[
            "Discrete Lehmann Representation"=>"man/DLR.md",
            "Lehmann representation convention"=>"man/kernel.md",
            "Monte Carlo integrator"=>"man/MC.md",
            "Important Sampling"=>"man/important_sampling.md",
        ],
        "API reference" => Any[
            "lib/Lehmann.md",
            "lib/Feynmandiagram.md",
            "lib/MCintegration.md",
            "lib/compositegrids.md",
            "lib/greenfunc.md",
            "lib/atom.md",
            "lib/utility.md",
            "lib/fastmath.md",
        ]
    ])

deploydocs(repo="github.com/numericalEFT/NumericalEFT.jl.git")


text:
using Flux, Flux.Data.MNIST, Statistics, BSON, StatsBase, Plots; pyplot()
using Flux: onecold

model= Chain(Conv((5, 5), 1=>8, relu), MaxPool((2,2)),
             Conv((3, 3), 8=>16, relu), MaxPool((2,2)),
                flatten, Dense(400, 10), softmax)

BSON.@load "../data/mnistConv.bson" modelParams
Flux.loadparams!(model, modelParams)

function predictor(img)
    whcn = ones(Float32,28,28, 1, 1)
    whcn[:,:,1,1] = Float32.(img)
    onecold(model(whcn),0:9)[1]
end

testLabels = Flux.Data.MNIST.labels(:test)
testImages = Flux.Data.MNIST.images(:test)
nTest = length(testLabels)

iC, iR = 0, 0
nCorrect = 0
goodExamples = zeros(Int,10)
badExamples = zeros(Int,10)
predictedBad = zeros(Int,10)
for i in 1:nTest
    prediction = predictor(testImages[i])
    trueLabel = testLabels[i]
    predictionIsCorrect = (prediction == trueLabel)
    global nCorrect += predictionIsCorrect
    global iC; global iR
    if predictionIsCorrect && trueLabel == iC
        goodExamples[iC+1] = i
        iC += 1
    end
    if !predictionIsCorrect && trueLabel == iR
        badExamples[iR+1] = i
        predictedBad[iR+1] = prediction
        iR += 1
    end
end

println("Percentage correctly classified: ", 100*nCorrect/nTest)

default(yflip = true, size = (1000,300),
        legend=false,color = :Greys,ticks=false)
p1 = heatmap(hcat(float.(testImages[goodExamples])...))
p2 = heatmap(hcat(float.(testImages[badExamples])...))
for i in 1:10
    annotate!(28i-3,25,text("$(predictedBad[i])",18))
end
plot(p1,p2,layout=(2,1))

max_stars_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook

max_issues_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook

max_forks_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook


text:
using Test

using Distributions, LinearAlgebra, Statistics
using EnKF

@testset "Additive Inflation" begin

T = AdditiveInflation(10)

@test size(T)==(10,)

@test length(T)==10

@test mean(T)== zeros(10)

A = MvNormal(zeros(10), 1.05*ones(10))

T.α = A

@test var(T) == var(A)

@test var(T) == 1.05^2*ones(10)

end

@testset "Multiplicative Inflation" begin

T = MultiplicativeInflation(10)

@test length(T)==10

@test T.β == 1.0

T.β = 1.05

@test T.β == 1.05

end

@testset "MultiAdditive Inflation" begin

T = MultiAdditiveInflation(10)

@test size(T)== (10,)

@test length(T)==10

@test T.β == 1.0

# @test T.α == MvNormal(zeros(10), I)

@test mean(T) == zeros(10)

@test var(T) ==  ones(10)

A = MvNormal(zeros(10), 1.05*ones(10))

T.β = 1.05

T.α = A

@test T.β == 1.05

@test mean(T) == zeros(10)

@test var(T) == 1.05^2*ones(10)

A = MvNormal(zeros(10), 1.01*ones(10))
T = MultiAdditiveInflation(10, 1.01, A)

@test T.β == 1.01

@test mean(T) == zeros(10)

@test var(T) == 1.01^2*ones(10)

end

@testset "State" begin

end

max_stars_repo_name: mleprovost/EnKF

max_issues_repo_name: mleprovost/EnKF

max_forks_repo_name: mleprovost/EnKF


text:
"""
Code for creating, loading and maniuplating line lists and masks.

Author: Eric Ford
Created: August 2020
"""

using DataFrames, CSV

abstract type AbstractCalcChunkWidth end

""" Functor to return a constant scale factor for chunk widths (regardless of wavelength passed)"""
struct ChunkWidthFixedΔlnλ <: AbstractCalcChunkWidth
   Δlnλ::Float64
end
(f::ChunkWidthFixedΔlnλ)(λ::Real) = f.Δlnλ

"""
   Functor to return a scale factor for chunk widths that depends on the chunk's central wavelength.

# TODO: Replace with something useful, e.g., uses actual PSF behavior as function of wavelength
"""
struct ChunkWidthFuncOfλ <: AbstractCalcChunkWidth
   Δlnλ::Float64
end

function (f::ChunkWidthFuncOfλ)(λ::Real; chunk_size_factor::Real = default_chunk_size_factor,
                                line_width::Real = default_line_width_mps, min_chunk_Δv::Real = default_min_chunk_Δv )
    chunk_half_width = max(chunk_size_factor*line_width, min_chunk_Δv)/speed_of_light_mps
    psf_width = λ*1e-6*(1+(λ-6000)/60000)   # TODO: Repalce, just some random number for demo purposes
    Δlnλ = sqrt(chunk_half_width^2+psf_width^2)
    return Δlnλ
end

"""
    Read mask in ESPRESSO csv format.
ESPRESSO format: lambda and weight.
Warning: ESPRESSO masks don't provide line depth and sometimes include one entry for a blend of lines.
"""
function read_mask_espresso(fn::String; calcΔ::CCWT = default_calc_chunk_width) where { CCWT<:AbstractCalcChunkWidth }
    local df = CSV.read(fn,DataFrame,threaded=false,header=["lambda","weight"],delim=' ',ignorerepeated=true)
    df[!,:lambda] .= λ_air_to_vac.(df[!,:lambda])
    local Δ = calcΔ.(df[!,:lambda])
    @assert all(Δ.>0)
    df[!,:lambda_lo] = df[!,:lambda]./(1 .+ Δ)
    df[!,:lambda_hi] = df[!,:lambda].*(1 .+ Δ)
    df[!,:depth] = df[!,:weight]  # TODO: Decide out what we want to do about tracking depths and weights sepoarately
    return df
end

""" Read mask in VALD csv format.
   VALD format: lambda_lo, lambdaa_hi and depth.
"""
function read_mask_vald(fn::String; calcΔ::CCWT = default_calc_chunk_width) where { CCWT<:AbstractCalcChunkWidth }
    local df = CSV.read(fn,DataFrame,threaded=false,header=["lambda_lo","lambda_hi","depth"])
    df[!,:lambda_lo] .= λ_air_to_vac.(df[!,:lambda_lo])
    df[!,:lambda_hi] .= λ_air_to_vac.(df[!,:lambda_hi])
    df[!,:lambda] = sqrt.(df[!,:lambda_lo].*df[!,:lambda_hi])
    local Δ = calcΔ.(df[!,:lambda])
    @assert all(Δ.>0)
    df[!,:lambda_lo] = df[!,:lambda]./(1 .+ Δ)
    df[!,:lambda_hi] = df[!,:lambda].*(1 .+ Δ)
    df[!,:weight] = df[!,:depth] # TODO: Decide out what we want to do about tracking depths and weights sepoarately
    return df
end

""" Return indices of any chunks in df that have overlapping lambda_hi[i] and lambda_lo[i+1].  """
function find_overlapping_chunks(df::DataFrame; verbose::Bool = true)
    @assert hasproperty(df,:lambda_lo)
    @assert hasproperty(df,:lambda_hi)
   if ! any(df.lambda_hi[1:end-1] .>= df.lambda_lo[2:end])   # Is there any point to keeping the if return early bit?
       return
   end
   idx_overlap = findall(df.lambda_hi[1:end-1] .>= df.lambda_lo[2:end])
   if verbose
       println("# Number of overlapping chunks: ",length(idx_overlap))
   end
   return idx_overlap
end

""" Return DataFrame with specifications for each chunk which will contain one or more lines.
    Input:  line_list a DataFrame with:
    -  lambda_lo, lambda_hi, lambda, depth
    Output:  DataFrame with
    - lambda_lo & lambda_hi: boundaries for chunk
    - lambda & line_depths: arrays with info about each line
"""
function merge_chunks(line_list::DataFrame)
    @assert hasproperty(line_list,:lambda_lo)
    @assert hasproperty(line_list,:lambda_hi)
    @assert hasproperty(line_list,:lambda)
    #@assert hasproperty(line_list,:depth)
    @assert hasproperty(line_list,:weight)
    chunk_list_df = DataFrame(:lambda_lo=>Float64[],:lambda_hi=>Float64[],
                                :lambda=>Array{Float64,1}[],:weight=>Array{Float64,1}[])
    num_lines = size(line_list,1)
    @assert num_lines >= 2
    lambda_lo_last = line_list[1,:lambda_lo]
    lambda_hi_last = line_list[1,:lambda_hi]
    lambda = [line_list[1,:lambda]]
    line_weights = [line_list[1,:weight]]
    for i in 2:num_lines
        lambda_lo = line_list[i,:lambda_lo]
        lambda_hi = line_list[i,:lambda_hi]
        if lambda_lo>lambda_hi_last
            push!(chunk_list_df, (lambda_lo_last, lambda_hi_last, lambda, line_weights))
            (lambda_lo_last, lambda_hi_last) = (lambda_lo, lambda_hi)
            lambda = [line_list[i,:lambda]]
            line_weights = [line_list[i,:weight]]
        else
            lambda_hi_last = lambda_hi
            push!(lambda,line_list[i,:lambda])
            push!(line_weights,line_list[i,:weight])
        end
    end
    if chunk_list_df[end,:lambda_hi] != lambda_hi_last
        #push!(chunk_list_df, (lambda_lo_last, lambda_hi_last))
        push!(chunk_list_df, (lambda_lo_last, lambda_hi_last, lambda, line_weights))
    end
    return chunk_list_df
end

max_stars_repo_name: RvSpectML/EchelleInstruments

max_issues_repo_name: RvSpectML/EchelleInstruments

max_forks_repo_name: RvSpectML/EchelleInstruments


text:
using Chemfiles
using Test

TESTS = [
    "atom.jl",
    "residue.jl",
    "topology.jl",
    "cell.jl",
    "frame.jl",
    "property.jl",
    "trajectory.jl",
    "selection.jl",
    "misc.jl",
]

include("utils.jl")

function main()
    @testset "Version" begin
        @test split(Chemfiles.version(), '-')[1] == "0.10.1"
    end
    root = dirname(@__FILE__)
    for test in TESTS
        include(test)
    end
end

main()


text:
function radius_correction(obj::VisibilityTrigger, arg0::jdouble)
    return jcall(obj, "radiusCorrection", jdouble, (jdouble,), arg0)
end

function value_of(::Type{VisibilityTrigger}, arg0::JString)
    return jcall(VisibilityTrigger, "valueOf", VisibilityTrigger, (JString,), arg0)
end

function values(::Type{VisibilityTrigger})
    return jcall(VisibilityTrigger, "values", Vector{VisibilityTrigger}, ())
end


text:
using CayleyMengerDeterminant
import InverseFunctions
import Static: StaticInt
import StaticArrays: Dynamic
using Test

@testset "CayleyMengerDeterminant.jl" begin
    InverseFunctions.test_inverse.(
        binomial2,
        [1, 2, 3, 4, 5, 6, Dynamic(), StaticInt(2), StaticInt(3)],
        compare = isequal,
    )
    InverseFunctions.test_inverse.(
        inverse_binomial2,
        [0, 1, 3, 6, 10, 15, Dynamic(), StaticInt(1), StaticInt(3)],
        compare = isequal,
    )

    @testset "index_triangular_nodiag" begin
        N = 100
        v = zeros(Int, binomial(N, 2))
        for ixA = 1:N
            for ixB = 1:(ixA-1)
                v[CayleyMengerDeterminant.index_triangular_nodiag(ixA, ixB)] += 1
            end
        end
        for k in v
            @test k == 1
        end
    end

    @testset "CayleyMengerDistanceMatrix" begin
        m0 = CayleyMengerDistanceMatrix(())
        @test m0.simplex_dimensions == 0
        @test size(m0.square_distances) == (0,)

        m1 = CayleyMengerDistanceMatrix((0,), (1,))
        @test m1.simplex_dimensions == 1
        @test size(m1.square_distances) == (1,)
        @test m1.square_distances == [1]
        @test m1 == CayleyMengerDistanceMatrix((1,), (2,))
        @test m1 == CayleyMengerDistanceMatrix((1,), (0,))

        m3 = CayleyMengerDistanceMatrix((0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1))
        @test m3.simplex_dimensions == 3
        @test size(m3.square_distances) == (6,)
        @test m3.square_distances == [1, 1, 2, 1, 2, 2]
        @test m3 == CayleyMengerDistanceMatrix((1, 1, 1), (1, 1, 0), (0, 1, 1), (1, 0, 1))
        @test m3 == CayleyMengerDistanceMatrix([1 1 1; 1 1 0; 0 1 1; 1 0 1])
    end

    @testset "simplex_volume" begin
        @test simplex_volume(()) == false
        @test simplex_volume((), distance_type = Int) == 0

        @test simplex_volume((0,), (1,)) == 1
        @test simplex_volume((1,), (2,)) == 1
        @test simplex_volume((1,), (0,)) == 1
        @test simplex_volume((2,), (0,)) == 2
        @test simplex_volume((-1,), (1,)) == 2

        @test simplex_volume((0, 0), (1, 0), (0, 1)) == 1 / 2
        @test simplex_volume((0, 0), (0, 2), (-2, 0)) == 2
        @test simplex_volume((0, 0), (0, 2), (-2, 0), distance_type = Int) == 2

        @test simplex_volume((0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)) == 1 / 6
        @test simplex_volume((1, 1, 1), (1, 1, 0), (0, 1, 1), (1, 0, 1)) == 1 / 6
        @test simplex_volume((1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1)) == 1 / 6
        @test simplex_volume((0, 0, 0), (0, 1, 2), (2, 1, 0), (0, 2, 0)) == 4 / 3

        @test simplex_volume([0 0 0; 1 0 0; 0 1 0; 0 0 1]) == 1 / 6
    end
end


text:
const _country_data = Dict(
    :BV => (Country{:BV},"Bouvet Island",074,[:NOK],"47","nothing","AN",true,"Americas","Latin America and the Caribbean"),
    :OM => (Country{:OM},"Oman",512,[:OMR],"968","Muscat","AS",true,"Asia","Western Asia"),
    :TF => (Country{:TF},"French Southern Territories",260,[:EUR],"262","Port-aux-Francais","AN",true,"Africa","Sub-Saharan Africa"),
    :NO => (Country{:NO},"Norway",578,[:NOK],"47","Oslo","EU",false,"Europe","Northern Europe"),
    :DO => (Country{:DO},"Dominican Republic",214,[:DOP],"1-809,1-829,1-849","Santo Domingo","NA",true,"Americas","Latin America and the Caribbean"),
    :SR => (Country{:SR},"Suriname",740,[:SRD],"597","Paramaribo","SA",true,"Americas","Latin America and the Caribbean"),
    :BS => (Country{:BS},"Bahamas",044,[:BSD],"1-242","Nassau","NA",true,"Americas","Latin America and the Caribbean"),
    :NP => (Country{:NP},"Nepal",524,[:NPR],"977","Kathmandu","AS",true,"Asia","Southern Asia"),
    :HM => (Country{:HM},"Heard Island and McDonald Islands",334,[:AUD],"672","nothing","AN",false,"Oceania","Australia and New Zealand"),
    :SJ => (Country{:SJ},"Svalbard and Jan Mayen Islands",744,[:NOK],"47","Longyearbyen","EU",false,"Europe","Northern Europe"),
    :EG => (Country{:EG},"Egypt",818,[:EGP],"20","Cairo","AF",true,"Africa","Northern Africa"),
    :EE => (Country{:EE},"Estonia",233,[:EUR],"372","Tallinn","EU",false,"Europe","Northern Europe"),
    :CU => (Country{:CU},"Cuba",192,[:CUP, :CUC],"53","Havana","NA",true,"Americas","Latin America and the Caribbean"),
    :US => (Country{:US},"United States of America",840,[:USD],"1","Washington","NA",false,"Americas","Northern America"),
    :LU => (Country{:LU},"Luxembourg",442,[:EUR],"352","Luxembourg","EU",false,"Europe","Western Europe"),
    :CM => (Country{:CM},"Cameroon",120,[:XAF],"237","Yaounde","AF",true,"Africa","Sub-Saharan Africa"),
    :AE => (Country{:AE},"United Arab Emirates",784,[:AED],"971","Abu Dhabi","AS",true,"Asia","Western Asia"),
    :FR => (Country{:FR},"France",250,[:EUR],"33","Paris","EU",false,"Europe","Western Europe"),
    :FI => (Country{:FI},"Finland",246,[:EUR],"358","Helsinki","EU",false,"Europe","Northern Europe"),
    :MQ => (Country{:MQ},"Martinique",474,[:EUR],"596","Fort-de-France","NA",true,"Americas","Latin America and the Caribbean"),
    :VG => (Country{:VG},"British Virgin Islands",092,[:USD],"1-284","Road Town","NA",true,"Americas","Latin America and the Caribbean"),
    :JP => (Country{:JP},"Japan",392,[:JPY],"81","Tokyo","AS",false,"Asia","Eastern Asia"),
    :TG => (Country{:TG},"Togo",768,[:XOF],"228","Lome","AF",true,"Africa","Sub-Saharan Africa"),
    :GW => (Country{:GW},"Guinea-Bissau",624,[:XOF],"245","Bissau","AF",true,"Africa","Sub-Saharan Africa"),
    :NF => (Country{:NF},"Norfolk Island",574,[:AUD],"672","Kingston","OC",false,"Oceania","Australia and New Zealand"),
    :IE => (Country{:IE},"Ireland",372,[:EUR],"353","Dublin","EU",false,"Europe","Northern Europe"),
    :TV => (Country{:TV},"Tuvalu",798,[:AUD],"688","Funafuti","OC",true,"Oceania","Polynesia"),
    :MX => (Country{:MX},"Mexico",484,[:MXN],"52","Mexico City","NA",true,"Americas","Latin America and the Caribbean"),
    :GY => (Country{:GY},"Guyana",328,[:GYD],"592","Georgetown","SA",true,"Americas","Latin America and the Caribbean"),
    :CA => (Country{:CA},"Canada",124,[:CAD],"1","Ottawa","NA",false,"Americas","Northern America"),
    :AD => (Country{:AD},"Andorra",020,[:EUR],"376","Andorra la Vella","EU",false,"Europe","Southern Europe"),
    :MF => (Country{:MF},"Saint Martin (French Part)",663,[:EUR],"590","Marigot","NA",true,"Americas","Latin America and the Caribbean"),
    :VE => (Country{:VE},"Venezuela (Bolivarian Republic of)",862,[:VEF],"58","Caracas","SA",true,"Americas","Latin America and the Caribbean"),
    :KN => (Country{:KN},"Saint Kitts and Nevis",659,[:XCD],"1-869","Basseterre","NA",true,"Americas","Latin America and the Caribbean"),
    :SD => (Country{:SD},"Sudan",729,[:SDG],"249","Khartoum","AF",true,"Africa","Northern Africa"),
    :GU => (Country{:GU},"Guam",316,[:USD],"1-671","Hagatna","OC",true,"Oceania","Micronesia"),
    :NE => (Country{:NE},"Niger",562,[:XOF],"227","Niamey","AF",true,"Africa","Sub-Saharan Africa"),
    :TM => (Country{:TM},"Turkmenistan",795,[:TMT],"993","Ashgabat","AS",true,"Asia","Central Asia"),
    :BN => (Country{:BN},"Brunei Darussalam",096,[:BND],"673","Bandar Seri Begawan","AS",true,"Asia","South-eastern Asia"),
    :KZ => (Country{:KZ},"Kazakhstan",398,[:KZT],"7","Astana","AS",true,"Asia","Central Asia"),
    :CI => (Country{:CI},"Côte d'Ivoire",384,[:XOF],"225","Yamoussoukro","AF",true,"Africa","Sub-Saharan Africa"),
    :SX => (Country{:SX},"Sint Maarten (Dutch part)",534,[:ANG],"1-721","Philipsburg","NA",true,"Americas","Latin America and the Caribbean"),
    :CO => (Country{:CO},"Colombia",170,[:COP],"57","Bogota","SA",true,"Americas","Latin America and the Caribbean"),
    :QA => (Country{:QA},"Qatar",634,[:QAR],"974","Doha","AS",true,"Asia","Western Asia"),
    :PG => (Country{:PG},"Papua New Guinea",598,[:PGK],"675","Port Moresby","OC",true,"Oceania","Melanesia"),
    :LV => (Country{:LV},"Latvia",428,[:EUR],"371","Riga","EU",false,"Europe","Northern Europe"),
    :UY => (Country{:UY},"Uruguay",858,[:UYU],"598","Montevideo","SA",true,"Americas","Latin America and the Caribbean"),
    :RO => (Country{:RO},"Romania",642,[:RON],"40","Bucharest","EU",false,"Europe","Eastern Europe"),
    :IM => (Country{:IM},"Isle of Man",833,[:GBP],"44","Douglas","EU",false,"Europe","Northern Europe"),
    :VA => (Country{:VA},"Holy See",336,[:EUR],"39-06","Vatican City","EU",false,"Europe","Southern Europe"),
    :PA => (Country{:PA},"Panama",591,[:PAB, :USD],"507","Panama City","NA",true,"Americas","Latin America and the Caribbean"),
    :BI => (Country{:BI},"Burundi",108,[:BIF],"257","Bujumbura","AF",true,"Africa","Sub-Saharan Africa"),
    :CC => (Country{:CC},"Cocos (Keeling) Islands",166,[:AUD],"61","West Island","AS",false,"Oceania","Australia and New Zealand"),
    :SA => (Country{:SA},"Saudi Arabia",682,[:SAR],"966","Riyadh","AS",true,"Asia","Western Asia"),
    :PF => (Country{:PF},"French Polynesia",258,[:XPF],"689","Papeete","OC",true,"Oceania","Polynesia"),
    :VU => (Country{:VU},"Vanuatu",548,[:VUV],"678","Port Vila","OC",true,"Oceania","Melanesia"),
    :YT => (Country{:YT},"Mayotte",175,[:EUR],"262","Mamoudzou","AF",true,"Africa","Sub-Saharan Africa"),
    :AU => (Country{:AU},"Australia",036,[:AUD],"61","Canberra","OC",false,"Oceania","Australia and New Zealand"),
    :TR => (Country{:TR},"Turkey",792,[:TRY],"90","Ankara","AS",true,"Asia","Western Asia"),
    :WS => (Country{:WS},"Samoa",882,[:WST],"685","Apia","OC",true,"Oceania","Polynesia"),
    :GB => (Country{:GB},"United Kingdom of Great Britain and Northern Ireland",826,[:GBP],"44","London","EU",false,"Europe","Northern Europe"),
    :GN => (Country{:GN},"Guinea",324,[:GNF],"224","Conakry","AF",true,"Africa","Sub-Saharan Africa"),
    :GT => (Country{:GT},"Guatemala",320,[:GTQ],"502","Guatemala City","NA",true,"Americas","Latin America and the Caribbean"),
    :UA => (Country{:UA},"Ukraine",804,[:UAH],"380","Kiev","EU",false,"Europe","Eastern Europe"),
    :GA => (Country{:GA},"Gabon",266,[:XAF],"241","Libreville","AF",true,"Africa","Sub-Saharan Africa"),
    :BZ => (Country{:BZ},"Belize",084,[:BZD],"501","Belmopan","NA",true,"Americas","Latin America and the Caribbean"),
    :MS => (Country{:MS},"Montserrat",500,[:XCD],"1-664","Plymouth","NA",true,"Americas","Latin America and the Caribbean"),
    :BA => (Country{:BA},"Bosnia and Herzegovina",070,[:BAM],"387","Sarajevo","EU",false,"Europe","Southern Europe"),
    :KP => (Country{:KP},"Democratic People's Republic of Korea",408,[:KPW],"850","Pyongyang","AS",true,"Asia","Eastern Asia"),
    :SS => (Country{:SS},"South Sudan",728,[:SSP],"211","Juba","AF",true,"Africa","Sub-Saharan Africa"),
    :PL => (Country{:PL},"Poland",616,[:PLN],"48","Warsaw","EU",false,"Europe","Eastern Europe"),
    :KI => (Country{:KI},"Kiribati",296,[:AUD],"686","Tarawa","OC",true,"Oceania","Micronesia"),
    :PR => (Country{:PR},"Puerto Rico",630,[:USD],"1","San Juan","NA",true,"Americas","Latin America and the Caribbean"),
    :HR => (Country{:HR},"Croatia",191,[:HRK],"385","Zagreb","EU",false,"Europe","Southern Europe"),
    :TT => (Country{:TT},"Trinidad and Tobago",780,[:TTD],"1-868","Port of Spain","NA",true,"Americas","Latin America and the Caribbean"),
    :PE => (Country{:PE},"Peru",604,[:PEN],"51","Lima","SA",true,"Americas","Latin America and the Caribbean"),
    :MR => (Country{:MR},"Mauritania",478,[:MRO],"222","Nouakchott","AF",true,"Africa","Sub-Saharan Africa"),
    :CZ => (Country{:CZ},"Czechia",203,[:CZK],"420","Prague","EU",false,"Europe","Eastern Europe"),
    :AG => (Country{:AG},"Antigua and Barbuda",028,[:XCD],"1-268","St. John's","NA",true,"Americas","Latin America and the Caribbean"),
    :BD => (Country{:BD},"Bangladesh",050,[:BDT],"880","Dhaka","AS",true,"Asia","Southern Asia"),
    :MH => (Country{:MH},"Marshall Islands",584,[:USD],"692","Majuro","OC",true,"Oceania","Micronesia"),
    :MT => (Country{:MT},"Malta",470,[:EUR],"356","Valletta","EU",false,"Europe","Southern Europe"),
    :BT => (Country{:BT},"Bhutan",064,[:INR, :BTN],"975","Thimphu","AS",true,"Asia","Southern Asia"),
    :SI => (Country{:SI},"Slovenia",705,[:EUR],"386","Ljubljana","EU",false,"Europe","Southern Europe"),
    :AS => (Country{:AS},"American Samoa",016,[:USD],"1-684","Pago Pago","OC",true,"Oceania","Polynesia"),
    :MG => (Country{:MG},"Madagascar",450,[:MGA],"261","Antananarivo","AF",true,"Africa","Sub-Saharan Africa"),
    :MC => (Country{:MC},"Monaco",492,[:EUR],"377","Monaco","EU",false,"Europe","Western Europe"),
    :FK => (Country{:FK},"Falkland Islands (Malvinas)",238,Symbol[],"500","Stanley","SA",true,"Americas","Latin America and the Caribbean"),
    :IR => (Country{:IR},"Iran (Islamic Republic of)",364,[:IRR],"98","Tehran","AS",true,"Asia","Southern Asia"),
    :TZ => (Country{:TZ},"United Republic of Tanzania",834,[:TZS],"255","Dodoma","AF",true,"Africa","Sub-Saharan Africa"),
    :BY => (Country{:BY},"Belarus",112,[:BYN],"375","Minsk","EU",false,"Europe","Eastern Europe"),
    :LC => (Country{:LC},"Saint Lucia",662,[:XCD],"1-758","Castries","NA",true,"Americas","Latin America and the Caribbean"),
    :IQ => (Country{:IQ},"Iraq",368,[:IQD],"964","Baghdad","AS",true,"Asia","Western Asia"),
    :FO => (Country{:FO},"Faroe Islands",234,[:DKK],"298","Torshavn","EU",false,"Europe","Northern Europe"),
    :IS => (Country{:IS},"Iceland",352,[:ISK],"354","Reykjavik","EU",false,"Europe","Northern Europe"),
    :BO => (Country{:BO},"Bolivia (Plurinational State of)",068,[:BOB],"591","Sucre","SA",true,"Americas","Latin America and the Caribbean"),
    :SH => (Country{:SH},"Saint Helena",654,[:SHP],"290","Jamestown","AF",true,"Africa","Sub-Saharan Africa"),
    :CL => (Country{:CL},"Chile",152,[:CLP],"56","Santiago","SA",true,"Americas","Latin America and the Caribbean"),
    :CW => (Country{:CW},"Curaçao",531,[:ANG],"599","Willemstad","NA",true,"Americas","Latin America and the Caribbean"),
    :BJ => (Country{:BJ},"Benin",204,[:XOF],"229","Porto-Novo","AF",true,"Africa","Sub-Saharan Africa"),
    :DK => (Country{:DK},"Denmark",208,[:DKK],"45","Copenhagen","EU",false,"Europe","Northern Europe"),
    :IN => (Country{:IN},"India",356,[:INR],"91","New Delhi","AS",true,"Asia","Southern Asia"),
    :UM => (Country{:UM},"United States Minor Outlying Islands",581,[:USD],"nothing","nothing","OC",true,"Oceania","Micronesia"),
    :GM => (Country{:GM},"Gambia",270,[:GMD],"220","Banjul","AF",true,"Africa","Sub-Saharan Africa"),
    :AM => (Country{:AM},"Armenia",051,[:AMD],"374","Yerevan","AS",true,"Asia","Western Asia"),
    :DZ => (Country{:DZ},"Algeria",012,[:DZD],"213","Algiers","AF",true,"Africa","Northern Africa"),
    :KW => (Country{:KW},"Kuwait",414,[:KWD],"965","Kuwait City","AS",true,"Asia","Western Asia"),
    :TJ => (Country{:TJ},"Tajikistan",762,[:TJS],"992","Dushanbe","AS",true,"Asia","Central Asia"),
    :LK => (Country{:LK},"Sri Lanka",144,[:LKR],"94","Colombo","AS",true,"Asia","Southern Asia"),
    :UG => (Country{:UG},"Uganda",800,[:UGX],"256","Kampala","AF",true,"Africa","Sub-Saharan Africa"),
    :ZW => (Country{:ZW},"Zimbabwe",716,[:ZWL],"263","Harare","AF",true,"Africa","Sub-Saharan Africa"),
    :MY => (Country{:MY},"Malaysia",458,[:MYR],"60","Kuala Lumpur","AS",true,"Asia","South-eastern Asia"),
    :GD => (Country{:GD},"Grenada",308,[:XCD],"1-473","St. George's","NA",true,"Americas","Latin America and the Caribbean"),
    :ES => (Country{:ES},"Spain",724,[:EUR],"34","Madrid","EU",false,"Europe","Southern Europe"),
    :SM => (Country{:SM},"San Marino",674,[:EUR],"378","San Marino","EU",false,"Europe","Southern Europe"),
    :BB => (Country{:BB},"Barbados",052,[:BBD],"1-246","Bridgetown","NA",true,"Americas","Latin America and the Caribbean"),
    :VN => (Country{:VN},"Viet Nam",704,[:VND],"84","Hanoi","AS",true,"Asia","South-eastern Asia"),
    :CF => (Country{:CF},"Central African Republic",140,[:XAF],"236","Bangui","AF",true,"Africa","Sub-Saharan Africa"),
    :DJ => (Country{:DJ},"Djibouti",262,[:DJF],"253","Djibouti","AF",true,"Africa","Sub-Saharan Africa"),
    :FJ => (Country{:FJ},"Fiji",242,[:FJD],"679","Suva","OC",true,"Oceania","Melanesia"),
    :ST => (Country{:ST},"Sao Tome and Principe",678,[:STD],"239","Sao Tome","AF",true,"Africa","Sub-Saharan Africa"),
    :GP => (Country{:GP},"Guadeloupe",312,[:EUR],"590","Basse-Terre","NA",true,"Americas","Latin America and the Caribbean"),
    :NZ => (Country{:NZ},"New Zealand",554,[:NZD],"64","Wellington","OC",false,"Oceania","Australia and New Zealand"),
    :SY => (Country{:SY},"Syrian Arab Republic",760,[:SYP],"963","Damascus","AS",true,"Asia","Western Asia"),
    :PH => (Country{:PH},"Philippines",608,[:PHP],"63","Manila","AS",true,"Asia","South-eastern Asia"),
    :IL => (Country{:IL},"Israel",376,[:ILS],"972","Jerusalem","AS",true,"Asia","Western Asia"),
    :JE => (Country{:JE},"Jersey",832,[:GBP],"44","Saint Helier","EU",false,"Europe","Northern Europe"),
    :IO => (Country{:IO},"British Indian Ocean Territory",086,[:USD],"246","Diego Garcia","AS",true,"Africa","Sub-Saharan Africa"),
    :KE => (Country{:KE},"Kenya",404,[:KES],"254","Nairobi","AF",true,"Africa","Sub-Saharan Africa"),
    :MW => (Country{:MW},"Malawi",454,[:MWK],"265","Lilongwe","AF",true,"Africa","Sub-Saharan Africa"),
    :MV => (Country{:MV},"Maldives",462,[:MVR],"960","Male","AS",true,"Asia","Southern Asia"),
    :AW => (Country{:AW},"Aruba",533,[:AWG],"297","Oranjestad","NA",true,"Americas","Latin America and the Caribbean"),
    :HK => (Country{:HK},"China, Hong Kong Special Administrative Region",344,[:HKD],"852","Hong Kong","AS",true,"Asia","Eastern Asia"),
    :SZ => (Country{:SZ},"Swaziland",748,[:SZL],"268","Mbabane","AF",true,"Africa","Sub-Saharan Africa"),
    :ID => (Country{:ID},"Indonesia",360,[:IDR],"62","Jakarta","AS",true,"Asia","South-eastern Asia"),
    :AT => (Country{:AT},"Austria",040,[:EUR],"43","Vienna","EU",false,"Europe","Western Europe"),
    :LR => (Country{:LR},"Liberia",430,[:LRD],"231","Monrovia","AF",true,"Africa","Sub-Saharan Africa"),
    :SO => (Country{:SO},"Somalia",706,[:SOS],"252","Mogadishu","AF",true,"Africa","Sub-Saharan Africa"),
    :MZ => (Country{:MZ},"Mozambique",508,[:MZN],"258","Maputo","AF",true,"Africa","Sub-Saharan Africa"),
    :TK => (Country{:TK},"Tokelau",772,[:NZD],"690","nothing","OC",true,"Oceania","Polynesia"),
    :MA => (Country{:MA},"Morocco",504,[:MAD],"212","Rabat","AF",true,"Africa","Northern Africa"),
    :SK => (Country{:SK},"Slovakia",703,[:EUR],"421","Bratislava","EU",false,"Europe","Eastern Europe"),
    :SV => (Country{:SV},"El Salvador",222,[:SVC, :USD],"503","San Salvador","NA",true,"Americas","Latin America and the Caribbean"),
    :CD => (Country{:CD},"Democratic Republic of the Congo",180,[:CDF],"243","Kinshasa","AF",true,"Africa","Sub-Saharan Africa"),
    :CH => (Country{:CH},"Switzerland",756,[:CHF],"41","Bern","EU",false,"Europe","Western Europe"),
    :KH => (Country{:KH},"Cambodia",116,[:KHR],"855","Phnom Penh","AS",true,"Asia","South-eastern Asia"),
    :BL => (Country{:BL},"Saint Barthélemy",652,[:EUR],"590","Gustavia","NA",true,"Americas","Latin America and the Caribbean"),
    :GQ => (Country{:GQ},"Equatorial Guinea",226,[:XAF],"240","Malabo","AF",true,"Africa","Sub-Saharan Africa"),
    :ZA => (Country{:ZA},"South Africa",710,[:ZAR],"27","Pretoria","AF",true,"Africa","Sub-Saharan Africa"),
    :GG => (Country{:GG},"Guernsey",831,[:GBP],"44","St Peter Port","EU",false,"Europe","Northern Europe"),
    :MO => (Country{:MO},"China, Macao Special Administrative Region",446,[:MOP],"853","Macao","AS",true,"Asia","Eastern Asia"),
    :HN => (Country{:HN},"Honduras",340,[:HNL],"504","Tegucigalpa","NA",true,"Americas","Latin America and the Caribbean"),
    :SL => (Country{:SL},"Sierra Leone",694,[:SLL],"232","Freetown","AF",true,"Africa","Sub-Saharan Africa"),
    :LI => (Country{:LI},"Liechtenstein",438,[:CHF],"423","Vaduz","EU",false,"Europe","Western Europe"),
    :IT => (Country{:IT},"Italy",380,[:EUR],"39","Rome","EU",false,"Europe","Southern Europe"),
    :YE => (Country{:YE},"Yemen",887,[:YER],"967","Sanaa","AS",true,"Asia","Western Asia"),
    :SC => (Country{:SC},"Seychelles",690,[:SCR],"248","Victoria","AF",true,"Africa","Sub-Saharan Africa"),
    :ME => (Country{:ME},"Montenegro",499,[:EUR],"382","Podgorica","EU",false,"Europe","Southern Europe"),
    :CV => (Country{:CV},"Cabo Verde",132,[:CVE],"238","Praia","AF",true,"Africa","Sub-Saharan Africa"),
    :BE => (Country{:BE},"Belgium",056,[:EUR],"32","Brussels","EU",false,"Europe","Western Europe"),
    :NC => (Country{:NC},"New Caledonia",540,[:XPF],"687","Noumea","OC",true,"Oceania","Melanesia"),
    :GF => (Country{:GF},"French Guiana",254,[:EUR],"594","Cayenne","SA",true,"Americas","Latin America and the Caribbean"),
    :JO => (Country{:JO},"Jordan",400,[:JOD],"962","Amman","AS",true,"Asia","Western Asia"),
    :GH => (Country{:GH},"Ghana",288,[:GHS],"233","Accra","AF",true,"Africa","Sub-Saharan Africa"),
    :DE => (Country{:DE},"Germany",276,[:EUR],"49","Berlin","EU",false,"Europe","Western Europe"),
    :BQ => (Country{:BQ},"Bonaire, Sint Eustatius and Saba",535,[:USD],"599","nothing","NA",true,"Americas","Latin America and the Caribbean"),
    :MD => (Country{:MD},"Republic of Moldova",498,[:MDL],"373","Chisinau","EU",false,"Europe","Eastern Europe"),
    :AO => (Country{:AO},"Angola",024,[:AOA],"244","Luanda","AF",true,"Africa","Sub-Saharan Africa"),
    :CK => (Country{:CK},"Cook Islands",184,[:NZD],"682","Avarua","OC",true,"Oceania","Polynesia"),
    :TO => (Country{:TO},"Tonga",776,[:TOP],"676","Nuku'alofa","OC",true,"Oceania","Polynesia"),
    :LT => (Country{:LT},"Lithuania",440,[:EUR],"370","Vilnius","EU",false,"Europe","Northern Europe"),
    :RU => (Country{:RU},"Russian Federation",643,[:RUB],"7","Moscow","EU",false,"Europe","Eastern Europe"),
    :AI => (Country{:AI},"Anguilla",660,[:XCD],"1-264","The Valley","NA",true,"Americas","Latin America and the Caribbean"),
    :AQ => (Country{:AQ},"Antarctica",010,Symbol[],"672","nothing","AN",false,"nothing","nothing"),
    :EC => (Country{:EC},"Ecuador",218,[:USD],"593","Quito","SA",true,"Americas","Latin America and the Caribbean"),
    :HT => (Country{:HT},"Haiti",332,[:HTG, :USD],"509","Port-au-Prince","NA",true,"Americas","Latin America and the Caribbean"),
    :EH => (Country{:EH},"Western Sahara",732,[:MAD],"212","El-Aaiun","AF",true,"Africa","Northern Africa"),
    :SE => (Country{:SE},"Sweden",752,[:SEK],"46","Stockholm","EU",false,"Europe","Northern Europe"),
    :CG => (Country{:CG},"Congo",178,[:XAF],"242","Brazzaville","AF",true,"Africa","Sub-Saharan Africa"),
    :PN => (Country{:PN},"Pitcairn",612,[:NZD],"870","Adamstown","OC",true,"Oceania","Polynesia"),
    :KG => (Country{:KG},"Kyrgyzstan",417,[:KGS],"996","Bishkek","AS",true,"Asia","Central Asia"),
    :MN => (Country{:MN},"Mongolia",496,[:MNT],"976","Ulan Bator","AS",true,"Asia","Eastern Asia"),
    :NG => (Country{:NG},"Nigeria",566,[:NGN],"234","Abuja","AF",true,"Africa","Sub-Saharan Africa"),
    :PS => (Country{:PS},"State of Palestine",275,Symbol[],"970","East Jerusalem","AS",true,"Asia","Western Asia"),
    :MM => (Country{:MM},"Myanmar",104,[:MMK],"95","Nay Pyi Taw","AS",true,"Asia","South-eastern Asia"),
    :ML => (Country{:ML},"Mali",466,[:XOF],"223","Bamako","AF",true,"Africa","Sub-Saharan Africa"),
    :LA => (Country{:LA},"Lao People's Democratic Republic",418,[:LAK],"856","Vientiane","AS",true,"Asia","South-eastern Asia"),
    :PK => (Country{:PK},"Pakistan",586,[:PKR],"92","Islamabad","AS",true,"Asia","Southern Asia"),
    :LB => (Country{:LB},"Lebanon",422,[:LBP],"961","Beirut","AS",true,"Asia","Western Asia"),
    :GR => (Country{:GR},"Greece",300,[:EUR],"30","Athens","EU",false,"Europe","Southern Europe"),
    :WF => (Country{:WF},"Wallis and Futuna Islands",876,[:XPF],"681","Mata Utu","OC",true,"Oceania","Polynesia"),
    :HU => (Country{:HU},"Hungary",348,[:HUF],"36","Budapest","EU",false,"Europe","Eastern Europe"),
    :RS => (Country{:RS},"Serbia",688,[:RSD],"381","Belgrade","EU",false,"Europe","Southern Europe"),
    :BF => (Country{:BF},"Burkina Faso",854,[:XOF],"226","Ouagadougou","AF",true,"Africa","Sub-Saharan Africa"),
    :KR => (Country{:KR},"Republic of Korea",410,[:KRW],"82","Seoul","AS",true,"Asia","Eastern Asia"),
    :CN => (Country{:CN},"China",156,[:CNY],"86","Beijing","AS",true,"Asia","Eastern Asia"),
    :ER => (Country{:ER},"Eritrea",232,[:ERN],"291","Asmara","AF",true,"Africa","Sub-Saharan Africa"),
    :ET => (Country{:ET},"Ethiopia",231,[:ETB],"251","Addis Ababa","AF",true,"Africa","Sub-Saharan Africa"),
    :GE => (Country{:GE},"Georgia",268,[:GEL],"995","Tbilisi","AS",true,"Asia","Western Asia"),
    :BM => (Country{:BM},"Bermuda",060,[:BMD],"1-441","Hamilton","NA",false,"Americas","Northern America"),
    :TH => (Country{:TH},"Thailand",764,[:THB],"66","Bangkok","AS",true,"Asia","South-eastern Asia"),
    :SN => (Country{:SN},"Senegal",686,[:XOF],"221","Dakar","AF",true,"Africa","Sub-Saharan Africa"),
    :TD => (Country{:TD},"Chad",148,[:XAF],"235","N'Djamena","AF",true,"Africa","Sub-Saharan Africa"),
    :NL => (Country{:NL},"Netherlands",528,[:EUR],"31","Amsterdam","EU",false,"Europe","Western Europe"),
    :NU => (Country{:NU},"Niue",570,[:NZD],"683","Alofi","OC",true,"Oceania","Polynesia"),
    :BG => (Country{:BG},"Bulgaria",100,[:BGN],"359","Sofia","EU",false,"Europe","Eastern Europe"),
    :NR => (Country{:NR},"Nauru",520,[:AUD],"674","Yaren","OC",true,"Oceania","Micronesia"),
    :TC => (Country{:TC},"Turks and Caicos Islands",796,[:USD],"1-649","Cockburn Town","NA",true,"Americas","Latin America and the Caribbean"),
    :VI => (Country{:VI},"United States Virgin Islands",850,[:USD],"1-340","Charlotte Amalie","NA",true,"Americas","Latin America and the Caribbean"),
    :FM => (Country{:FM},"Micronesia (Federated States of)",583,[:USD],"691","Palikir","OC",true,"Oceania","Micronesia"),
    :BH => (Country{:BH},"Bahrain",048,[:BHD],"973","Manama","AS",true,"Asia","Western Asia"),
    :LS => (Country{:LS},"Lesotho",426,[:LSL, :ZAR],"266","Maseru","AF",true,"Africa","Sub-Saharan Africa"),
    :PW => (Country{:PW},"Palau",585,[:USD],"680","Melekeok","OC",true,"Oceania","Micronesia"),
    :AF => (Country{:AF},"Afghanistan",004,[:AFN],"93","Kabul","AS",true,"Asia","Southern Asia"),
    :NA => (Country{:NA},"Namibia",516,[:NAD, :ZAR],"264","Windhoek","AF",true,"Africa","Sub-Saharan Africa"),
    :CX => (Country{:CX},"Christmas Island",162,[:AUD],"61","Flying Fish Cove","AS",false,"Oceania","Australia and New Zealand"),
    :LY => (Country{:LY},"Libya",434,[:LYD],"218","Tripoli","AF",true,"Africa","Northern Africa"),
    :SB => (Country{:SB},"Solomon Islands",090,[:SBD],"677","Honiara","OC",true,"Oceania","Melanesia"),
    :PT => (Country{:PT},"Portugal",620,[:EUR],"351","Lisbon","EU",false,"Europe","Southern Europe"),
    :ZM => (Country{:ZM},"Zambia",894,[:ZMW],"260","Lusaka","AF",true,"Africa","Sub-Saharan Africa"),
    :KY => (Country{:KY},"Cayman Islands",136,[:KYD],"1-345","George Town","NA",true,"Americas","Latin America and the Caribbean"),
    :TL => (Country{:TL},"Timor-Leste",626,[:USD],"670","Dili","OC",true,"Asia","South-eastern Asia"),
    :CR => (Country{:CR},"Costa Rica",188,[:CRC],"506","San Jose","NA",true,"Americas","Latin America and the Caribbean"),
    :PY => (Country{:PY},"Paraguay",600,[:PYG],"595","Asuncion","SA",true,"Americas","Latin America and the Caribbean"),
    :RW => (Country{:RW},"Rwanda",646,[:RWF],"250","Kigali","AF",true,"Africa","Sub-Saharan Africa"),
    :AR => (Country{:AR},"Argentina",032,[:ARS],"54","Buenos Aires","SA",true,"Americas","Latin America and the Caribbean"),
    :GL => (Country{:GL},"Greenland",304,[:DKK],"299","Nuuk","NA",false,"Americas","Northern America"),
    :AZ => (Country{:AZ},"Azerbaijan",031,[:AZN],"994","Baku","AS",true,"Asia","Western Asia"),
    :KM => (Country{:KM},"Comoros",174,[:KMF],"269","Moroni","AF",true,"Africa","Sub-Saharan Africa"),
    :VC => (Country{:VC},"Saint Vincent and the Grenadines",670,[:XCD],"1-784","Kingstown","NA",true,"Americas","Latin America and the Caribbean"),
    :BR => (Country{:BR},"Brazil",076,[:BRL],"55","Brasilia","SA",true,"Americas","Latin America and the Caribbean"),
    :RE => (Country{:RE},"Réunion",638,[:EUR],"262","Saint-Denis","AF",true,"Africa","Sub-Saharan Africa"),
    :MK => (Country{:MK},"The former Yugoslav Republic of Macedonia",807,[:MKD],"389","Skopje","EU",false,"Europe","Southern Europe"),
    :MU => (Country{:MU},"Mauritius",480,[:MUR],"230","Port Louis","AF",true,"Africa","Sub-Saharan Africa"),
    :SG => (Country{:SG},"Singapore",702,[:SGD],"65","Singapore","AS",true,"Asia","South-eastern Asia"),
    :MP => (Country{:MP},"Northern Mariana Islands",580,[:USD],"1-670","Saipan","OC",true,"Oceania","Micronesia"),
    :AL => (Country{:AL},"Albania",008,[:ALL],"355","Tirana","EU",false,"Europe","Southern Europe"),
    :UZ => (Country{:UZ},"Uzbekistan",860,[:UZS],"998","Tashkent","AS",true,"Asia","Central Asia"),
    :PM => (Country{:PM},"Saint Pierre and Miquelon",666,[:EUR],"508","Saint-Pierre","NA",false,"Americas","Northern America"),
    :AX => (Country{:AX},"Åland Islands",248,[:EUR],"358","Mariehamn","EU",false,"Europe","Northern Europe"),
    :JM => (Country{:JM},"Jamaica",388,[:JMD],"1-876","Kingston","NA",true,"Americas","Latin America and the Caribbean"),
    :CY => (Country{:CY},"Cyprus",196,[:EUR],"357","Nicosia","EU",true,"Asia","Western Asia"),
    :GI => (Country{:GI},"Gibraltar",292,[:GIP],"350","Gibraltar","EU",false,"Europe","Southern Europe"),
    :GS => (Country{:GS},"South Georgia and the South Sandwich Islands",239,Symbol[],"500","Grytviken","AN",true,"Americas","Latin America and the Caribbean"),
    :TN => (Country{:TN},"Tunisia",788,[:TND],"216","Tunis","AF",true,"Africa","Northern Africa"),
    :DM => (Country{:DM},"Dominica",212,[:XCD],"1-767","Roseau","NA",true,"Americas","Latin America and the Caribbean"),
    :BW => (Country{:BW},"Botswana",072,[:BWP],"267","Gaborone","AF",true,"Africa","Sub-Saharan Africa"),
    :NI => (Country{:NI},"Nicaragua",558,[:NIO],"505","Managua","NA",true,"Americas","Latin America and the Caribbean"),
)


text:
const where_bisect = 0.49609375

"""
    bisect(X::Interval, α=0.49609375)

Split the interval `X` at position α; α=0.5 corresponds to the midpoint.
Returns a tuple of the new intervals.
"""
function bisect(X::Interval, α=where_bisect)
    @assert 0 ≤ α ≤ 1

    m = mid(X, α)

    return (Interval(X.lo, m), Interval(m, X.hi))
end

"""
    bisect(X::IntervalBox, α=0.49609375)

Bisect the `IntervalBox` `X` at position α ∈ [0,1] along its longest side.
"""
function bisect(X::IntervalBox, α=where_bisect)
    i = argmax(diam.(X))  # find longest side

    return bisect(X, i, α)
end

"""
    bisect(X::IntervalBox, i::Integer, α=0.49609375)

Bisect the `IntervalBox` in side number `i`.
"""
function bisect(X::IntervalBox, i::Integer, α=where_bisect)

    x1, x2 = bisect(X[i], α)

    X1 = setindex(X, x1, i)
    X2 = setindex(X, x2, i)

    return (X1, X2)
end


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

mutable struct IoK8sApiCoreV1TopologySelectorLabelRequirement <: SwaggerModel
    key::Any # spec type: Union{ Nothing, String } # spec name: key
    values::Any # spec type: Union{ Nothing, Vector{String} } # spec name: values

    function IoK8sApiCoreV1TopologySelectorLabelRequirement(;key=nothing, values=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1TopologySelectorLabelRequirement, Symbol("key"), key)
        setfield!(o, Symbol("key"), key)
        validate_property(IoK8sApiCoreV1TopologySelectorLabelRequirement, Symbol("values"), values)
        setfield!(o, Symbol("values"), values)
        o
    end
end # type IoK8sApiCoreV1TopologySelectorLabelRequirement

const _property_map_IoK8sApiCoreV1TopologySelectorLabelRequirement = Dict{Symbol,Symbol}(Symbol("key")=>Symbol("key"), Symbol("values")=>Symbol("values"))
const _property_types_IoK8sApiCoreV1TopologySelectorLabelRequirement = Dict{Symbol,String}(Symbol("key")=>"String", Symbol("values")=>"Vector{String}")
Base.propertynames(::Type{ IoK8sApiCoreV1TopologySelectorLabelRequirement }) = collect(keys(_property_map_IoK8sApiCoreV1TopologySelectorLabelRequirement))
Swagger.property_type(::Type{ IoK8sApiCoreV1TopologySelectorLabelRequirement }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApiCoreV1TopologySelectorLabelRequirement[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1TopologySelectorLabelRequirement }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1TopologySelectorLabelRequirement[property_name]

function check_required(o::IoK8sApiCoreV1TopologySelectorLabelRequirement)
    (getproperty(o, Symbol("key")) === nothing) && (return false)
    (getproperty(o, Symbol("values")) === nothing) && (return false)
    true
end

function validate_property(::Type{ IoK8sApiCoreV1TopologySelectorLabelRequirement }, name::Symbol, val)
end


text:
module IntoTheJungleCodeModTempleDoor

using ..Ahorn, Maple

@mapdef Entity "IntoTheJungleCodeMod/TempleDoor" TempleDoor(x::Integer, y::Integer)

const placements = Ahorn.PlacementDict(
    "Temple Door (Into The Jungle code mod)" => Ahorn.EntityPlacement(
        TempleDoor
    )
)

function Ahorn.selection(entity::TempleDoor)
    x, y = Ahorn.position(entity)
    return Ahorn.Rectangle(x - 30, y - 3, 60, 35)
end

function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::TempleDoor, room::Maple.Room)
    Ahorn.drawSprite(ctx, "JungleHelper/TempleMainDoor/templemaindoor_14", 0, 15)
end

end

max_stars_repo_name: Jackal-Celeste/JungleHelper

max_issues_repo_name: Jackal-Celeste/JungleHelper

max_forks_repo_name: Jackal-Celeste/JungleHelper


text:
using BlockDiagonals
using ChainRulesCore
using ChainRulesTestUtils
using Documenter
using FiniteDifferences # For overloading to_vec
using Test

@testset "BlockDiagonals" begin
    # The doctests fail on x86, so only run them on 64-bit hardware
    Sys.WORD_SIZE == 64 && doctest(BlockDiagonals)
    include("blockdiagonal.jl")
    include("base_maths.jl")
    include("linalg.jl")
end  # tests


text:
let
    @test sprint_padded(4;pad=5)                == "    4"
    @test sprint_padded("hi";pad=5)             == "   hi"
    @test sprint_padded("hi";
        pad=5,leftaligned=true)                 == "hi   "
    io = IOBuffer()
    sprint_padded_list(io,[1,10,2];pad=3)
    @test String(take!(io))    == "[  1 10  2]"
    sprint_padded_list(io,[1,10,2];
        pad=3,leftaligned=true)
    @test String(take!(io))    == "[1  10 2  ]"
    sprint_padded_list_array(io,[[1,2,3],[4,5,6]];
        id_pad=3,pad=3,leftaligned=true)
    @test String(take!(io))                     ==  """
                                                      1: [1  2  3  ]
                                                      2: [4  5  6  ]
                                                    """
    sprint_indexed_list_array(io,[[1,2,3],[4,5,6]];
        id_pad=4,pad=3,leftaligned=true)
    @test String(take!(io))                     ==  "   T:  0  1  2   \n   1: [1  2  3  ]\n   2: [4  5  6  ]\n"

end


text:
# export jlmie_Qsca, jlmie_Qsca_a_n, jlmie_Qsca_b_n

function jlmie_Qsca(m,x,nmax::Int=-1)
# Calculate scattering efficiency of a sphere
# Input:
# m: relative refractive index (n_material / n_environment)
# x: size parameter (wavenumber * radius)
# namx: maximun order of resonances being considered
#       (nmax = 1: dipole, 2: dipole+quadrupole, ...,
#        -1: sufficiently large value determined by x)
# Output:
# Qsca: Scattering efficiency (total up to n-th order resonances)
    if nmax == -1
        nmax = largenmax(x)
    end

    Qsca = zeros(length(x))
    for i = 1:nmax
        Qsca = Qsca .+ jlmie_Qsca_n(m,x,i)
    end
    return Qsca
end

function jlmie_Qsca_n(m,x,n::Int)
    an,bn,_,_ = jlmie_abcd(m,x,n)
    nth_Qsca = 2 ./ x.^2 .* (2*n+1).*(abs.(an).^2 .+ abs.(bn).^2)
    return nth_Qsca
end

function jlmie_Qsca_a_n(m,x,n::Int)
# calculate scattering efficiency due to the n-th order electric multipole
# (n = 1: dipole, 2: quadrupole, ...)
    an,_,_,_ = jlmie_abcd(m,x,n)
    nth_Qsca_a = 2 ./ x.^2 .* (2*n+1).*(abs.(an).^2)
    return nth_Qsca_a
end

function jlmie_Qsca_b_n(m,x,n::Int)
# calculate scattering efficiency due to the n-th order magnetic multipole
# (n = 1: dipole, 2: quadrupole, ...)
    _,bn,_,_ = jlmie_abcd(m,x,n)
    nth_Qsca_b = 2 ./ x.^2 .* (2*n+1).*(abs.(bn).^2)
    return nth_Qsca_b
end

max_stars_repo_name: Hinamoooon/jlmie

max_issues_repo_name: Hinamoooon/jlmie

max_forks_repo_name: Hinamoooon/jlmie


text:
function add_surface_fluxes!(ds)
    Qθ = ds.metadata["temperature_flux"]

    T = ds["T"]
    wT = ds["wT"]

    Nz = size(T, 3)
    wT[:, :, Nz+1, :] .= Qθ

    return ds
end


text:
using Plots;
using Printf;

alpha = 40;
f(D) = D/(2*tan(deg2rad(alpha/2)));
fpd = 300;
sfp(f) = 1/(1/f - 1/(fpd+f));
sl = 10*1000;
slp(f) = 1/(1/f - 1/(sl+f));
c(A, D) = A * (sfp(f(D)) / slp(f(D)) - 1);

As = 10:10:50;
x=5:5:35;
y=[(x->c(A, x)/x*100).(x) for A in As];
plot(
  x,y,
  title=@sprintf("Focal plane distance=%dcm, Light source distance=%dm", fpd/10, sl/1000),
  xlabel="Sensor size",
  ylabel="Bokeh relative to sensor size",
  label=reshape((A->@sprintf("A=%dmm",A)).(As),1,:),
  yformatter=(v->@sprintf("%d%%",v)),
  xformatter=(v->@sprintf("%dmm",v)),
  lw=3,
  draw_arrow=true,
  legend=:topleft,
)
savefig("constant-aperture.svg")

Fs=(x->sqrt(2)^x).(1:8)
y=[(x->c(f(x)/F, x)/x*100).(x) for F in Fs];
plot(
  x,y,
  title=@sprintf("Focal plane distance=%dcm, Light source distance=%dm", fpd/10, sl/1000),
  xlabel="Sensor size",
  ylabel="Bokeh relative to sensor size",
  label=reshape((F->@sprintf("A=f/%.1f",F)).(Fs),1,:),
  yformatter=(v->@sprintf("%d%%",v)),
  xformatter=(v->@sprintf("%dmm",v)),
  lw=3,
  draw_arrow=true,
  legend=:topleft,
)
savefig("fstop-aperture.svg")


text:
using PTools

println("testing pfork ...")
assert(pfork(2,ind->ind) == [1:2])
assert(pfork(100,ind->ind) == [1:100])
f(ind) = ones(10,100)*ind
r = pfork(10,f)
should = map(f,1:10)
assert(r == should)

println("testing pfork_shm ...")
n = 10
R = pfork_shm(n, Float32, (n,), (ind, r) -> r[ind]=ind)
should = float32([1:n])
assert(R==should)
assert(isa(R, Array{Float32}))
assert(size(R)==(n,))

n = 10
R = pfork_shm(n, Float32, (3,n), (ind, r) -> r[:,ind]=ind)
should = float32(repmat([1:n]',3,1))
assert(R==should)
assert(isa(R, Array{Float32}))
assert(size(R)==(3,n))

n = 10
param = 10
R = pfork_shm(n, Float32, (3,n), (ind, r, param) -> r[:,ind]=ind*param, param)
should = float32(repmat([1:n]'*param,3,1))
assert(R==should)
assert(isa(R, Array{Float32}))
assert(size(R)==(3,n))

n = 10
R = pfork_shm(n, Float32, (3,n), (ind, r) -> r[:,ind]=ind)
should = float32(repmat([1:n]',3,1))
assert(R==should)
assert(isa(R, Array{Float32}))
assert(size(R)==(3,n))

n = 10
R1,R2 = pfork_shm(n, {(Float32, (3,n)), (Float64, (n,))},
              (ind, r1, r2) -> (r1[:,ind]=ind; r2[ind]=ind*ind))
should1 = float32(repmat([1:n]',3,1))
should2 = [1:n].^2
assert(R1==should1)
assert(R2==should2)
assert(isa(R1, Array{Float32}))
assert(isa(R2, Array{Float64}))
assert(size(R1)==(3,n))
assert(size(R2)==(n,))

println("ok!")


text:
#!/usr/bin/env julia

home = homedir()
namespace = "pandola"
target = pwd()

# Main call.
main() = begin
    file_name = "index.css"
    pcs_dist_path = "$home/$namespace/pcs/dist/$file_name"
    target_file = "$target/$file_name"

    if target_file |> isfile
        rm(target_file)
        println("\nOK, Clear done.\n")
    else
        println("\nOK, No need to clear.\n")
    end
end

main()

max_stars_repo_name: yuffiy/pandola

max_issues_repo_name: HairyRabbit/pandola

max_forks_repo_name: HairyRabbit/pandola


text:
@api_default function delete(api::API, company::Company, p::Purchase; options...)
    post(api, "/company/$(company.Id)/purchase",
    query=Dict{Any,Any}(
        "operation" => "delete"
    ),
    params=Dict(
        "Id" => p.Id,
        "SyncToken" => p.SyncToken
    ); options...)
end

@api_default function create(api::API, company::Company, p::Purchase; options...)
    post(api, "/company/$(company.Id)/purchase",
    params=to_json(p); options...)
end


text:
using Documenter
using Jaynes

makedocs(sitename = "Jaynes.jl",
         pages = ["Introduction" => "index.md",
                  "Modeling language" => "modeling_lang.md",
                  "Examples" => "examples.md",
                  "Concepts" => "concepts.md",
                  "Architecture" => "architecture.md",
                  "Library" => ["Traces, choices, and call sites" => "library_api/sites.md",
                                "Execution contexts" => "library_api/contexts.md",
                                "Selection interface" => "library_api/selection_interface.md",
                                "Inference" => ["Importance sampling" => "inference/is.md",
                                                "Metropolis-Hastings" => "inference/mh.md",
                                                "Particle filtering" => "inference/pf.md",
                                                "Automatic differentiation variational inference" => "inference/vi.md"],
                                "Foreign model interface" => "library_api/fmi.md",
                                "Differentiable programming" => "library_api/diff_prog.md",
                               ],
                  #"Tutorials" => [
                  #               "Bayesian linear regression" => "bayeslinreg.md",
                  #               "Autoencoding with black box extensions" => "autoencoding.md",
                  #               "Gaussian process kernel synthesis" => "gp_kernel_synth.md",
                  #               "Inference compilation" => "infcomp.md"],
                  "Benchmarks" => "benchmarks/index.md",
                  "Related work" => "related_work.md"
                 ],
         format = Documenter.HTML(prettyurls = true,
                                  assets = ["assets/favicon.ico"])
        )

deploydocs(repo = "github.com/femtomc/Jaynes.jl.git")


text:
# ----------------------------- #
# MathProgBase solver interface #
# ----------------------------- #

function SolverInterface.initialize(d::GMMNLPE, rf::Vector{Symbol})
    for feat in rf
        if !(feat in [:Grad, :Jac, :Hess])
            error("Unsupported feature $feat")
        end
    end
end

SolverInterface.features_available(d::GMMNLPE) = [:Grad, :Jac, :Hess]

function SolverInterface.eval_f(d::GMMNLPE, theta)
    gn = d.smf(theta)
    (gn'd.W*gn)[1]
end

SolverInterface.eval_g(d::GMMNLPE, Dg, x) = nothing

function SolverInterface.eval_grad_f(d::GMMNLPE, grad_f, theta)
    grad_f[:] = 2*d.Dmf(theta)'*(d.W*d.smf(theta))
end

SolverInterface.jac_structure(d::GMMNLPE) = [],[]
SolverInterface.eval_jac_g(d::GMMNLPE, J, x) = nothing
SolverInterface.eval_hesslag(d::GMMNLPE, H, x, σ, μ) = nothing
SolverInterface.hesslag_structure(d::GMMNLPE) = [],[]


text:
# Initializing Python (surprisingly complicated; see also deps/build.jl)

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

# global PyObject constants, initialized to NULL and then overwritten in __init__
# (eventually, the ability to define global const in __init__ may go away,
#  and in any case this is better for type inference during precompilation)
const inspect = PyNULL()
const builtin = PyNULL()
const BuiltinFunctionType = PyNULL()
const MethodType = PyNULL()
const MethodWrapperType = PyNULL()
const ufuncType = PyNULL()
const format_traceback = PyNULL()
const pyproperty = PyNULL()
const jlfun2pyfun = PyNULL()
const c_void_p_Type = PyNULL()

# other global constants initialized at runtime are defined via Ref
# or are simply left as non-const values
const pynothing = Ref{PyPtr}(0)
const pyxrange = Ref{PyPtr}(0)

#########################################################################
# initialize jlWrapType for pytype.jl

function pyjlwrap_init()
    # PyMemberDef stores explicit pointers, hence must be initialized at runtime
    empty!(pyjlwrap_members)  # for AOT
    push!(pyjlwrap_members, PyMemberDef(pyjlwrap_membername,
                                        T_PYSSIZET, sizeof_pyjlwrap_head, READONLY,
                                        pyjlwrap_doc),
                            PyMemberDef(C_NULL,0,0,0,C_NULL))

    # all cfunctions must be compiled at runtime
    pyjlwrap_dealloc_ptr = @cfunction(pyjlwrap_dealloc, Cvoid, (PyPtr,))
    pyjlwrap_repr_ptr = @cfunction(pyjlwrap_repr, PyPtr, (PyPtr,))
    pyjlwrap_hash_ptr = @cfunction(pyjlwrap_hash, UInt, (PyPtr,))
    pyjlwrap_hash32_ptr = @cfunction(pyjlwrap_hash32, UInt32, (PyPtr,))
    pyjlwrap_call_ptr = @cfunction(pyjlwrap_call, PyPtr, (PyPtr,PyPtr,PyPtr))
    pyjlwrap_getattr_ptr = @cfunction(pyjlwrap_getattr, PyPtr, (PyPtr,PyPtr))
    pyjlwrap_getiter_ptr = @cfunction(pyjlwrap_getiter, PyPtr, (PyPtr,))

    # detect at runtime whether we are using Stackless Python
    try
        pyimport("stackless")
        Py_TPFLAGS_HAVE_STACKLESS_EXTENSION[] = Py_TPFLAGS_HAVE_STACKLESS_EXTENSION_
    catch
    end

    PyTypeObject!(jlWrapType, "PyCall.jlwrap", sizeof(Py_jlWrap)) do t::PyTypeObject
        t.tp_flags |= Py_TPFLAGS_BASETYPE
        t.tp_members = pointer(pyjlwrap_members);
        t.tp_dealloc = pyjlwrap_dealloc_ptr
        t.tp_repr = pyjlwrap_repr_ptr
        t.tp_call = pyjlwrap_call_ptr
        t.tp_getattro = pyjlwrap_getattr_ptr
        t.tp_iter = pyjlwrap_getiter_ptr
        t.tp_hash = sizeof(Py_hash_t) < sizeof(Int) ?
                    pyjlwrap_hash32_ptr : pyjlwrap_hash_ptr
        t.tp_weaklistoffset = fieldoffset(Py_jlWrap, 3)
    end
end

#########################################################################
# Virtual environment support

venv_python(::Nothing) = pyprogramname

function venv_python(venv::AbstractString, suffix::AbstractString = "")
    # `suffix` is used to insert version number (e.g., "3.7") in tests
    # (see ../test/test_venv.jl)
    if Sys.iswindows()
        return joinpath(venv, "Scripts", "python$suffix.exe")
    else
        return joinpath(venv, "bin", "python$suffix")
    end
    # "Scripts" is used only in Windows and "bin" elsewhere:
    # https://github.com/python/cpython/blob/3.7/Lib/venv/__init__.py#L116
end

"""
    python_cmd(args::Cmd = ``; venv, python) :: Cmd

Create an appropriate `Cmd` for running Python program with command
line arguments `args`.

# Keyword Arguments
- `venv::String`: The path of a virtualenv to be used instead of the
  default environment with which PyCall isconfigured.
- `python::String`: The path to the Python executable.  `venv` is ignored
  when this argument is specified.
"""
function python_cmd(args::Cmd = ``;
                    venv::Union{Nothing, AbstractString} = nothing,
                    python::AbstractString = venv_python(venv))
    return pythonenv(`$python $args`)
end

function find_libpython(python::AbstractString)
    script = joinpath(@__DIR__, "..", "deps", "find_libpython.py")
    cmd = python_cmd(`$script`; python = python)
    try
        return read(cmd, String)
    catch
        return nothing
    end
end

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

const _finalized = Ref(false)
# This flag is set via `Py_AtExit` to avoid calling `pydecref_` after
# Python is finalized.

function _set_finalized()
    # This function MUST NOT invoke any Python APIs.
    # https://docs.python.org/3/c-api/sys.html#c.Py_AtExit
    _finalized[] = true
    return nothing
end

function Py_Finalize()
    pygui_stop_all()
    ccall(@pysym(:Py_Finalize), Cvoid, ())
end

function __init__()
    # Clear out global states.  This is required only for PyCall
    # AOT-compiled into system image.
    _finalized[] = false
    empty!(_namespaces)
    empty!(eventloops)
    global npy_initialized = false
    empty!(npy_api)
    empty!(pycall_gc)
    empty!(pyexc)
    empty!(pytype_queries)
    empty!(permanent_strings)

    # sanity check: in Pkg for Julia 0.7+, the location of Conda can change
    # if e.g. you checkout Conda master, and we'll need to re-build PyCall
    # for something like pyimport_conda to continue working.
    if conda && dirname(python) != abspath(Conda.PYTHONDIR)
        error("Using Conda.jl python, but location of $python seems to have moved to $(Conda.PYTHONDIR).  Re-run Pkg.build(\"PyCall\") and restart Julia.")
    end

    # issue #189
    libpy_handle = libpython === nothing ? C_NULL :
        Libdl.dlopen(libpython, Libdl.RTLD_LAZY|Libdl.RTLD_DEEPBIND|Libdl.RTLD_GLOBAL)

    already_inited = 0 != ccall((@pysym :Py_IsInitialized), Cint, ())

    if !already_inited
        pyhome = PYTHONHOME

        if isfile(get(ENV, "PYCALL_JL_RUNTIME_PYTHON", ""))
            _current_python[] = ENV["PYCALL_JL_RUNTIME_PYTHON"]

            # Check libpython compatibility.
            venv_libpython = find_libpython(current_python())
            if venv_libpython === nothing
                error("""
                `libpython` for $(current_python()) cannot be found.
                PyCall.jl cannot initialize Python safely.
                """)
            elseif venv_libpython != libpython
                error("""
                Incompatible `libpython` detected.
                `libpython` for $(current_python()) is:
                    $venv_libpython
                `libpython` for $pyprogramname is:
                    $libpython
                PyCall.jl only supports loading Python environment using
                the same `libpython`.
                """)
            end

            if haskey(ENV, "PYCALL_JL_RUNTIME_PYTHONHOME")
                pyhome = ENV["PYCALL_JL_RUNTIME_PYTHONHOME"]
            else
                pyhome = pythonhome_of(current_python())
            end
        end

        Py_SetPythonHome(libpy_handle, pyversion, pyhome)
        Py_SetProgramName(libpy_handle, pyversion, current_python())
        ccall((@pysym :Py_InitializeEx), Cvoid, (Cint,), 0)
    end

    # Will get reinitialized properly on first use
    Sys.iswindows() && (PyActCtx[] = C_NULL)

    # Make sure python wasn't upgraded underneath us
    new_pyversion = vparse(split(unsafe_string(ccall(@pysym(:Py_GetVersion),
                               Ptr{UInt8}, ())))[1])

    if new_pyversion.major != pyversion.major
        error("PyCall precompiled with Python $pyversion, but now using Python $new_pyversion; ",
              "you need to relaunch Julia and re-run Pkg.build(\"PyCall\")")
    end

    copy!(inspect, pyimport("inspect"))
    copy!(builtin, pyimport(pyversion.major < 3 ? "__builtin__" : "builtins"))
    copy!(pyproperty, pybuiltin(:property))

    pyexc_initialize() # mappings from Julia Exception types to Python exceptions

    # cache Python None -- PyPtr, not PyObject, to prevent it from
    # being finalized prematurely on exit
    pynothing[] = @pyglobalobj(:_Py_NoneStruct)

    # xrange type (or range in Python 3)
    pyxrange[] = @pyglobalobj(:PyRange_Type)

    # ctypes.c_void_p for Ptr types
    copy!(c_void_p_Type, pyimport("ctypes")."c_void_p")

    # traceback.format_tb function, for show(PyError)
    copy!(format_traceback, pyimport("traceback")."format_tb")

    init_datetime()
    pyjlwrap_init()

    # jlwrap is a class, and when assigning it to an object
    #    obj[:foo] = some_julia_function
    # it won't behave like a regular Python method because it's not a Python
    # function (in particular, `self` won't be passed to it). The solution is:
    #    obj[:foo] = jlfun2pyfun(some_julia_function)
    # This is a bit of a kludge, obviously.
    copy!(jlfun2pyfun,
          pyeval_("""lambda f: lambda *args, **kwargs: f(*args, **kwargs)"""))

    if !already_inited
        # some modules (e.g. IPython) expect sys.argv to be set
        ref0 = Ref{UInt32}(0)
        GC.@preserve ref0 ccall(@pysym(:PySys_SetArgvEx), Cvoid,
                                        (Cint, Ref{Ptr{Cvoid}}, Cint),
                                        1, pointer_from_objref(ref0), 0)

        # Some Python code checks sys.ps1 to see if it is running
        # interactively, and refuses to be interactive otherwise.
        # (e.g. Matplotlib: see PyPlot#79)
        if isinteractive()
            let sys = pyimport("sys")
                if !hasproperty(sys, "ps1")
                    sys."ps1" = ">>> "
                end
            end
        end
    end

    # Configure finalization steps.
    #
    # * In julia/PyCall, `julia` needs to call `Py_Finalize` to
    #   finalize Python runtime to invoke Python functions registered
    #   in Python's exit hook.  This is done by Julia's `atexit` exit
    #   hook.
    #
    # * In PyJulia, `python` needs to call `jl_atexit_hook` in its
    #   exit hook instead.
    #
    # In both cases, it is important to not invoke GC of the finalized
    # runtime.  This is ensured by:
    @pycheckz ccall((@pysym :Py_AtExit), Cint, (Ptr{Cvoid},),
                    @cfunction(_set_finalized, Cvoid, ()))
    if !already_inited
        # Once `_set_finalized` is successfully registered to
        # `Py_AtExit`, it is safe to call `Py_Finalize` during
        # finalization of this Julia process.
        atexit(Py_Finalize)
    end
end