text:
"""
GenX: An Configurable Capacity Expansion Model
Copyright (C) 2021,  Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
A complete copy of the GNU General Public License v2 (GPLv2) is available
in LICENSE.txt.  Users uncompressing this from an archive may not have
received this license file.  If not, see <http://www.gnu.org/licenses/>.
"""

@doc raw"""
	load_generators_data(setup::Dict, path::AbstractString, inputs_gen::Dict, fuel_costs::Dict, fuel_CO2::Dict)

Function for reading input parameters related to electricity generators (plus storage and flexible demand resources)
"""
function load_generators_data(setup::Dict, path::AbstractString, inputs_gen::Dict, fuel_costs::Dict, fuel_CO2::Dict)

	# Generator related inputs
	gen_in = DataFrame(CSV.File(joinpath(path, "Generators_data.csv"), header=true), copycols=true)

	# Add Resource IDs after reading to prevent user errors
	gen_in[!,:R_ID] = 1:size(collect(skipmissing(gen_in[!,1])),1)

	# Store DataFrame of generators/resources input data for use in model
	inputs_gen["dfGen"] = gen_in

	# Number of resources
	inputs_gen["G"] = size(collect(skipmissing(gen_in[!,:R_ID])),1)

	# Set indices for internal use
	G = inputs_gen["G"]   # Number of resources (generators, storage, DR, and DERs)

	## Defining sets of generation and storage resources

	# Set of storage resources with symmetric charge/discharge capacity
	inputs_gen["STOR_SYMMETRIC"] = gen_in[gen_in.STOR.==1,:R_ID]
	# Set of storage resources with asymmetric (separte) charge/discharge capacity components
	inputs_gen["STOR_ASYMMETRIC"] = gen_in[gen_in.STOR.==2,:R_ID]
	# Set of all storage resources
	inputs_gen["STOR_ALL"] = union(inputs_gen["STOR_SYMMETRIC"],inputs_gen["STOR_ASYMMETRIC"])

	# Set of storage resources with long duration storage capabilitites
	#if setup["LongDurationStorage"] == 1
		inputs_gen["STOR_HYDRO_LONG_DURATION"] = gen_in[(gen_in.LDS.==1) .& (gen_in.HYDRO.==1),:R_ID]
		inputs_gen["STOR_LONG_DURATION"] = gen_in[(gen_in.LDS.==1) .& (gen_in.STOR.==1),:R_ID]
		inputs_gen["STOR_SHORT_DURATION"] = gen_in[(gen_in.LDS.==0) .& (gen_in.STOR.==1),:R_ID]
	#end

	# Set of all reservoir hydro resources
	inputs_gen["HYDRO_RES"] = gen_in[(gen_in[!,:HYDRO].==1),:R_ID]
	# Set of reservoir hydro resources modeled with known reservoir energy capacity
	inputs_gen["HYDRO_RES_KNOWN_CAP"] = intersect(gen_in[gen_in.Hydro_Energy_to_Power_Ratio.>0,:R_ID], inputs_gen["HYDRO_RES"])

	# Set of flexible demand-side resources
	inputs_gen["FLEX"] = gen_in[gen_in.FLEX.==1,:R_ID]

	# Set of must-run plants - could be behind-the-meter PV, hydro run-of-river, must-run fossil or thermal plants
	inputs_gen["MUST_RUN"] = gen_in[gen_in.MUST_RUN.==1,:R_ID]

	# Set of controllable variable renewable resources
	inputs_gen["VRE"] = gen_in[gen_in.VRE.>=1,:R_ID]

	# Set of thermal generator resources
	if setup["UCommit"]>=1
		# Set of thermal resources eligible for unit committment
		inputs_gen["THERM_COMMIT"] = gen_in[gen_in.THERM.==1,:R_ID]
		# Set of thermal resources not eligible for unit committment
		inputs_gen["THERM_NO_COMMIT"] = gen_in[gen_in.THERM.==2,:R_ID]
	else # When UCommit == 0, no thermal resources are eligible for unit committment
		inputs_gen["THERM_COMMIT"] = Int64[]
		inputs_gen["THERM_NO_COMMIT"] = union(gen_in[gen_in.THERM.==1,:R_ID], gen_in[gen_in.THERM.==2,:R_ID])
	end
	inputs_gen["THERM_ALL"] = union(inputs_gen["THERM_COMMIT"],inputs_gen["THERM_NO_COMMIT"])

	# For now, the only resources eligible for UC are themal resources
	inputs_gen["COMMIT"] = inputs_gen["THERM_COMMIT"]

	if setup["Reserves"] >= 1
		# Set for resources with regulation reserve requirements
		inputs_gen["REG"] = gen_in[(gen_in[!,:Reg_Max].>0),:R_ID]
		# Set for resources with spinning reserve requirements
		inputs_gen["RSV"] = gen_in[(gen_in[!,:Rsv_Max].>0),:R_ID]
	end

	# Set of all resources eligible for new capacity
	inputs_gen["NEW_CAP"] = intersect(gen_in[gen_in.New_Build.==1,:R_ID], gen_in[gen_in.Max_Cap_MW.!=0,:R_ID])
	# Set of all resources eligible for capacity retirements
	inputs_gen["RET_CAP"] = intersect(gen_in[gen_in.New_Build.!=-1,:R_ID], gen_in[gen_in.Existing_Cap_MW.>=0,:R_ID])

	# Set of all storage resources eligible for new energy capacity
	inputs_gen["NEW_CAP_ENERGY"] = intersect(gen_in[gen_in.New_Build.==1,:R_ID], gen_in[gen_in.Max_Cap_MWh.!=0,:R_ID], inputs_gen["STOR_ALL"])
	# Set of all storage resources eligible for energy capacity retirements
	inputs_gen["RET_CAP_ENERGY"] = intersect(gen_in[gen_in.New_Build.!=-1,:R_ID], gen_in[gen_in.Existing_Cap_MWh.>=0,:R_ID], inputs_gen["STOR_ALL"])

	# Set of asymmetric charge/discharge storage resources eligible for new charge capacity
	inputs_gen["NEW_CAP_CHARGE"] = intersect(gen_in[gen_in.New_Build.==1,:R_ID], gen_in[gen_in.Max_Charge_Cap_MW.!=0,:R_ID], inputs_gen["STOR_ASYMMETRIC"])
	# Set of asymmetric charge/discharge storage resources eligible for charge capacity retirements
	inputs_gen["RET_CAP_CHARGE"] = intersect(gen_in[gen_in.New_Build.!=-1,:R_ID], gen_in[gen_in.Existing_Charge_Cap_MW.>=0,:R_ID], inputs_gen["STOR_ASYMMETRIC"])

	# Names of resources
	inputs_gen["RESOURCES"] = collect(skipmissing(gen_in[!,:Resource][1:inputs_gen["G"]]))
	# Zones resources are located in
	zones = collect(skipmissing(gen_in[!,:Zone][1:inputs_gen["G"]]))
	# Resource identifiers by zone (just zones in resource order + resource and zone concatenated)
	inputs_gen["R_ZONES"] = zones
	inputs_gen["RESOURCE_ZONES"] = inputs_gen["RESOURCES"] .* "_z" .* string.(zones)

	if setup["ParameterScale"] ==1  # Parameter scaling turned on - adjust values of subset of parameter values
		# The existing capacity of a power plant in megawatts
		inputs_gen["dfGen"][!,:Existing_Charge_Cap_MW] = gen_in[!,:Existing_Charge_Cap_MW]/ModelScalingFactor # Convert to GW
		# The existing capacity of storage in megawatt-hours STOR = 1 or STOR = 2
		inputs_gen["dfGen"][!,:Existing_Cap_MWh] = gen_in[!,:Existing_Cap_MWh]/ModelScalingFactor # Convert to GWh
		# The existing charging capacity for resources where STOR = 2
		inputs_gen["dfGen"][!,:Existing_Cap_MW] = gen_in[!,:Existing_Cap_MW]/ModelScalingFactor # Convert to GW

		# Cap_Size scales only capacities for those technologies with capacity >1
		# Step 1: convert vector to float
		inputs_gen["dfGen"][!,:Cap_Size] =convert(Array{Float64}, gen_in[!,:Cap_Size])
		for g in 1:G  # Scale only those capacities for which Cap_Size > 1
			if inputs_gen["dfGen"][!,:Cap_Size][g]>1.0
				inputs_gen["dfGen"][!,:Cap_Size][g] = gen_in[!,:Cap_Size][g]/ModelScalingFactor # Convert to GW
			end
		end

		# Min capacity terms
		# Limit on minimum discharge capacity of the resource. -1 if no limit on minimum capacity
		inputs_gen["dfGen"][!,:Min_Cap_MW] = gen_in[!,:Min_Cap_MW]/ModelScalingFactor # Convert to GW
		# Limit on minimum energy capacity of the resource. -1 if no limit on minimum capacity
		inputs_gen["dfGen"][!,:Min_Cap_MWh] = gen_in[!,:Min_Cap_MWh]/ModelScalingFactor # Convert to GWh
		# Limit on minimum charge capacity of the resource. -1 if no limit on minimum capacity
		inputs_gen["dfGen"][!,:Min_Charge_Cap_MW] = gen_in[!,:Min_Charge_Cap_MW]/ModelScalingFactor # Convert to GWh

		## Max capacity terms
		# Limit on maximum discharge capacity of the resource. -1 if no limit on maximum capacity
		inputs_gen["dfGen"][!,:Max_Cap_MW] = gen_in[!,:Max_Cap_MW]/ModelScalingFactor # Convert to GW
		# Limit on maximum energy capacity of the resource. -1 if no limit on maximum capacity
		inputs_gen["dfGen"][!,:Max_Cap_MWh] = gen_in[!,:Max_Cap_MWh]/ModelScalingFactor # Convert to GWh
		# Limit on maximum charge capacity of the resource. -1 if no limit on maximum capacity
		inputs_gen["dfGen"][!,:Max_Charge_Cap_MW] = gen_in[!,:Max_Charge_Cap_MW]/ModelScalingFactor # Convert to GW

		## Investment cost terms
		# Annualized capacity investment cost of a generation technology
		inputs_gen["dfGen"][!,:Inv_Cost_per_MWyr] = gen_in[!,:Inv_Cost_per_MWyr]/ModelScalingFactor # Convert to $ million/GW/yr with objective function in millions
		# Annualized investment cost of the energy capacity for a storage technology with STOR = 1 or STOR = 2
		inputs_gen["dfGen"][!,:Inv_Cost_per_MWhyr] = gen_in[!,:Inv_Cost_per_MWhyr]/ModelScalingFactor # Convert to $ million/GWh/yr  with objective function in millions
		# Annualized capacity investment cost for the charging portion of a storage technology with STOR = 2
		inputs_gen["dfGen"][!,:Inv_Cost_Charge_per_MWyr] = gen_in[!,:Inv_Cost_Charge_per_MWyr]/ModelScalingFactor # Convert to $ million/GWh/yr  with objective function in millions

		## Fixed O&M cost terms
		# Fixed operations and maintenance cost of a generation or storage technology
		inputs_gen["dfGen"][!,:Fixed_OM_Cost_per_MWyr] = gen_in[!,:Fixed_OM_Cost_per_MWyr]/ModelScalingFactor # Convert to $ million/GW/yr with objective function in millions
		# Fixed operations and maintenance cost of the power aspect of a storage technology of type STOR = 1 or STOR = 2
		inputs_gen["dfGen"][!,:Fixed_OM_Cost_per_MWhyr] = gen_in[!,:Fixed_OM_Cost_per_MWhyr]/ModelScalingFactor # Convert to $ million/GW/yr with objective function in millions
		# Fixed operations and maintenance cost of the charging aspect of a storage technology of type STOR = 2
		inputs_gen["dfGen"][!,:Fixed_OM_Cost_Charge_per_MWyr] = gen_in[!,:Fixed_OM_Cost_Charge_per_MWyr]/ModelScalingFactor # Convert to $ million/GW/yr with objective function in millions

		## Variable O&M cost terms
		# Variable operations and maintenance cost of a generation or storage technology
		inputs_gen["dfGen"][!,:Var_OM_Cost_per_MWh] = gen_in[!,:Var_OM_Cost_per_MWh]/ModelScalingFactor # Convert to $ million/GWh with objective function in millions
		# Variable operations and maintenance cost of the charging aspect of a storage technology with STOR = 2,
		# or variable operations and maintenance costs associated with flexible demand with FLEX = 1
		inputs_gen["dfGen"][!,:Var_OM_Cost_per_MWh_In] = gen_in[!,:Var_OM_Cost_per_MWh_In]/ModelScalingFactor # Convert to $ million/GWh with objective function in millions
		# Cost of providing regulation reserves
		inputs_gen["dfGen"][!,:Reg_Cost] = gen_in[!,:Reg_Cost]/ModelScalingFactor # Convert to $ million/GW with objective function in millions
		# Cost of providing spinning reserves
		inputs_gen["dfGen"][!,:Rsv_Cost] = gen_in[!,:Rsv_Cost]/ModelScalingFactor # Convert to $ million/GW with objective function in millions
	end

	if setup["UCommit"]>=1
		if setup["ParameterScale"] ==1  # Parameter scaling turned on - adjust values of subset of parameter values
			# Cost per MW of nameplate capacity to start a generator
			inputs_gen["dfGen"][!,:Start_Cost_per_MW] = gen_in[!,:Start_Cost_per_MW]/ModelScalingFactor # Convert to $ million/GW with objective function in millions
		end

		# Fuel consumed on start-up (million BTUs per MW per start) if unit commitment is modelled
		start_fuel = convert(Array{Float64}, collect(skipmissing(gen_in[!,:Start_Fuel_MMBTU_per_MW])))
		# Fixed cost per start-up ($ per MW per start) if unit commitment is modelled
		start_cost = convert(Array{Float64}, collect(skipmissing(inputs_gen["dfGen"][!,:Start_Cost_per_MW])))
		inputs_gen["C_Start"] = zeros(Float64, G, inputs_gen["T"])
		inputs_gen["dfGen"][!,:CO2_per_Start] = zeros(Float64, G)
	end

	# Heat rate of all resources (million BTUs/MWh)
	heat_rate = convert(Array{Float64}, collect(skipmissing(gen_in[!,:Heat_Rate_MMBTU_per_MWh])) )
	# Fuel used by each resource
	fuel_type = collect(skipmissing(gen_in[!,:Fuel]))
	# Maximum fuel cost in $ per MWh and CO2 emissions in tons per MWh
	inputs_gen["C_Fuel_per_MWh"] = zeros(Float64, G, inputs_gen["T"])
	inputs_gen["dfGen"][!,:CO2_per_MWh] = zeros(Float64, G)
	for g in 1:G
		# NOTE: When Setup[ParameterScale] =1, fuel costs are scaled in fuels_data.csv, so no if condition needed to scale C_Fuel_per_MWh
		inputs_gen["C_Fuel_per_MWh"][g,:] = fuel_costs[fuel_type[g]].*heat_rate[g]
		inputs_gen["dfGen"][!,:CO2_per_MWh][g] = fuel_CO2[fuel_type[g]]*heat_rate[g]
		if setup["ParameterScale"] ==1
			inputs_gen["dfGen"][!,:CO2_per_MWh][g] = inputs_gen["dfGen"][!,:CO2_per_MWh][g] * ModelScalingFactor
		end
		# kton/MMBTU * MMBTU/MWh = kton/MWh, to get kton/GWh, we need to mutiply 1000
		if g in inputs_gen["COMMIT"]
			# Start-up cost is sum of fixed cost per start plus cost of fuel consumed on startup.
			# CO2 from fuel consumption during startup also calculated

			inputs_gen["C_Start"][g,:] = inputs_gen["dfGen"][!,:Cap_Size][g] * (fuel_costs[fuel_type[g]] .* start_fuel[g] .+ start_cost[g])
			# No need to re-scale C_Start since Cap_size, fuel_costs and start_cost are scaled When Setup[ParameterScale] =1 - Dharik
			inputs_gen["dfGen"][!,:CO2_per_Start][g]  = inputs_gen["dfGen"][!,:Cap_Size][g]*(fuel_CO2[fuel_type[g]]*start_fuel[g])
			if setup["ParameterScale"] ==1
				inputs_gen["dfGen"][!,:CO2_per_Start][g] = inputs_gen["dfGen"][!,:CO2_per_Start][g] * ModelScalingFactor
			end
			# Setup[ParameterScale] =1, inputs_gen["dfGen"][!,:Cap_Size][g] is GW, fuel_CO2[fuel_type[g]] is ktons/MMBTU, start_fuel is MMBTU/MW,
			#   thus the overall is MTons/GW, and thus inputs_gen["dfGen"][!,:CO2_per_Start][g] is Mton, to get kton, change we need to multiply 1000
			# Setup[ParameterScale] =0, inputs_gen["dfGen"][!,:Cap_Size][g] is MW, fuel_CO2[fuel_type[g]] is tons/MMBTU, start_fuel is MMBTU/MW,
			#   thus the overall is MTons/GW, and thus inputs_gen["dfGen"][!,:CO2_per_Start][g] is ton
		end
	end
	println("Generators_data.csv Successfully Read!")

	return inputs_gen
end

max_stars_repo_name: Betristor/LTESOM

max_issues_repo_name: Betristor/LTESOM

max_forks_repo_name: Betristor/LTESOM


text:
function Frequency()
    return Frequency(())
end

function Frequency(arg0::Comparator)
    return Frequency((Comparator,), arg0)
end

function add_value(obj::Frequency, arg0::Comparable)
    return jcall(obj, "addValue", void, (Comparable,), arg0)
end

function clear(obj::Frequency)
    return jcall(obj, "clear", void, ())
end

function entry_set_iterator(obj::Frequency)
    return jcall(obj, "entrySetIterator", JIterator, ())
end

function equals(obj::Frequency, arg0::Object)
    return jcall(obj, "equals", jboolean, (Object,), arg0)
end

function get_class(obj::Object)
    return jcall(obj, "getClass", Class, ())
end

function get_count(obj::Frequency, arg0::Comparable)
    return jcall(obj, "getCount", jlong, (Comparable,), arg0)
end

function get_cum_freq(obj::Frequency, arg0::Comparable)
    return jcall(obj, "getCumFreq", jlong, (Comparable,), arg0)
end

function get_cum_pct(obj::Frequency, arg0::Comparable)
    return jcall(obj, "getCumPct", jdouble, (Comparable,), arg0)
end

function get_mode(obj::Frequency)
    return jcall(obj, "getMode", List, ())
end

function get_pct(obj::Frequency, arg0::Comparable)
    return jcall(obj, "getPct", jdouble, (Comparable,), arg0)
end

function get_sum_freq(obj::Frequency)
    return jcall(obj, "getSumFreq", jlong, ())
end

function get_unique_count(obj::Frequency)
    return jcall(obj, "getUniqueCount", jint, ())
end

function hash_code(obj::Frequency)
    return jcall(obj, "hashCode", jint, ())
end

function increment_value(obj::Frequency, arg0::Comparable, arg1::jlong)
    return jcall(obj, "incrementValue", void, (Comparable, jlong), arg0, arg1)
end

function merge(obj::Frequency, arg0::Collection)
    return jcall(obj, "merge", void, (Collection,), arg0)
end

function merge(obj::Frequency, arg0::Frequency)
    return jcall(obj, "merge", void, (Frequency,), arg0)
end

function notify(obj::Object)
    return jcall(obj, "notify", void, ())
end

function notify_all(obj::Object)
    return jcall(obj, "notifyAll", void, ())
end

function to_string(obj::Frequency)
    return jcall(obj, "toString", JString, ())
end

function values_iterator(obj::Frequency)
    return jcall(obj, "valuesIterator", JIterator, ())
end

function wait(obj::Object)
    return jcall(obj, "wait", void, ())
end

function wait(obj::Object, arg0::jlong)
    return jcall(obj, "wait", void, (jlong,), arg0)
end

function wait(obj::Object, arg0::jlong, arg1::jint)
    return jcall(obj, "wait", void, (jlong, jint), arg0, arg1)
end

ext: jl


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule gmsh_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("gmsh")
JLLWrappers.@generate_main_file("gmsh", UUID("630162c2-fc9b-58b3-9910-8442a8a132e6"))
end  # module gmsh_jll


text:
# File for plotting Figure 3

using Pkg
using DataFrames
using Gadfly
using JLD2

import Cairo, Fontconfig

# Plotting

load_dict = load("data/noise_split_dim.jld2")
p1 = load_dict["plot_df"]
rename!(p1, "approach" => "σ^2")

p = plot(Scale.color_discrete_manual("#E7C15F", "#C33149", "#2A9D8F"), Guide.colorkey(title="σϵ 2"))

push!(p, layer(p1, x=:depth, y=:mean, ymin=:ymin, ymax=:ymax, color="σ^2", Geom.line, Geom.ribbon, alpha=[0.6]))

push!(p, Guide.YLabel("% of splits on noisy variables"))
push!(p, Guide.XLabel("Tree Depth"))
# push!(p, Guide.title("Comparison of approaches"))
push!(p, Theme(line_width=0.6mm))

draw(PNG("figures/graphs/wide_sigmas.png", 20cm, 12cm, dpi=300), p)

max_stars_repo_name: christianhilscher/emma

max_issues_repo_name: christianhilscher/emma

max_forks_repo_name: christianhilscher/emma


text:
"""
Julia program to find the n-th element from Stern's Diatomic Series
Stern's diatomic series is the sequence which generates the integer sequence that arises
in the Calkin-Wilf tree. This sequence can be computed by the fusc function.
"""

function stern_diatomic_num(n)
    if(n == 0)
        return 0
    end

    dp = zeros(Int, n)

    dp[1] = 1
    # Traverse and Fill the `dp` array.
    for i in 2:n
        # If i is even
        if(i % 2 == 0)
            dp[i] = dp[i ÷ 2]
        # If i is odd
        else
            dp[i] = dp[(i - 1) ÷ 2 ] + dp[(i + 1) ÷ 2]
        end
    end
    return dp[n]
end

print("Enter the value of n(where you need the nth Stern's Diatomic number): ")
n = readline()
n = parse(Int, n)
if(n < 0)
    print("Invalid Value of n !!!")
    exit()
end
res = stern_diatomic_num(n)
println("The $n'th Stern's Diatomic is $res.")

"""
Time Complexity: O(n), where 'n' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the value of n(where you need the nth Stern's Diatomic number): 258
The 258'th Stern's Diatomic is 8.

SAMPLE 2
Enter the value of n(where you need the nth Stern's Diatomic number): -98
Invalid Value of n !!!
"""

max_issues_repo_name: adarshnjena/NeoAlgo

max_forks_repo_name: adarshnjena/NeoAlgo


text:
# # Orthocube Examples (Bravais Lattice)

# ## Preamble
using TightBindingLattice
using Plots
mkpath("example_orthocube")

function draw_orthocube(orthocube::OrthoCube, coordinates::AbstractMatrix{<:Integer})
    xlim = (minimum(coordinates[1,:]) - 3.5, maximum(coordinates[1,:]) + 3.5)
    ylim = (minimum(coordinates[2,:]) - 3.5, maximum(coordinates[2,:]) + 3.5)
    boundary = let
        r0 = [0,0]
        r1 = orthocube.shape_matrix[:,1]
        r2 = orthocube.shape_matrix[:,2]
        hcat(r0, r1, r1 .+ r2, r2, r0)
    end
    fig = plot(boundary[1,:], boundary[2,:], label="", size=(400, 400))
    for Ri in Iterators.product(-1:1, -1:1)
        alpha = (Ri == (0,0)) ? 1.0 : 0.1
        Rr = orthocube.shape_matrix * [Ri...]
        scatter!(coordinates[1,:] .+ Rr[1], coordinates[2,:] .+ Rr[2], aspect_ratio=1, markersize=12, xlim=xlim, ylim=ylim, markeralpha=alpha, label="")
        annotation = []
        for i in 1:size(coordinates, 2)
            x = coordinates[1,i] + Rr[1]
            y = coordinates[2,i] + Rr[2]
            if xlim[1] < x < xlim[2] && ylim[1] < y < ylim[2]
                push!(annotation, (x, y, text("$i", 8, :black, :center)))
            end
        end
        if !isempty(annotation)
            annotation = [annotation...]
            annotate!(annotation)
        end
    end
    fig
end

# ## (4,-4) x (4,4)
size_matrix = [ 4 4; -4 4]
orthocube = OrthoCube(size_matrix)
generator_translations = find_generators(orthocube)
coordinates = generate_coordinates(orthocube, generator_translations)
coordmat = hcat(coordinates...)
println("All elements")
for (i, c) in enumerate(coordinates)
    println("$i : $c")
end
println("Generator translations")
for (it, t) in enumerate(eachcol(generator_translations))
    println("t($it) = $t")
end
draw_orthocube(orthocube, coordmat)
savefig("example_orthocube/bravais_(4,-4)x(4,4).svg")

# ![](example_orthocube//bravais_(4,-4)x(4,4).svg)

# ## (2,-2) x (2,4)
size_matrix = [ 2 2; -2 4]
orthocube = OrthoCube(size_matrix)
generator_translations = find_generators(orthocube)
coordinates = generate_coordinates(orthocube, generator_translations)
coordmat = hcat(coordinates...)
draw_orthocube(orthocube, coordmat)
println("All elements")
for (i, c) in enumerate(coordinates)
    println("$i : $c")
end
println("Generator translations")
for (it, t) in enumerate(eachcol(generator_translations))
    println("t($it) = $t")
end
draw_orthocube(orthocube, coordmat)
savefig("example_orthocube/bravais_(2,-2)x(2,4).svg")

# ![](example_orthocube//bravais_(2,-2)x(2,4).svg)


text:
using jInv.Mesh
using Test

# regular mesh
domain = [1.2 2.4 0.0 1.1 0.0 2.3]
n      = [3 4 5]
M3D      = getRegularMesh(domain,n)
display(M3D)
M2D      = getRegularMesh(domain[1:4],n[1:2])
display(M2D)

# tensor mesh
h1 = rand(4)
h2 = rand(5)
h3 = rand(6)
MT = getTensorMesh3D(h1,h2,h3)
display(MT)


text:
using TestImages, FileIO, ImageCore

function main()
    img = Float32.(channelview(testimage("mandril_color")))

    img_shear = clamp01.(shear(img, 150, 2, 3))
    img_rotated = clamp01.(rotate(img, 50, (2, 3)))
    img_rotated2 = clamp01.(rotate(img_rotated, -50, (2, 3)))

    save("../../paper/figures/img_sheared.png", colorview(RGB, img_shear))
    save("../../paper/figures/img_rotated.png", colorview(RGB, img_rotated))
    save("../../paper/figures/img_rotated2.png", colorview(RGB, img_rotated2))
end


text:
# coding: utf-8

# In[1]:

#this is a more advanced knapsack problem
#we have a new variable called groups
#we are only allowed to select at most one item from each group
#please note julia version is a lot more complex than python version
#simply becuz julia starts index at 1 and doesnt allow negative number indexing
#please check the following link for the basic knapsack problem
# https://github.com/je-suis-tm/recursion-and-dynamic-programming/blob/master/knapsack.jl

# In[2]:

#solve multiple choice knapsack via dynamic programming
function knapsack_multichoice(total_weight,values,weights,groups)

    #julia starts index at 1 which is why we use length(values)
    #create a nested list with size of number of items*weights
    array=[[0 for _ in 1:total_weight] for _ in 1:length(values)]
    path=[[[] for _ in 1:total_weight] for _ in 1:length(values)]

    #now we begin our traversal on all elements in matrix
    for i in 1:length(values)
        for j in 1:total_weight

            #-1 doesnt work as index in julia
            #have to find a way to get around
            if i==1
                if weights[1]<=j
                    array[1][j]=values[1]
                    path[1][j]=[1]
                end
                continue
            end

            #this is the part to check if adding item i would exceed the current capacity j
            #if it does,we go to the previous status
            #if not,we shall find out whether adding item i would be the new optimal
            if weights[i]<j

                #initialize
                subset_max=0
                target=1

                #we only select one item from each group
                #we will find the item that maximizes the value in each group
                prev_group=groups[i]-1

                #get column of the matrix
                subset=[row[j-weights[i]] for row in array]

                #find the item that maximizes the value in the previous group
                for k in 1:length(values)
                    if groups[k]==prev_group && subset[k]>subset_max
                        subset_max=subset[k]
                        target=k
                    end
                end

                #dynamic programming
                if subset_max+values[i]>array[i-1][j]
                    array[i][j]=subset_max+values[i]
                    path[i][j]=[path[target][j-weights[i]];[i]]
                elseif subset_max+values[i]==array[i-1][j] && weights[i]<weights[path[i-1][j][end]]
                    array[i][j]=subset_max+values[i]
                    path[i][j]=[path[target][j-weights[i]];[i]]
                else
                    array[i][j]=array[i-1][j]
                    path[i][j]=path[i-1][j]
                end

            elseif weights[i]==j

                #dynamic programming
                if values[i]>array[i-1][j]
                    array[i][j]=values[i]
                    path[i][j]=[i]
                elseif values[i]==array[i-1][j] && weights[i]<weights[path[i-1][j][end]]
                    array[i][j]=values[i]
                    path[i][j]=[i]
                else
                    array[i][j]=array[i-1][j]
                    path[i][j]=path[i-1][j]
                end

            else
                array[i][j]=array[i-1][j]
                path[i][j]=path[i-1][j]
            end
        end
    end
    return array,path
end

# In[3]:

#a simple test
values=[60,80,100,110,120,150]
weights=[10,15,20,25,30,35]
groups=[0,0,1,1,2,2]
total_weight=50

# In[4]:

array,path=knapsack_multichoice(total_weight,values,
                                weights,groups)

println(array[length(weights)][total_weight])
println(path[length(weights)][total_weight])

max_stars_repo_path: knapsack multiple choice.jl

max_issues_repo_path: knapsack multiple choice.jl

max_forks_repo_path: knapsack multiple choice.jl


text:
# This file was generated, do not modify it. # hide
using CSV
data = CSV.read(fpath)


text:
export DEBUG_METADATA_VERSION, strip_debuginfo!

DEBUG_METADATA_VERSION() = API.LLVMDebugMetadataVersion()

strip_debuginfo!(mod::Module) = API.LLVMStripModuleDebugInfo(ref(mod))

if libllvm_version >= v"8.0"
set_subprogram!(func::Function, sp::Metadata) = LLVM.API.LLVMSetSubprogram(ref(func), ref(sp))
get_subprogram(func::Function) = Metadata(LLVM.API.LLVMGetSubprogram(ref(func)))
end


text:
using BenchmarkTools
using SymSpellChecker
using SymSpellChecker: VerbosityALL, VerbosityTOP, VerbosityCLOSEST
using Statistics
using CSV
using DataFrames

ASSETS_PATH = joinpath(@__DIR__, "..", "..", "assets")
function load_noisy()
    map(readlines(joinpath(ASSETS_PATH, "noisy_query_en_1000.txt"))) do x
        String(split(x)[1])
    end
end

dicts = [
    joinpath(ASSETS_PATH, "frequency_dictionary_en_30_000.txt"),
    joinpath(ASSETS_PATH, "frequency_dictionary_en_82_765.txt"),
    joinpath(ASSETS_PATH, "frequency_dictionary_en_500_000.txt"),
]

dict_names = ["30k", "82k", "500k"]

query1k = load_noisy()

prefix_length = 5
max_edit = 2

# df = DataFrame(word = String[], min_val = Float64[], med_val = Float64[], avg_val = Float64[])
const d = SymSpell(dicts[1], max_dictionary_edit_distance = max_edit, prefix_length = prefix_length)

open(joinpath(@__DIR__, "words.csv"), "w") do file
    println(file, "word,min_val,med_val,avg_val")
    flush(file)
    for (i, word) in enumerate(query1k)
        bm = @benchmark lookup($d, $word, verbosity = $VerbosityCLOSEST)
        # push!(df, (word, minimum(bm.times/1000_000), median(bm.times/1000_000), mean(bm.times/1000_000)))
        println(file, "$word,$(minimum(bm.times/1000_000)),$(median(bm.times/1000_000)),$(mean(bm.times/1000_000))")
        flush(file)
        if mod(i, 50) == 0
            @show i
        end
    end
end
# sort!(df, :med_val, rev = true)


text:
# default increase and decrease functions.
function decreaseBase(α::T, TR::TrustRegion) where {T}
    return α * TR.decrease_factor
end

function decrease(X::TPData, α::T, TR::TrustRegion) where {T}
    return decreaseBase(α, TR)
end

function decrease(X::PDataFact, α::T, TR::TrustRegion) where {T}
    X.success = false
    return decreaseBase(α, TR)
end

function decrease(X::PDataKARC, α::Float64, TR::TrustRegion)
    X.indmin += 1
    positives = findall(X.positives)
    p_imin = positives[X.indmin]
    α2 = max(X.norm_dirs[p_imin] / X.shifts[p_imin], eps())

    targetα = α * TR.decrease_factor

    # fix α to its "ideal" value to satisfy αλ=||d||
    # while ensuring α decreases enough
    while α2 > targetα && p_imin < length(positives)
        X.indmin += 1
        p_imin = positives[X.indmin]
        α2 = max(X.norm_dirs[p_imin] / X.shifts[p_imin], eps())
    end

    if p_imin == length(positives)
        @warn "PreProcessKARC failure: α2=$α2"
    end

    X.d = X.xShift[p_imin]
    X.λ = X.shifts[p_imin]

    return α2
end

function decrease(X::PDataKTR, α::Float64, TR::TrustRegion)
    X.indmin += 1
    positives = findall(X.positives)
    p_imin = positives[X.indmin]
    α2 = X.norm_dirs[p_imin]

    # fix α to its "ideal" value to satisfy α=||d||
    # while ensuring α decreases enough
    targetα = α * TR.decrease_factor

    while α2 > targetα && p_imin < length(positives)
        X.indmin += 1
        p_imin = positives[X.indmin]
        α2 = X.norm_dirs[p_imin]
    end

    if p_imin == length(positives)
        @warn "PreProcessKTR failure: α2=$α2"
    end

    X.d = X.xShift[p_imin]
    X.λ = X.shifts[p_imin]

    return α2
end

function increase(α::T, TR::TrustRegion) where {T}
    return min(α * TR.increase_factor, TR.max_α)
end

function increase(X::TPData, α::T, TR::TrustRegion) where {T}
    return increase(α, TR)
end


text:
# test the structs
@info "Testing the FT and NaN of the structs...";
@testset "FT and NaN --- Types" begin
    for FT in [Float32, Float64]
        node   = SPACSimple{FT}();
        cont1L = SPACContainer1L{FT}();
        cont2L = SPACContainer2L{FT}();

        for data in [node, cont1L, cont2L]
            @test FT_test(data, FT);
            @test NaN_test(data);
        end
    end
end

# test and benchmark the big_leaf_partition!
println();
@info "Testing the big_leaf_partition!...";
@testset "SoilPlantAirContinuum --- big_leaf_partition!" begin
    for FT in [Float32, Float64]
        node   = SPACSimple{FT}();
        zenith = FT(30);
        r_all  = FT(1000);

        big_leaf_partition!(node, zenith, r_all);
        @test FT_test(node, FT);
        @test NaN_test(node);
    end
end

# test the gain_risk_map
println();
@info "Testing the gain_risk_map Function...";
@testset "SoilPlantAirContinuum --- gain_risk_map" begin
    for FT in [Float32, Float64]
        node   = SPACSimple{FT}();
        photo  = C3CLM(FT);
        zenith = FT(30);
        r_all  = FT(1000);

        big_leaf_partition!(node, zenith, r_all);
        mat = gain_risk_map(node, photo);
        @test FT_test(mat, FT);
        @test NaN_test(mat);
    end
end

# test and benchmark the leaf_gas_exchange_nonopt!
println();
@info "Testing the leaf_gas_exchange_nonopt! Functions...";
@testset "SoilPlantAirContinuum --- leaf_gas_exchange_nonopt!" begin
    for FT in [Float32, Float64]
        node   = SPACSimple{FT}();
        photo  = C3CLM(FT);
        zenith = FT(30);
        r_all  = FT(1000);
        flow   = FT(4);
        f_sl   = FT(2.5);
        f_sh   = FT(1.5);

        big_leaf_partition!(node, zenith, r_all);
        leaf_gas_exchange_nonopt!(node, photo, flow);
        @test FT_test(node, FT);
        @test NaN_test(node);
        leaf_gas_exchange_nonopt!(node, photo, f_sl, f_sh);
        @test FT_test(node, FT);
        @test NaN_test(node);
    end
end

# test and benchmark the leaf_gas_exchange!
println();
@info "Testing the leaf_gas_exchange! Functions...";
@testset "SoilPlantAirContinuum --- leaf_gas_exchange!" begin
    for FT in [Float32, Float64]
        node   = SPACSimple{FT}();
        photo  = C3CLM(FT);
        zenith = FT(30);
        r_all  = FT(1000);
        flow   = FT(4);
        f_sl   = FT(2.5);
        f_sh   = FT(1.5);

        big_leaf_partition!(node, zenith, r_all);
        leaf_gas_exchange!(node, photo, flow);
        @test FT_test(node, FT);
        @test NaN_test(node);
        leaf_gas_exchange!(node, photo, f_sl, f_sh);
        @test FT_test(node, FT);
        @test NaN_test(node);
    end
end

# test and benchmark the leaf_temperature*
println();
@info "Testing the leaf_temperature* Functions...";
@testset "SoilPlantAirContinuum --- leaf_temperature*" begin
    for FT in [Float32, Float64]
        node = SPACSimple{FT}();
        rad  = FT(300);
        flow = FT(4);

        for result in [ leaf_temperature(node, rad, flow),
                        leaf_temperature_shaded(node, rad, flow),
                        leaf_temperature_sunlit(node, rad, flow) ]
            @test FT_test(result, FT);
            @test NaN_test(result);
        end
    end
end

# test and benchmark the optimize_flows!
println();
@info "Testing the optimize_flows! Functions...";
@testset "SoilPlantAirContinuum --- optimize_flows!" begin
    for FT in [Float32, Float64]
        node   = SPACSimple{FT}();
        photo  = C3CLM(FT);
        zenith = FT(30);
        r_all  = FT(1000);

        big_leaf_partition!(node, zenith, r_all);
        optimize_flows!(node, photo);
        @test FT_test(node, FT);
        @test NaN_test(node);
    end
end

# test and benchmark the atmosheric* functions
println();
@info "Testing the atmosheric* Functions...";
@testset "SoilPlantAirContinuum --- atmosheric*" begin
    for FT in [Float32, Float64]
        h = FT(1000);

        for result in [ atmospheric_pressure(h),
                        atmospheric_pressure_ratio(h),
                        ppm_to_Pa(h) ]
            @test FT_test(result, FT);
            @test NaN_test(result);
        end
    end
end

# test and benchmark the zenith_angle
println();
@info "Testing the zenith_angle Functions...";
@testset "SoilPlantAirContinuum --- zenith_angle" begin
    for FT in [Float32, Float64]
        latd = FT(10);
        decd = FT(10);
        lhad = FT(10);
        day  = FT(100)
        hour = FT(13)
        minu = FT(30)

        for result in [ zenith_angle(latd, decd, lhad),
                        zenith_angle(latd, day, hour),
                        zenith_angle(latd, day, hour, minu) ]
            @test FT_test(result, FT);
            @test NaN_test(result);
        end
    end
end

# test and benchmark the annual_profit
println();
@info "Testing the annual_profit Functions...";
@testset "SoilPlantAirContinuum --- annual_profit" begin
    arti = artifact"2020_leaf_invest_weather" *  "/gs_sample.csv";
    weat = DataFrame(CSV.File(arti));
    for FT in [Float32, Float64]
        node    = SPACSimple{FT}();
        photo   = C3CLM(FT);
        weatmat = Matrix{FT}(weat);

        gscp = annual_profit(node, photo, weatmat);
        @test FT_test(gscp, FT);
        @test NaN_test(gscp);
    end
end

# test and benchmark the annual_simulation!
println();
@info "Testing annual_simulation! Functions...";
@testset "SoilPlantAirContinuum --- annual_simulation!" begin
    arti = artifact"2020_leaf_invest_weather" *  "/gs_sample.csv";
    weat = DataFrame(CSV.File(arti));
    for FT in [Float32, Float64]
        node  = SPACSimple{FT}();
        photo = C3CLM(FT);
        df    = create_dataframe(FT, weat);

        annual_simulation!(node, photo, weat, df);
        @test FT_test(node, FT);
        @test NaN_test(node);
    end
end

# test and benchmark the leaf_allocation!
println();
@info "Testing the leaf_allocation! Functions...";
@testset "SoilPlantAirContinuum --- leaf_allocation!" begin
    for FT in [Float32, Float64]
        node  = SPACSimple{FT}();
        photo = C3CLM(FT);
        laba  = FT(1000);
        vmax  = FT(80);

        leaf_allocation!(node, laba);
        @test FT_test(node, FT);
        @test NaN_test(node);
        leaf_allocation!(node, photo, vmax);
        @test FT_test(node, FT);
        @test NaN_test(node);
        leaf_allocation!(node, photo, laba, vmax);
        @test FT_test(node, FT);
        @test NaN_test(node);
    end
end

# test and benchmark the optimize_leaf
println();
@info "Testing the optimize_leaf! Functions...";
@testset "SoilPlantAirContinuum --- optimize_leaf!" begin
    arti = artifact"2020_leaf_invest_weather" *  "/gs_sample.csv";
    weat = DataFrame(CSV.File(arti));
    for FT in [Float32, Float64]
        node    = SPACSimple{FT}();
        photo   = C3CLM(FT);
        weatmat = Matrix{FT}(weat);

        optimize_leaf!(node, photo, weatmat);
        @test FT_test(node, FT);
        @test NaN_test(node);
    end
end

# test the function to vary SPACSimple
println();
@info "Testing the vary_spac! Functions...";
@testset "SoilPlantAirContinuum --- vary_spac!" begin
    arti = artifact"2020_leaf_invest_weather" *  "/gs_sample.csv";
    weat = DataFrame(CSV.File(arti));
    facs = ["kl", "kw", "wb", "wc", "wk",
            "cc", "cv", "gm",
            "ga", "sd",
            "ta", "rh", "ca"];
    for FT in [Float32, Float64]
        node = SPACSimple{FT}();
        for _fac in facs
            vary_spac!(node, weat, _fac, FT(1.5));
            @test true;
        end
    end
end

# test the function for mSCOPE version radiation
println();
@info "Testing the mSCOPE verion setup...";
@testset "SoilPlantAirContinuum --- vary_spac!" begin
    for FT in [Float32, Float64]
        node = SPACMono{FT}();
        initialize_spac_canopy!(node);
        layer_fluxes!(node);
        @test NaN_test(node);
    end
end

max_stars_repo_name: bbuman/Land

max_issues_repo_name: bbuman/Land

max_forks_repo_name: bbuman/Land


text:
# syntax: proto3
using ProtoBuf
import ProtoBuf.meta

struct __enum_LogMessage_Level <: ProtoEnum
    UNKNOWN::Int32
    DEBUG::Int32
    INFO::Int32
    WARN::Int32
    ERROR::Int32
    FATAL::Int32
    __enum_LogMessage_Level() = new(0,10,20,30,40,50)
end #struct __enum_LogMessage_Level
const LogMessage_Level = __enum_LogMessage_Level()

mutable struct LogMessage <: ProtoType
    level::Int32
    message::AbstractString
    LogMessage(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct LogMessage

struct __enum_SessionLog_SessionStatus <: ProtoEnum
    STATUS_UNSPECIFIED::Int32
    START::Int32
    STOP::Int32
    CHECKPOINT::Int32
    __enum_SessionLog_SessionStatus() = new(0,1,2,3)
end #struct __enum_SessionLog_SessionStatus
const SessionLog_SessionStatus = __enum_SessionLog_SessionStatus()

mutable struct SessionLog <: ProtoType
    status::Int32
    checkpoint_path::AbstractString
    msg::AbstractString
    SessionLog(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct SessionLog

mutable struct TaggedRunMetadata <: ProtoType
    tag::AbstractString
    run_metadata::Array{UInt8,1}
    TaggedRunMetadata(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct TaggedRunMetadata

mutable struct Event <: ProtoType
    wall_time::Float64
    step::Int64
    file_version::AbstractString
    graph_def::Array{UInt8,1}
    summary::Summary
    log_message::LogMessage
    session_log::SessionLog
    tagged_run_metadata::TaggedRunMetadata
    Event(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)
end #mutable struct Event
const __oneofs_Event = Int[0,0,1,1,1,1,1,1]
const __oneof_names_Event = [Symbol("what")]
meta(t::Type{Event}) = meta(t, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, true, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, __oneofs_Event, __oneof_names_Event, ProtoBuf.DEF_FIELD_TYPES)

export Event, LogMessage_Level, LogMessage, SessionLog_SessionStatus, SessionLog, TaggedRunMetadata


text:
# Testing of samplers

using Distributions
using Base.Test

import Distributions:
    CategoricalDirectSampler,
    AliasTable,
    BinomialGeomSampler,
    BinomialTPESampler,
    BinomialPolySampler,
    BinomialAliasSampler,
    PoissonADSampler,
    PoissonCountSampler,
    ExponentialSampler,
    GammaGDSampler,
    GammaGSSampler,
    GammaMTSampler,
    GammaIPSampler,
    PoissBinAliasSampler

n_tsamples = 10^6

## Categorical samplers

@test_throws ErrorException CategoricalDirectSampler(Float64[])
@test_throws ErrorException AliasTable(Float64[])

for S in [CategoricalDirectSampler, AliasTable]
    println("    testing $S")
    for p in Any[[1.0], [0.3, 0.7], [0.2, 0.3, 0.4, 0.1]]
        test_samples(S(p), Categorical(p), n_tsamples)
    end
end

## Binomial samplers

binomparams = [(0, 0.4), (0, 0.6), (5, 0.0), (5, 1.0),
               (1, 0.2), (1, 0.8), (3, 0.4), (4, 0.6),
               (40, 0.5), (100, 0.4), (300, 0.6)]

for (S, paramlst) in [
    (BinomialGeomSampler, [(0, 0.4), (0, 0.6), (5, 0.0), (5, 1.0), (1, 0.2), (1, 0.8), (3, 0.4), (4, 0.6)]),
    (BinomialTPESampler, [(40, 0.5), (100, 0.4), (300, 0.6)]),
    (BinomialPolySampler, binomparams),
    (BinomialAliasSampler, binomparams) ]

    println("    testing $S")
    for pa in paramlst
        n, p = pa
        test_samples(S(n, p), Binomial(n, p), n_tsamples)
    end
end

## Poisson samplers

for (S, paramlst) in [
    (PoissonCountSampler, [0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 15.0, 20.0, 30.0]),
    (PoissonADSampler, [5.0, 10.0, 15.0, 20.0, 30.0])]

    println("    testing $S")
    for μ in paramlst
        test_samples(S(μ), Poisson(μ), n_tsamples)
    end
end

## Poisson Binomial sampler
S = PoissBinAliasSampler
paramlst = (fill(0.2, 30), linspace(0.1, .99, 30), [fill(0.1, 10); fill(0.9, 10)])
println("    testing $S")
for p in paramlst
    test_samples(S(p), PoissonBinomial(p), n_tsamples)
end

## Exponential samplers

for S in [ExponentialSampler]
    println("    testing $S")
    for scale in [1.0, 2.0, 3.0]
        test_samples(S(scale), Exponential(scale), n_tsamples)
    end
end

## Gamma samplers
# shape >= 1
for S in [GammaGDSampler, GammaMTSampler]
    println("    testing $S")
    for d in [Gamma(1.0, 1.0), Gamma(2.0, 1.0), Gamma(3.0, 1.0),
               Gamma(1.0, 2.0), Gamma(3.0, 2.0), Gamma(100.0, 2.0)]
        test_samples(S(d), d, n_tsamples)
    end
end

# shape < 1
for S in [GammaGSSampler, GammaIPSampler]
    println("    testing $S")
    for d in [Gamma(0.1,1.0),Gamma(0.9,1.0)]
        test_samples(S(d), d, n_tsamples)
    end
end


text:
module TestCandidate

import Wordle
import Test: @test, @test_throws

c = Wordle.Candidate("alone")
@test c.chars === ('a', 'l', 'o', 'n', 'e')
@test String(c) === "alone"

# Too short
@test_throws Exception Candidate("true")

# Not all lowercase
@test_throws Exception Candidate("Alone")

# Not all ASCII
@test_throws Exception Candidate("señor")

end # module


text:
"""
	Levenberg-Marquardt
		(damped least squares)
"""
function levenberg_marquardt(res::Function, x;
		reg = 1.0e-8, tol_r = 1.0e-8, tol_d = 1.0e-6)

	y = copy(x)
	Δy = copy(x)

	merit(z) = res(z)' * res(z)

	α = 1.0
	iter = 0

	while iter < 100
		me = merit(y)
		r = res(y)
		∇r = ForwardDiff.jacobian(res, y)

		_H = ∇r' * ∇r
		Is = Diagonal(diag(_H))
		H = (_H + reg * Is)

		pd_iter = 0
		while !isposdef(Hermitian(Array(H)))
			reg *= 2.0
			H = (_H + reg * Is)
			pd_iter += 1

			if pd_iter > 100 || reg > 1.0e12
				@error "regularization failure"
			end
		end

		try
			Δy = -1.0 * H \ (∇r' * r)
		catch
			@warn "implicit-function theorem failure"
			return y
		end

		ls_iter = 0
		while merit(y + α * Δy) > me + 1.0e-4 * (∇r' * r)' * (α * Δy)
			α *= 0.5
			reg = reg
			ls_iter += 1

			if ls_iter > 100 || reg > 1.0e12
				@error "line search failure"
			end
		end

		y .+= α * Δy
		α = min(1.2 * α, 1.0)
		reg = 0.5 * reg

		iter += 1

		norm(α * Δy, Inf) < tol_d && (return y)
		norm(r, Inf) < tol_r && (return y)
	end

	@warn "Gauss Newton failure"
	return y
end


text:
@testset "Eigenvalues of interval matrices" begin

    # symmetrix matrix
    A = Symmetric([-1 0 -1..1;
         0 -1 -1..1;
         -1..1 -1..1 0.1])

    evrohn = eigenbox(A)
    @test interval_isapprox(evrohn, -2.4143..1.5143; atol=1e-3)

    evhertz = eigenbox(A, Hertz())
    @test interval_isapprox(evhertz, -1.9674..1.0674; atol=1e-3)

    # real matrix
    A = [-3.. -2 4..5 4..6 -1..1.5;
         -4.. -3 -4.. -3 -4.. -3 1..2;
         -5.. -4 2..3 -5.. -4 -1..0;
         -1..0.1 0..1 1..2 -4..2.5]

    ev = eigenbox(A)
    @test interval_isapprox(real(ev), -8.8221..3.4408; atol=1e-3)
    @test interval_isapprox(imag(ev), -10.7497..10.7497; atol=1e-3)

    evhertz = eigenbox(A, Hertz())
    @test interval_isapprox(real(evhertz), -7.3691..3.2742; atol=1e-3)
    @test interval_isapprox(imag(evhertz), -8.794..8.794; atol=1e-3)

    # hermitian matrix
    A = Hermitian([1..2 (5..9)+(2..5)*im (3..5)+(2..4)im;
        (5..9)+(-5.. -2)*im 2..3 (7..8)+(6..10)im;
        (3..5)+(-4.. -2)*im (7..8)+(-10.. -6)*im 3..4])

    ev = eigenbox(A)
    @test interval_isapprox(ev, -15.4447..24.3359; atol=1e-3)

    # complex matrix
    A = [(1..2)+(3..4)*im 3..4;1+(2..3)*im 4..5]

    ev = eigenbox(A)
    @test interval_isapprox(real(ev), -1.28812..7.28812; atol=1e-3)
    @test interval_isapprox(imag(ev), -2.04649..5.54649; atol=1e-3)
end


text:
using BinaryProvider # requires BinaryProvider 0.3.0 or later

include("compile.jl")

# env var to force compilation from source, for testing purposes
const force_compile = get(ENV, "FORCE_COMPILE_HDF5", "no") == "yes"

# Parse some basic command-line arguments
const verbose = "--verbose" in ARGS
const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr")))
products = [
    LibraryProduct(prefix, ["libhdf5"], :libhdf5),
    LibraryProduct(prefix, ["libhdf5_hl"], :libhdf5_hl),
]

verbose && force_compile && @info("Forcing compilation from source.")

# Download binaries from hosted location
bin_prefix = "https://github.com/JuliaPackaging/Yggdrasil/releases/download/HDF5-v1.10.5+4"

# Listing of files generated by BinaryBuilder:
download_info = Dict(
    Linux(:i686, libc=:glibc) => ("$bin_prefix/HDF5.v1.10.5.i686-linux-gnu.tar.gz", "f290ce45ee19c5cef8eb0895a891bee4912212eec0d6679d14e6d0765c222d4d"),
    Windows(:i686) => ("$bin_prefix/HDF5.v1.10.5.i686-w64-mingw32.tar.gz", "64b57b9db79f8f2c1eb2296256bd1ff1dae17acc0114ed099a0c349bfffe2373"),
    MacOS(:x86_64) => ("$bin_prefix/HDF5.v1.10.5.x86_64-apple-darwin14.tar.gz", "e08e5f4fb408776511617e971e4eb7cd40e6a8d75270b4abc244d493601c7928"),
    Linux(:x86_64, libc=:glibc) => ("$bin_prefix/HDF5.v1.10.5.x86_64-linux-gnu.tar.gz", "ed551bbb4e05d93a46580fd77c74002ed378c6e785160e4ed1095f862d15e686"),
    Windows(:x86_64) => ("$bin_prefix/HDF5.v1.10.5.x86_64-w64-mingw32.tar.gz", "f191f6befb2505c99a90168357b749b745744a0c1c1710f28356da1c380d038b"),
)

# source code tarball and hash for fallback compilation
source_url = "https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.10/hdf5-1.10.5/src/hdf5-1.10.5.tar.gz"
source_hash = "6d4ce8bf902a97b050f6f491f4268634e252a63dadd6656a1a9be5b7b7726fa8"

# Install unsatisfied or updated dependencies:
unsatisfied = any(!satisfied(p; verbose=verbose) for p in products)
dl_info = choose_download(download_info, platform_key_abi())

# If we have a download, and we are unsatisfied (or the version we're
# trying to install is not itself installed) then load it up!
if dl_info !== nothing && unsatisfied || !isinstalled(dl_info...; prefix=prefix) && !force_compile
    # Download and install binaries
    install(dl_info...; prefix=prefix, force=true, verbose=verbose)

    # check again whether the dependency is satisfied, which
    # may not be true if dlopen fails due to a libc++ incompatibility
    unsatisfied = any(!satisfied(p; verbose=verbose) for p in products)
end

if dl_info === nothing && unsatisfied || force_compile
    # If we don't have a compatible .tar.gz to download
    # fall back to building from source, giving the library a different name
    # so that it is not overwritten by BinaryBuilder downloads or vice-versa.
    Sys.iswindows() && error("Manual compilation mode from source is not available for this platform.")
    verbose && @info("Building from source for your platform (\"$(Sys.MACHINE)\", parsed as \"$(triplet(platform_key_abi()))\").")

    libname = "libhdf5_from_src"
    products = [
        LibraryProduct(prefix, [libname], :libhdf5)
        LibraryProduct(prefix, [libname*"_hl"], :libhdf5_hl)
    ]
    source_path = joinpath(prefix, "downloads", "src.tar.gz")
    if !isfile(source_path) || !verify(source_path, source_hash; verbose=verbose) || unsatisfied
        compile(libname, source_url, source_hash, prefix=prefix, verbose=verbose)
    end
end

# Write out a deps.jl file that will contain mappings for our products
write_deps_file(joinpath(@__DIR__, "deps.jl"), products, verbose=verbose)


text:
#=
Case folding for UTF-16 encoded strings

Copyright 2018 Gandalf Software, Inc., Scott P. Jones
Licensed under MIT License, see LICENSE.md
=#

# These are more complex, and maybe belong in a separate UTF16Str.jl package

function _lower(::Type{<:Str{UTF16CSE}}, beg, off, len)
    buf, out = _allocate(UInt16, len)
    unsafe_copyto!(out, beg, len)
    fin = out + (len<<1)
    out += off
    while out < fin
        ch = get_codeunit(out)
        if ch <= 0x7f
            _isupper_a(ch) && set_codeunit!(out, ch += 0x20)
        elseif ch <= 0xff
            _isupper_l(ch) && set_codeunit!(out, ch += 0x20)
        elseif is_surrogate_trail(ch)
            # pick up previous code unit (lead surrogate)
            cp = get_supplementary(get_codeunit(out - 2), ch)
            if _isupper_u(cp)
                w1, w2 = get_utf16(_lowercase_u(cp))
                set_codeunit!(out - 2, w1)
                set_codeunit!(out,     w2)
            end
        elseif _isupper_u(ch)
            set_codeunit!(out, _lowercase_u(ch))
        end
        out += 2
    end
    Str(UTF16CSE, buf)
end

function lowercase(str::Str{UTF16CSE})
    @preserve str begin
        pnt = beg = pointer(str)
        fin = beg + sizeof(str)
        while pnt < fin
            ch = get_codeunit(pnt)
            prv = pnt
            (ch > 0xd7ff # May be surrogate pair
             ? _isupper_u(ch > 0xdfff ? ch%UInt32 : get_supplementary(ch, get_codeunit(pnt += 2)))
             : (is_ascii(ch)
                ? _isupper_a(ch)
                : (is_latin(ch) ? _isupper_l(ch) : _isupper_u(ch)))) &&
                    return _lower(UTF16Str, beg, prv-beg, ncodeunits(str))
            pnt += 2
        end
    end
    str
end

function _upper(::Type{<:Str{UTF16CSE}}, beg, off, len)
    buf, out = _allocate(UInt16, len)
    unsafe_copyto!(out, beg, len)
    fin = out + (len<<1)
    out += off
    while out < fin
        ch = get_codeunit(out)
        if is_ascii(ch)
            _islower_a(ch) && set_codeunit!(out, ch -= 0x20)
        elseif is_latin(ch)
            if _can_upper_l(ch)
                set_codeunit!(out, ch -= 0x20)
            elseif ch == 0xb5
                set_codeunit!(out, 0x39c)
            elseif ch == 0xff
                set_codeunit!(out, 0x178)
            end
        elseif is_surrogate_trail(ch)
            # pick up previous code unit (lead surrogate)
            cp = get_supplementary(get_codeunit(out - 2), ch)
            if _cat(cp) == Uni.LL
                w1, w2 = get_utf16(_uppercase_u(cp))
                set_codeunit!(out - 2, w1)
                set_codeunit!(out,     w2)
            end
        elseif _cat(ch) == Uni.LL
            set_codeunit!(out, _uppercase_u(ch))
        end
        out += 2
    end
    Str(UTF16CSE, buf)
end

function uppercase(str::UTF16Str)
    @preserve str begin
        pnt = beg = pointer(str)
        fin = beg + sizeof(str)
        while pnt < fin
            ch = get_codeunit(pnt)
            prv = pnt
            (ch > 0xd7ff # May be surrogate pair
             ? _islower_u(ch > 0xdfff ? ch%UInt32 : get_supplementary(ch, get_codeunit(pnt += 2)))
             : _can_upper_ch(ch)) &&
                 return _upper(UTF16Str, beg, prv-beg, ncodeunits(str))
            pnt += 2
        end
    end
    str
end


text:
using AutoViz
using Colors

#############################################################
# Radar Sensor

type RadarSensor
    angles::Vector{Float64}
    ranges::Vector{Float64}
    range_rates::Vector{Float64}
    max_range::Float64
    poly::ConvexPolygon
end
function RadarSensor(nbeams::Int;
    max_range::Float64=100.0,
    angle_offset::Float64=0.0,
    )
    angles = collect(linspace(angle_offset,2*pi+angle_offset,nbeams+1))[2:end]
    ranges = Array(Float64, nbeams)
    range_rates = Array(Float64, nbeams)
    RadarSensor(angles, ranges, range_rates, max_range, ConvexPolygon(4))
end
function observe!(radar::RadarSensor, scene::Scene, roadway::Roadway, vehicle_index::Int)
    state_ego = scene[vehicle_index].state
    egoid = scene[vehicle_index].def.id
    ego_vel = polar(state_ego.v, state_ego.posG.θ)
    for (i,angle) in enumerate(radar.angles)
        ray_angle = state_ego.posG.θ + angle
        ray_vec = polar(1.0, ray_angle)
        ray = VecSE2(state_ego.posG.x, state_ego.posG.y, ray_angle)

        range = radar.max_range
        range_rate = 0.0
        for veh in scene
            if veh.def.id != egoid
                to_oriented_bounding_box!(radar.poly, veh)
                range2 = AutomotiveDrivingModels.get_collision_time(ray, radar.poly, 1.0)
                if !isnan(range2) && range2 < range
                    range = range2
                    relative_speed = polar(veh.state.v, veh.state.posG.θ) - ego_vel
                    range_rate = proj(relative_speed, ray_vec, Float64)
                end
            end
        end
        radar.ranges[i] = range
        radar.range_rates[i] = range_rate
    end

    radar
end
function render_radar!(rendermodel::RenderModel, radar::RadarSensor, posG::VecSE2;
    color::Colorant=colorant"white",
    line_width::Float64 = 0.05,
    )

    for (angle, range, range_rate) in zip(radar.angles, radar.ranges, radar.range_rates)
        ray = VecSE2(posG.x, posG.y, posG.θ + angle)
        t = 2 / (1 + exp(-range_rate))
        ray_color = t > 1.0 ? lerp(RGBA(1.0,1.0,1.0,0.5), RGBA(0.2,0.2,1.0,0.5), t/2) :
                              lerp(RGBA(1.0,0.2,0.2,0.5), RGBA(1.0,1.0,1.0,0.5), t)
        render_ray!(rendermodel::RenderModel, ray, color=ray_color, length=range, line_width=line_width)
    end
    rendermodel
end

#############################################################
# Road Line Radar Sensor

type RoadlineRadarSensor
    angles::Vector{Float64}
    ranges::Matrix{Float64} # [n_lanes by nbeams]
    max_range::Float64
    poly::ConvexPolygon
end
function RoadlineRadarSensor(nbeams::Int;
    max_range::Float64=100.0,
    max_depth::Int=2,
    angle_offset::Float64=0.0,
    )

    angles = collect(linspace(angle_offset,2*pi+angle_offset,nbeams+1))[2:end]
    ranges = Array(Float64, max_depth, nbeams)
    RoadlineRadarSensor(angles, ranges, max_range, ConvexPolygon(4))
end
function _update_radar!(radar::RoadlineRadarSensor, ray, p_lo, p_hi, beam_index)
    test_range = get_collision_time(ray, AutomotiveDrivingModels.LineSegment(p_lo, p_hi), 1.0)

    n_ranges = size(radar.ranges, 1)
    if !isnan(test_range)
        for k in 1 : n_ranges
            if test_range < radar.ranges[k,beam_index]
                for l in k+1 : n_ranges
                    radar.ranges[l,beam_index] = radar.ranges[l-1,beam_index]
                end
                radar.ranges[k,beam_index] = test_range
                break
            end
        end
    end
    radar
end
function observe!(radar::RoadlineRadarSensor, scene::Scene, roadway::Roadway, vehicle_index::Int)
    state_ego = scene[vehicle_index].state
    egoid = scene[vehicle_index].def.id
    ego_vel = polar(state_ego.v, state_ego.posG.θ)

    fill!(radar.ranges, radar.max_range)
    for (i,angle) in enumerate(radar.angles)
        ray_angle = state_ego.posG.θ + angle
        ray_vec = polar(1.0, ray_angle)
        ray = VecSE2(state_ego.posG.x, state_ego.posG.y, ray_angle)

        for seg in roadway.segments
            for lane in seg.lanes

                N = length(lane.curve)
                halfwidth = lane.width/2

                # always render the left lane marking
                p_lo = convert(VecE2, lane.curve[1].pos + polar(halfwidth, lane.curve[1].pos.θ + π/2))
                for j in 2:length(lane.curve)
                    p_hi = convert(VecE2, lane.curve[j].pos + polar(halfwidth, lane.curve[j].pos.θ + π/2))
                    _update_radar!(radar, ray, p_lo, p_hi, i)
                    p_lo = p_hi
                end
                if has_next(lane)
                    lane2 = next_lane(lane, roadway)
                    pt = lane2.curve[1]
                    p_hi = convert(VecE2, pt.pos + polar(lane2.width/2, pt.pos.θ + π/2))
                    _update_radar!(radar, ray, p_lo, p_hi, i)
                end

                # only check the right lane marking if this is the first lane
                if lane.tag.lane == 1
                    p_lo = convert(VecE2, lane.curve[1].pos + polar(halfwidth, lane.curve[1].pos.θ - π/2))
                    for j in 2:length(lane.curve)
                        p_hi = convert(VecE2, lane.curve[j].pos + polar(halfwidth, lane.curve[j].pos.θ - π/2))
                        _update_radar!(radar, ray, p_lo, p_hi, i)
                        p_lo = p_hi
                    end
                    if has_next(lane)
                        lane2 = next_lane(lane, roadway)
                        pt = lane2.curve[1]
                        p_hi = convert(VecE2, pt.pos + polar(lane2.width/2, pt.pos.θ - π/2))
                        _update_radar!(radar, ray, p_lo, p_hi, i)
                    end
                end
            end
        end
    end

    radar
end
function render_radar!(rendermodel::RenderModel, radar::RoadlineRadarSensor, posG::VecSE2;
    color::Colorant=RGBA(1.0,1.0,1.0,0.5),
    line_width::Float64 = 0.05,
    depth_level::Int = 1, # if 1, render first lanes struck by beams, if 2 render 2nd ...
    )

    for (angle, range) in zip(radar.angles, radar.ranges[depth_level,:])
        ray = VecSE2(posG.x, posG.y, posG.θ + angle)
        render_ray!(rendermodel::RenderModel, ray, color=color, length=range, line_width=line_width)
    end
    rendermodel
end

#############################################################
# Feature Extraction

const RADAR = RadarSensor(200, max_range=100.0, angle_offset=-π) # car distances and range rates
const LINERADAR = RoadlineRadarSensor(200, max_range=100.0, angle_offset=-π, max_depth=3) # lane edges
const N_FEATURES = 2*length(RADAR.ranges) + length(LINERADAR.ranges)
function AutomotiveDrivingModels.pull_features!{Fl<:AbstractFloat}(features::Array{Fl}, rec::SceneRecord, roadway::Roadway, vehicle_index::Int, pastframe::Int=0;
    radar::RadarSensor = RADAR,
    lineradar::RoadlineRadarSensor = LINERADAR,
    )

    #=
    let N = length(radar.ranges)
    let M = size(lineradar.ranges, 2)
    let max_depth = size(lineradar.ranges, 1)

    1 : N is the radar ranges; distance to the struck object, maxes out
    N+1 : 2N is the radar range rates
    2N+1 : 2N + M is line radar ranges at depth 1
    2N+M+1 : 2N + 2M is line radar ranges at depth 2
    ...
    2N+(max_depth-1)×M+1 : 2N + max_depth×M is line radar ranges at depth max_depth
    =#

    scene = get_scene(rec, pastframe)

    observe!(radar, scene, roadway, vehicle_index)
    observe!(lineradar, scene, roadway, vehicle_index)

    N = length(radar.ranges)
    M = size(lineradar.ranges, 2)
    max_depth = size(lineradar.ranges, 1)

    copy!(features, 1, radar.ranges, 1)
    copy!(features, N+1, radar.range_rates, 1)
    copy!(features, 2N+1, lineradar.ranges, 1)

    if findfirst(v->isnan(v), features) != 0
        error("feature $(findfirst(v->isnan(v), features)) is nan")
    end

    features
end

max_stars_repo_name: yoshihikokuwahara/gail-driver

max_issues_repo_name: yoshihikokuwahara/gail-driver

max_forks_repo_name: yoshihikokuwahara/gail-driver


text:
using SymbolicIntegration, SymbolicUtils
@syms x

#Integration Test Problems from
#https://rulebasedintegration.org/testProblems.html

#1 Algebraic functions\1.3 Miscellaneous\1.3.1 Rational functions.input
#Problems from Calculus textbooks and competitions
problems = [
#Ayres Calculus, 1964 edition
[(3*x-4*x^2+3*x^3)//(1+x^2),x,4,"-4*x+3/2*x^2+4*atan(x)"],
[(5+3*x)//(1-x-x^2+x^3),x,3,"4/(1-x)+atanh(x)"],
[(-1-x-x^3+x^4)//(-x^2+x^3),x,3,"(-1)/x+1/2*x^2-2*log(1-x)+2*log(x)"],
[(2+x+x^2+x^3)//(2+3*x^2+x^4),x,6,"atan(x)+1/2*log(2+x^2)"],
[(-4+8*x-4*x^2+4*x^3-x^4+x^5)//(2+x^2)^3,x,5,"(-1)/(2+x^2)^2+1/2*log(2+x^2)-atan(x/sqrt(2))/sqrt(2)"],
[(-1-3*x+x^2)//(-2*x+x^2+x^3),x,3,"-log(1-x)+1/2*log(x)+3/2*log(2+x)"],
[(3-x+3*x^2-2*x^3+x^4)//(3*x-2*x^2+x^3),x,4,"1/2*x^2+log(x)-1/2*log(3-2*x+x^2)"],
[(-1+x+x^3)//(1+x^2)^2,x,4,"-1/2*x/(1+x^2)-1/2*atan(x)+1/2*log(1+x^2)"],
[(1+2*x-x^2+8*x^3+x^4)//((x+x^2)*(1+x^3)),x,7,"(-3)/(1+x)+log(x)-2*log(1+x)+log(1-x+x^2)-2*atan((1-2*x)/sqrt(3))/sqrt(3)"],
[(15-5*x+x^2+x^3)//((5+x^2)*(3+2*x+x^2)),x,7,"1/2*log(3+2*x+x^2)+5*atan((1+x)/sqrt(2))/sqrt(2)-atan(x/sqrt(5))*sqrt(5)"],
[(-3+25*x+23*x^2+32*x^3+15*x^4+7*x^5+x^6)//((1+x^2)^2*(2+x+x^2)^2),x,6,"(-3)/(1+x^2)+1/(2+x+x^2)+log(1+x^2)-log(2+x+x^2)"],

#Edwards and Penney Calculus
[1//((1+x^2)*(4+x^2)),x,3,"-1/6*atan(1/2*x)+1/3*atan(x)"],
#[(a+b*x^3)//(1+x^2),x,5,"1/2*b*x^2+a*atan(x)-1/2*b*log(1+x^2)"],
[(x+x^2)//((4+x)*(-4+x^2)),x,4,"-1/2*atanh(1/2*x)+log(4+x)"],
[(4+x^2)//((1+x^2)*(2+x^2)),x,3,"3*atan(x)-atan(x/sqrt(2))*sqrt(2)"],
[(5-4*x+3*x^2+x^4)//((-1+x)^2*(1+x^2)),x,5,"5/2/(1-x)+x+2*atan(x)+1/2*log(1-x)+3/4*log(1+x^2)"],
[(1+x^4)//(2+x^2),x,3,"-2*x+1/3*x^3+5*atan(x/sqrt(2))/sqrt(2)"],
[(2+2*x+x^4)//(x^4+x^5),x,3,"(-2/3)/x^3+log(1+x)"],
[(-1-5*x+2*x^2)//(2-x-2*x^2+x^3),x,2,"2*log(1-x)-log(2-x)+log(1+x)"],
[(2+x+x^3)//(1+2*x^2+x^4),x,5,"x/(1+x^2)+atan(x)+1/2*log(1+x^2)"],
[(1+2*x+x^2+x^3)//(1+2*x^2+x^4),x,5,"(-1/2)/(1+x^2)+atan(x)+1/2*log(1+x^2)"],
[(3+4*x)//((1+x^2)*(2+x^2)),x,8,"3*atan(x)+2*log(1+x^2)-2*log(2+x^2)-3*atan(x/sqrt(2))/sqrt(2)"],
[(2+x)//((1+x^2)*(4+x^2)),x,8,"-1/3*atan(1/2*x)+2/3*atan(x)+1/6*log(1+x^2)-1/6*log(4+x^2)"],

#Grossman Calculus
[(2-x+x^3)//(-7-6*x+x^2),x,5,"6*x+1/2*x^2+169/4*log(7-x)-1/4*log(1+x)"],
[(-1+x^5)//(-1+x^2),x,4,"1/2*x^2+1/4*x^4+log(1+x)"],
[(5+2*x-x^2+x^3)//(1+x+x^2),x,6,"-2*x+1/2*x^2+3/2*log(1+x+x^2)+11*atan((1+2*x)/sqrt(3))/sqrt(3)"],
[(-3+x-2*x^3+x^4)//(10-8*x+2*x^2),x,6,"3/2*x+1/2*x^2+1/6*x^3+6*atan(2-x)+3/4*log(5-4*x+x^2)"],
[(1+2*x+3*x^2+x^3)//((-3+x)*(-2+x)*(-1+x)),x,2,"x+7/2*log(1-x)-25*log(2-x)+61/2*log(3-x)"],
[(2-7*x+x^2-x^3+x^4)//(-24-14*x+x^2+x^3),x,2,"-2*x+1/2*x^2+13/3*log(4-x)-22/3*log(2+x)+20*log(3+x)"],
[(2+x^2)//((-1+x)^2*x*(1+x)),x,2,"3/2/(1-x)-5/4*log(1-x)+2*log(x)-3/4*log(1+x)"],
[(3+x^2+x^3)//(2+x^2)^2,x,4,"1/4*(4+x)/(2+x^2)+1/2*log(2+x^2)+5/4*atan(x/sqrt(2))/sqrt(2)"],
[(-35+70*x-4*x^2+2*x^3)//((26-10*x+x^2)*(17-2*x+x^2)),x,10,"-15033/1025*atan(5-x)-4607/4100*atan(1/4*(-1+x))+1003/1025*log(26-10*x+x^2)+22/1025*log(17-2*x+x^2)"],
[(2+x^2)//((-5+x)*(-3+x)*(4+x)),x,2,"-11/14*log(3-x)+3/2*log(5-x)+2/7*log(4+x)"],
[x^4//((-1+x)*(2+x^2)),x,5,"x+1/2*x^2+1/3*log(1-x)-2/3*log(2+x^2)-2/3*atan(x/sqrt(2))*sqrt(2)"],

#Spivak Calculus
[(-1+7*x+2*x^2)//(-1-x+x^2+x^3),x,2,"(-3)/(1+x)+2*log(1-x)"],
[(1+2*x)//(-1+3*x-3*x^2+x^3),x,2,"(-3/2)/(1-x)^2+2/(1-x)"],
[(5-5*x+7*x^2+x^3)//((-1+x)^2*(1+x)^3),x,2,"1/(1-x)+(-2)/(1+x)^2"],
[(1+3*x+3*x^2)//(1+2*x+2*x^2+x^3),x,6,"log(1+x)+log(1+x+x^2)-2*atan((1+2*x)/sqrt(3))/sqrt(3)"],

#Stewart Calculus
[(-1+2*x+x^2)//(-2*x+3*x^2+2*x^3),x,3,"1/10*log(1-2*x)+1/2*log(x)-1/10*log(2+x)"],
[(1+4*x-2*x^2+x^4)//(1-x-x^2+x^3),x,2,"2/(1-x)+x+1/2*x^2+log(1-x)-log(1+x)"],
[(4-x+2*x^2)//(4*x+x^3),x,6,"-1/2*atan(1/2*x)+log(x)+1/2*log(4+x^2)"],
[(1+x^2+x^3)//((-1+x)*x*(1+x^2)^3*(1+x+x^2)),x,14,"1/8*(1+x)/(1+x^2)^2-3/8*(1-x)/(1+x^2)+3/16*x/(1+x^2)+7/16*atan(x)+1/8*log(1-x)-log(x)+15/16*log(1+x^2)-1/2*log(1+x+x^2)-atan((1+2*x)/sqrt(3))/sqrt(3)"],
[(1-3*x+2*x^2-x^3)//(1+x^2)^2,x,4,"1/2*(2-x)/(1+x^2)+3/2*atan(x)-1/2*log(1+x^2)"],
[(1-3*x+2*x^2-x^3)//(x*(1+x^2)^2),x,6,"1/2*(-1-2*x)/(1+x^2)-2*atan(x)+log(x)-1/2*log(1+x^2)"],
[(1-x-x^2+x^3+x^4)//(-x+x^3),x,4,"x+1/2*x^2-log(x)+1/2*log(1-x^2)"],
[(2-4*x^2+x^3)//((1+x^2)*(2+x^2)),x,8,"6*atan(x)-1/2*log(1+x^2)+log(2+x^2)-5*atan(x/sqrt(2))*sqrt(2)"],
[(1+x^2+x^4)//((1+x^2)*(4+x^2)^2),x,6,"-13/24*x/(4+x^2)+25/144*atan(1/2*x)+1/9*atan(x)"],
[(1+x^2+x^3)//(2*x^2+x^3+x^4),x,7,"(-1/2)/x-1/4*log(x)+5/8*log(2+x+x^2)+1/4*atan((1+2*x)/sqrt(7))/sqrt(7)"],
[(1-12*x+x^2+x^3)//(-12+x+x^2),x,5,"1/2*x^2-2/7*atanh(1/7*(1+2*x)),1/2*x^2+1/7*log(3-x)-1/7*log(4+x)"],
[(-3+5*x+6*x^2)//(-3*x+2*x^2+x^3),x,3,"2*log(1-x)+log(x)+3*log(3+x)"],
[(-2+3*x+5*x^2)//(2*x^2+x^3),x,3,"1/x+2*log(x)+3*log(2+x)"],
[(18-2*x-4*x^2)//(-6+x+4*x^2+x^3),x,2,"log(1-x)-2*log(2+x)-3*log(3+x)"],
[(1+x-2*x^2+x^3)//(4+5*x^2+x^4),x,7,"-3/2*atan(1/2*x)+atan(x)+1/2*log(4+x^2)"],
[(-32+5*x-27*x^2+4*x^3)//(-70-299*x-286*x^2+50*x^3-13*x^4+30*x^5),x,6,"-3146/80155*log(7-3*x)-334/323*log(1+2*x)+4822/4879*log(2+5*x)+11049/260015*log(5+x+x^2)+3988/13685*atan((1+2*x)/sqrt(19))/sqrt(19)"],
[(8-13*x^2-7*x^3+12*x^5)//(4-20*x+41*x^2-80*x^3+116*x^4-80*x^5+100*x^6),x,7,"5828/9075/(2-5*x)+1/1452*(-313-502*x)/(1+2*x^2)-59096/99825*log(2-5*x)+2843/7986*log(1+2*x^2)+503/7986*atan(x*sqrt(2))/sqrt(2),5828/9075/(2-5*x)+1/1452*(-313-502*x)/(1+2*x^2)-59096/99825*log(2-5*x)+2843/7986*log(1+2*x^2)-251/726*atan(x*sqrt(2))/sqrt(2)+272/1331*atan(x*sqrt(2))*sqrt(2)"],

#Thomas Calculus, 8th Edition
[(9+x^4)//(x^2*(9+x^2)),x,3,"(-1)/x+x-10/3*atan(1/3*x)"],
[(2*x+x^4)//(1+x^2),x,6,"-x+1/3*x^3+atan(x)+log(1+x^2)"],
[(-x+x^3)//((-1+x)^2*(1+x^2)),x,5,"atan(x)+log(1-x)"],
[(2+5*x+3*x^2+2*x^3)//(1+x+x^2),x,3,"x+x^2+log(1+x+x^2)"],
[(3-4*x-5*x^2+3*x^3)//(x^3*(-1+x+x^2)),x,5,"3/2/x^2+(-1)/x+3*log(x)-1/10*log(1+2*x-sqrt(5))*(15-sqrt(5))-1/10*log(1+2*x+sqrt(5))*(15+sqrt(5))"],
[(4+8*x+5*x^2+2*x^3)//(2+2*x+x^2)^2,x,5,"(-1)/(2+2*x+x^2)-atan(1+x)+log(2+2*x+x^2)"],
[(-1+x)^4*x^4//(1+x^2),x,3,"4*x-4/3*x^3+x^5-2/3*x^6+1/7*x^7-4*atan(x)"],
[(-20*x+4*x^2)//(9-10*x^2+x^4),x,-11,"log(1-x)-1/2*log(3-x)+3/2*log(1+x)-2*log(3+x)"],
[(-1+x+4*x^3)//((-1+x)*x^2*(1+x^2)),x,5,"(-1)/x+atan(x)+2*log(1-x)-log(1+x^2)"],
[(1-3*x+2*x^2-4*x^3+x^4)//(1+x^2)^3,x,4,"(-1/4)/(1+x^2)^2+2/(1+x^2)+atan(x)"],
[(1-3*x+2*x^2-4*x^3+x^4)//(1+3*x^2+3*x^4+x^6),x,5,"(-1/4)/(1+x^2)^2+2/(1+x^2)+atan(x)"],

#North Texas University Integration Competition
[(1+x+2*x^2+2*x^3)//(x^2+x^3+x^4),x,4,"(-1)/x+log(1+x+x^2)"],
]

for prob in problems
    result = integrate(prob[1], x)
    println("∫", prob[1], "dx = ", result)
    println("expected: ", prob[4])
    println("--------------------------------------------------------------------")
end


text:
    @with_kw struct GPSData
        integrity_status_flag::Union{Nothing,Bool} = nothing
        TOW::Union{Nothing,Int64} = nothing
        alert_flag::Union{Nothing,Bool} = nothing
        anti_spoof_flag::Union{Nothing,Bool} = nothing

        trans_week::Union{Nothing,Int64} = nothing
        codeonl2::Union{Nothing,Int64} = nothing
        ura::Union{Nothing,Float64} = nothing
        svhealth::Union{Nothing,String} = nothing
        IODC::Union{Nothing,String} = nothing
        l2pcode::Union{Nothing,Bool} = nothing
        T_GD::Union{Nothing,Float64} = nothing
        t_oc::Union{Nothing,Int64} = nothing
        a_f2::Union{Nothing,Float64} = nothing
        a_f1::Union{Nothing,Float64} = nothing
        a_f0::Union{Nothing,Float64} = nothing

        IODE_Sub_2::Union{Nothing,String} = nothing
        C_rs::Union{Nothing,Float64} = nothing
        Δn::Union{Nothing,Float64} = nothing
        M_0::Union{Nothing,Float64} = nothing
        C_uc::Union{Nothing,Float64} = nothing
        e::Union{Nothing,Float64} = nothing
        C_us::Union{Nothing,Float64} = nothing
        sqrt_A::Union{Nothing,Float64} = nothing
        t_oe::Union{Nothing,Int64} = nothing
        fit_interval::Union{Nothing,Bool} = nothing
        AODO::Union{Nothing,Int64} = nothing

        C_ic::Union{Nothing,Float64} = nothing
        Ω_0::Union{Nothing,Float64} = nothing
        C_is::Union{Nothing,Float64} = nothing
        i_0::Union{Nothing,Float64} = nothing
        C_rc::Union{Nothing,Float64} = nothing
        ω::Union{Nothing,Float64} = nothing
        Ω_dot::Union{Nothing,Float64} = nothing
        IODE_Sub_3::Union{Nothing,String} = nothing
        IDOT::Union{Nothing,Float64} = nothing
    end

    @with_kw struct GPSL1Constants
        PI = 3.1415926535898
        Ω_dot_e = 7.2921151467e-5
        c = 2.99792458e8
        μ = 3.986005e14
        F =  -4.442807633e-10
    end

    @with_kw mutable struct GNSSDecoderState
        PRN::Int64
        buffer::BitArray{1} = falses(BUFFER_LENGTH)
        data::GPSData = GPSData()
        constants::GPSL1Constants = GPSL1Constants()
        preamble_found::Bool = false
        subframe_count::Int = 0
        prev_30::Bool = false
        prev_29::Bool = false
        data_integrity::Bool = true # pass of parity check
        new_data_needed::Bool = false # IODE must be equal to the 8 LSB of the IODC. If they don't match new data must be collected
        subframes_decoded::MVector{5,Bool} = MVector{5,Bool}(false, false, false, false, false)
        nb_prev::Int = 0
        num_bits_buffered::Int = 0
    end


text:
using Test
using Distances
using Distributions
using ConditionalDists
using IPMeasures
using CUDA
using Flux

using IPMeasures: mapsum, mmd, mmdfromdist, mmd2_and_variance,
    GaussianKernel, RQKernel, IMQKernel, null_distribution, samplecolumns,
    split2, pairwisel2

@testset "samplecolumns" begin
    xs = randn(2,5)
    ys = samplecolumns(xs, 2)
    @test sum(all(xs .≈ ys[:,1], dims=1)) == 1
    @test sum(all(xs .≈ ys[:,2], dims=1)) == 1

    ys = samplecolumns(xs, 12)
    @test all(xs .== ys)
end

@testset "split2" begin
    x = randn(2,10)
    (a,b) = split2(x)
    @test all(x[:,1:5] .== a)
    @test all(x[:,6:10] .== b)
end

@testset "pairwisel2" begin
    n = 20
    x = rand(Float32, n, 3) .* 45
    y = rand(Float32, n, 3) .* -120

    dcpu = pairwisel2(x,y)
    dgpu = pairwisel2(gpu(x), gpu(y))
    @test dgpu isa typeof(gpu(x))
    @test dcpu ≈ cpu(dgpu) rtol=1e-2
end

@testset "mapsum" begin
	d = randn(5,5)
	@test mapsum(exp, d , [1,2]) ≈ sum(exp.(d[1:2,1:2]))
	@test mapsum(exp, d , [1,5]) ≈ sum(exp.(d[[1,5],[1,5]]))
	@test mapsum(exp, d , [1,2],[3,5]) ≈ sum(exp.(d[1:2,[3,5]]))
end

@testset "kernels" begin
	x = randn(3,10)
    d = IPMeasures.pairwisel2(x,x)
	i, j = [1,2,3], [4,5,6]
	for k in [GaussianKernel(1.0), RQKernel(1.0), IMQKernel(1.0)]
		@test mmdfromdist(k, d, i, j) .≈ mmd(k, x[:,i],x[:,j])
		@test mmd(k, randn(1,1000), randn(1,1000)) < 1e-2
	end
end

@testset "Null distribution" begin
    k = GaussianKernel(1.0)
    x = randn(100, 100)
    n = 100
    d = null_distribution(k,x,n)
    @test size(d) == (100,)
end

include("mmd.jl")
include("kl_divergence.jl")


text:
genblas_dot{T<:Base.LinAlg.BlasFloat}(x::Vector{T}, y::Vector{T}) = BLAS.dot(x, y)
genblas_dot(x, y) = dot(x,y)
genblas_scal!{T<:Base.LinAlg.BlasFloat}(a::T, x::Vector{T}) = BLAS.scal!(length(x), a, x, 1)
genblas_scal!(a, x) = x .*= a
genblas_axpy!{T<:Base.LinAlg.BlasFloat}(a::T, x::Vector{T}, y::Vector{T}) = BLAS.axpy!(a, x, y)
genblas_axpy!(a, x, y) = y .+= a.*x
genblas_nrm2{T<:Base.LinAlg.BlasFloat}(x::Vector{T}) = BLAS.nrm2(length(x), x, 1)
genblas_nrm2(x) = norm(x)


text:
@symbol_func function volume(cur_reactor::AbstractReactor)
  cur_volume = 2.0

  cur_volume *= cur_reactor.pi ^ 2

  cur_volume *= cur_reactor.R_0

  cur_volume *= a(cur_reactor) ^ 2

  cur_volume *= cur_reactor.kappa_95

  cur_volume *= g(cur_reactor)

  cur_volume
end


text:
using BinaryBuilder

name = "nlminb"
version = v"0.1.1"

# Collection of sources required to build NLopt
sources = [
    GitSource("https://github.com/eco-hydro/nlminb.f.git",
              "4d8d42e4b03629cacf4d7531b4d496f44261d18f"), # v0.1.1
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/nlminb.f

## compile by hand
if [[ "${proc_family}" == "intel" ]]; then
    FLAGS="-mfpmath=sse -msse2 -mstackrealign"
fi

CFLAGS="-fPIC -DNDEBUG  -Iinclude -O2 -Wall -std=gnu99 ${FLAGS}" \
    FFLAGS="-fPIC -fno-optimize-sibling-calls -O2 ${FLAGS}" \
    target=${libdir}/libnlminb.${dlext} make
"""

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

# The products that we will ensure are always built
products = [
    LibraryProduct("libnlminb", :libnlminb),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency("CompilerSupportLibraries_jll"),
    Dependency("OpenBLAS32_jll"),
]

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

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
using LinearAlgebra
include("poli_sturm.jl");
include("elimina_zeros.jl");

function msinal(w, d, p)

    p = poli_sturm(w,d,p);

    p = elimina_zeros(p);

    n = size(p,1);
    ms = 0;
    for i = 2:n+1
        if p[i]*p[i-1] < 0
            ms += 1;
        end
    end

    return ms;

end


text:
import Base: @kwdef

_parse_seed(seed::String) = hex2bytes(seed)
_parse_seed(seed::Vector{UInt8}) = seed

_parse_bits(x::String, N::Int) = hex2bits(x)[end - N + 1:end]
_parse_bits(x::BitVector, m::Int) = x
_parse_bits(x::Nothing, m::Int) = x

_parse_int(x::String) = parse(BigInt, x, base=16)
_parse_int(x::Integer) = BigInt(x)
_parse_int(::Nothing) = nothing

function spec(::Type{P}; kwargs...) where P <: AbstractPoint

    n = hasmethod(order, Tuple{Type{P}}) ? order(P) : nothing
    h = hasmethod(cofactor, Tuple{Type{P}}) ? cofactor(P) : nothing

    EQ = eq(P)
    F = field(P)

    return spec(EQ, F; n, h, kwargs...)
end

spec(p::P) where P <: AbstractPoint = spec(P; Gx=value(gx(p)), Gy=value(gy(p)))

spec(::Type{ECGroup{P}}) where P = spec(P)
spec(g::ECGroup) = spec(g.x)

@kwdef struct ECP <: Spec
    p::BigInt
    n::Union{BigInt, Nothing} = nothing
    a::BigInt = -3
    b::BigInt
    Gx::Union{BigInt, Nothing} = nothing
    Gy::Union{BigInt, Nothing} = nothing

    function ECP(p, n, a, b, Gx, Gy)

        _a = mod(_parse_int(a), p) # taking mod as conventually a=-3
        _b = _parse_int(b)
        _Gx = _parse_int(Gx)
        _Gy = _parse_int(Gy)

        #return ECP(p, n, _a, _b, _Gx, _Gy)
        return new(p, n, _a, _b, _Gx, _Gy)
    end
end

order(curve::ECP) = curve.n
generator(curve::ECP) = (curve.Gx, curve.Gy)

modulus(curve::ECP) = curve.p

# I could always add a field for equation to be used

function spec(::Type{EQ}, ::Type{F}; n=nothing, h=nothing, Gx=nothing, Gy=nothing) where {EQ <: Weierstrass, F <: PrimeField}

    _a = a(EQ)
    _b = b(EQ)

    p = modulus(F)

    return ECP(p, n, _a, _b, Gx, Gy) # I will need to add H in the end here
end

Base.:(==)(x::ECP, y::ECP) = x.p == y.p && x.n == y.n && x.a == y.a && x.b == y.b && x.Gx == y.Gx && x.Gy == y.Gy

abstract type EC2N <: Spec end

order(curve::EC2N) = curve.n
generator(curve::EC2N) = (curve.Gx, curve.Gy)

a(curve::EC2N) = curve.a
b(curve::EC2N) = curve.b

@kwdef struct Koblitz_GNB <: EC2N
    m::Int
    T::Int
    n::BigInt
    a::Int
    Gx::BitVector
    Gy::BitVector

    function Koblitz_GNB(m::Int, T::Int, n::BigInt, a::Int, Gx::BitVector, Gy::BitVector)

        @assert a in [0, 1]
        @assert length(Gx) == length(Gy) == m

        new(m, T, n, a, Gx, Gy)
    end
end

function Koblitz_GNB(m, T, n, a, Gx, Gy)

    _m = convert(Int, m)
    _T = convert(Int, T)
    _a = convert(Int, a)
    _n = convert(BigInt, n)
    _Gx = _parse_bits(Gx, _m)
    _Gy = _parse_bits(Gy, _m)

    return Koblitz_GNB(_m, _T, _n, _a, _Gx, _Gy)
end

function b(curve::Koblitz_GNB)

    (; m) = curve

    _b = 1
    b′ = _parse_bits_gnb(_b, m)

    return b′
end

@kwdef struct Koblitz_PB <: EC2N
    f::Vector{Int}
    n::BigInt
    a::Int
    Gx::BitVector
    Gy::BitVector

    function Koblitz_PB(f::Vector{Int}, n::BigInt, a::Int, Gx::BitVector, Gy::BitVector)

        m = maximum(f)

        @assert a in [0, 1]
        @assert length(Gx) == length(Gy) == m

        new(f, n, a, Gx, Gy)
    end
end

function Koblitz_PB(f, n, a, Gx, Gy)

    _f = convert(Vector{Int}, f)

    m = maximum(_f)

    _n = convert(BigInt, n)
    _a = convert(Int, a)
    _Gx = _parse_bits(Gx, m)
    _Gy = _parse_bits(Gy, m)

    return Koblitz_PB(_f, _n, _a, _Gx, _Gy)
end

function b(curve::Koblitz_PB)

    (; f) = curve

    m = maximum(f)

    _b = 1
    b′ = _parse_bits_pb(_b, m)

    return b′
end

function _int2bits_gnb(x::Int, m::Int)
    if x == 0
        return BitVector(0 for i in 1:m)
    elseif x == 1
        return BitVector(1 for i in 1:m)
    else
        error("Conversion of $x not possible")
    end
end

_parse_bits_gnb(x::BitVector, m::Int) = x
_parse_bits_gnb(x::String, m::Int) = _parse_bits(x, m)
_parse_bits_gnb(x::Int, m::Int) = _int2bits_gnb(x, m)

#abstract type BinaryCurveSpec <: EllipticCurveSpec end

@kwdef struct BEC_GNB <: EC2N  #BinaryCurveSpec
    m::Int
    T::Int
    n::BigInt
    a::BitVector
    b::BitVector
    Gx::BitVector
    Gy::BitVector

    function BEC_GNB(m::Int, T::Int, n::BigInt, a::BitVector, b::BitVector, Gx::BitVector, Gy::BitVector)

        @assert m == length(a) == length(b) == length(Gx) == length(Gy)

        new(m, T, n, a, b, Gx, Gy)
    end
end

function BEC_GNB(m, T, n, a, b, Gx, Gy)

    _m = convert(Int, m)
    _T = convert(Int, T)
    _n = convert(BigInt, n)
    _a = _parse_bits_gnb(a, _m)
    _b = _parse_bits_gnb(b, _m)
    _Gx = _parse_bits(Gx, _m)
    _Gy = _parse_bits(Gy, _m)

    return BEC_GNB(_m, _T, _n, _a, _b, _Gx, _Gy)
end

function BEC_GNB(curve::Koblitz_GNB)

    (; m, T, n, a, Gx, Gy) = curve

    _b = b(curve)

    return BEC_GNB(m, T, n, a, _b, Gx, Gy)
end

function _int2bits_pb(x::Int, m::Int)
    if x == 0
        return BitVector(0 for i in 1:m)
    elseif x == 1
        return BitVector(((0 for i in 1:m-1)..., 1))
    else
        error("Conversion of $x not possible")
    end
end

_parse_bits_pb(x::BitVector, m::Int) = x
_parse_bits_pb(x::String, m::Int) = _parse_bits(x, m)
_parse_bits_pb(x::Int, m::Int) = _int2bits_pb(x, m)

@kwdef struct BEC_PB <: EC2N  #BinaryCurveSpec
    f::Vector{Int}
    n::BigInt
    a::BitVector
    b::BitVector
    Gx::BitVector
    Gy::BitVector

    function BEC_PB(f::Vector{Int}, n::BigInt, a::BitVector, b::BitVector, Gx::BitVector, Gy::BitVector)

        m = maximum(f)

        @assert length(a) == length(b) == length(Gx) == length(Gy) == m

        new(f, n, a, b, Gx, Gy)
    end
end

function BEC_PB(f, n, a, b, Gx, Gy)

    _f = convert(Vector{Int}, f)
    _m = maximum(_f)
    _n = convert(BigInt, n)

    _a = _parse_bits_pb(a, _m)
    _b = _parse_bits_pb(b, _m)
    _Gx = _parse_bits(Gx, _m)
    _Gy = _parse_bits(Gy, _m)

    return BEC_PB(_f, _n, _a, _b, _Gx, _Gy)
end

function BEC_PB(curve::Koblitz_PB)

    (; f, n, a, Gx, Gy) = curve

    _b = b(curve)

    return BEC_PB(f, n, a, _b, Gx, Gy)
end

### Methods for making a concrete AffinePoint type from given elliptic curve spec

function specialize(::Type{AffinePoint{Weierstrass, F}}, curve::ECP) where F <: PrimeField

    (; p, a, b) = curve

    P = AffinePoint{specialize(Weierstrass, a, b), specialize(F, p)}

    return P
end

specialize(::Type{AffinePoint}, spec::ECP) = specialize(AffinePoint{Weierstrass, FP}, spec)
#specialize(::Type{ECPoint}, spec::ECP; name = nothing) = specialize(ECPoint{AffinePoint}, spec; name)

function specialize(::Type{F}, curve::BEC_PB) where F <: BinaryField
    (; f) = curve
    return specialize(F, f)
end

function specialize(::Type{F}, curve::BEC_GNB) where F <: BinaryField
    (; m, T) = curve
    return specialize(F, m, T)
end

specialize(::Type{BinaryCurve}, curve::EC2N) = specialize(BinaryCurve, a(curve), b(curve))

function specialize(::Type{AffinePoint{BinaryCurve, F}}, curve) where F <: BinaryField
    P = AffinePoint{specialize(BinaryCurve, curve), specialize(F, curve)}
    return P
end

specialize(::Type{AffinePoint}, curve::BEC_GNB) = specialize(AffinePoint{BinaryCurve, F2GNB}, curve)
specialize(::Type{AffinePoint}, curve::BEC_PB) = specialize(AffinePoint{BinaryCurve, F2PB}, curve)

specialize(::Type{AffinePoint{BinaryCurve, F}}, curve::Koblitz_GNB) where F <: BinaryField = specialize(AffinePoint{BinaryCurve, F}, BEC_GNB(curve))
specialize(::Type{AffinePoint{BinaryCurve, F}}, curve::Koblitz_PB) where F <: BinaryField = specialize(AffinePoint{BinaryCurve, F}, BEC_PB(curve))

################################ Constants #################

############### Prime curves #############

#
const Curve_P_192 = ECP(
    p = 6277101735386680763835789423207666416083908700390324961279,
    n = 6277101735386680763835789423176059013767194773182842284081,
    #SEED = "3045ae6f c8422f64 ed579528 d38120ea e12196d5",
    #c = "3099d2bb bfcb2538 542dcd5f b078b6ef 5f3d6fe2 c745de65",
    b = "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",
    Gx = "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012",
    Gy = "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"
)

const Curve_P_244 = ECP(
    p = 26959946667150639794667015087019630673557916260026308143510066298881,
    n = 26959946667150639794667015087019625940457807714424391721682722368061,
    # SEED = "bd713447 99d5c7fc dc45b59f a3b9ab8f 6a948bc5",
    # c = "5b056c7e 11dd68f4 0469ee7f 3c7a7d74 f7d12111 6506d031 218291fb",
    b = "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",
    Gx = "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21",
    Gy = "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"
)

const Curve_P_256 = ECP(
    p = 115792089210356248762697446949407573530086143415290314195533631308867097853951,
    n = 115792089210356248762697446949407573529996955224135760342422259061068512044369,
    #SEED = "c49d3608 86e70493 6a6678e1 139d26b7 819f7e90",
    #c = "7efba166 2985be94 03cb055c 75d4f7e0 ce8d84a9 c5114abc af317768 0104fa0d",
    b = "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",
    Gx = "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296",
    Gy = "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"
)

const Curve_P_384 = ECP(
    p = 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319,
    n = 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643,
    #SEED = "a335926a a319a27a 1d00896a 6773a482 7acdac73",
    #c = "79d1e655 f868f02f ff48dcde e14151dd b80643c1 406d0ca1 0dfe6fc5 2009540a 495e8042 ea5f744f 6e184667 cc722483",
    b = "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",
    Gx = "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7",
    Gy = "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"
)

const Curve_P_521 = ECP(
    p = 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151,
    n = 6864797660130609714981900799081393217269435300143305409394463459185543183397655394245057746333217197532963996371363321113864768612440380340372808892707005449,
    #SEED = "d09e8800 291cb853 96cc6717 393284aa a0da64ba",
    #c = "0b4 8bfa5f42 0a349495 39d2bdfc 264eeeeb 077688e4 4fbf0ad8 f6d0edb3 7bd6b533 28100051 8e19f1b9 ffbe0fe9 ed8a3c22 00b8f875 e523868c 70c1e5bf 55bad637",
    b = "051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",
    Gx = "c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66",
    Gy = "118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"
)

############### Koblitz curves ################

const Curve_K_163_PB = Koblitz_PB(
    f = [163, 7, 6, 3, 0],
    a = 1,
    n = 5846006549323611672814741753598448348329118574063,
    Gx = "2 fe13c053 7bbc11ac aa07d793 de4e6d5e 5c94eee8",
    Gy = "2 89070fb0 5d38ff58 321f2e80 0536d538 ccdaa3d9"
)

const Curve_K_163_GNB = Koblitz_GNB(
    n = 5846006549323611672814741753598448348329118574063,
    a = 1,
    m = 163,
    T = 4,
    Gx = "0 5679b353 caa46825 fea2d371 3ba450da 0c2a4541",
    Gy = "2 35b7c671 00506899 06bac3d9 dec76a83 5591edb2"
)

const Curve_K_233_PB = Koblitz_PB(
    f = [233, 74, 0],
    a = 0,
    n = 3450873173395281893717377931138512760570940988862252126328087024741343,
    Gx = "172 32ba853a 7e731af1 29f22ff4 149563a4 19c26bf5 0a4c9d6e efad6126",
    Gy = "1db 537dece8 19b7f70f 555a67c4 27a8cd9b f18aeb9b 56e0c110 56fae6a3"
)

const Curve_K_233_GNB = Koblitz_GNB(
    m = 233,
    T = 2,
    a = 0,
    n = 3450873173395281893717377931138512760570940988862252126328087024741343,
    Gx = "0fd e76d9dcd 26e643ac 26f1aa90 1aa12978 4b71fc07 22b2d056 14d650b3",
    Gy = "064 3e317633 155c9e04 47ba8020 a3c43177 450ee036 d6335014 34cac978"
)

const Curve_K_283_PB = Koblitz_PB(
    f = [283, 12, 7, 5, 0],
    a = 0,
    n = 3885337784451458141838923813647037813284811733793061324295874997529815829704422603873,
    Gx = "503213f 78ca4488 3f1a3b81 62f188e5 53cd265f 23c1567a 16876913 b0c2ac24 58492836",
    Gy = "1ccda38 0f1c9e31 8d90f95d 07e5426f e87e45c0 e8184698 e4596236 4e341161 77dd2259"
)

const Curve_K_283_GNB = Koblitz_GNB(
    m = 283,
    T = 6,
    a = 0,
    n = 3885337784451458141838923813647037813284811733793061324295874997529815829704422603873,
    Gx = "3ab9593 f8db09fc 188f1d7c 4ac9fcc3 e57fcd3b db15024b 212c7022 9de5fcd9 2eb0ea60",
    Gy = "2118c47 55e7345c d8f603ef 93b98b10 6fe8854f feb9a3b3 04634cc8 3a0e759f 0c2686b1"
)

const Curve_K_409_PB = Koblitz_PB(
    f = [409, 87, 0],
    a = 0,
     n = 330527984395124299475957654016385519914202341482140609642324395022880711289249191050673258457777458014096366590617731358671,
    Gx = "060f05f 658f49c1 ad3ab189 0f718421 0efd0987 e307c84c 27accfb8 f9f67cc2 c460189e b5aaaa62 ee222eb1 b35540cf e9023746",
    Gy = "1e36905 0b7c4e42 acba1dac bf04299c 3460782f 918ea427 e6325165 e9ea10e3 da5f6c42 e9c55215 aa9ca27a 5863ec48 d8e0286b"
)

const Curve_K_409_GNB = Koblitz_GNB(
    m = 409,
    T = 4,
    a = 0,
    n = 330527984395124299475957654016385519914202341482140609642324395022880711289249191050673258457777458014096366590617731358671,
    Gx = "1b559c7 cba2422e 3affe133 43e808b5 5e012d72 6ca0b7e6 a63aeafb c1e3a98e 10ca0fcf 98350c3b 7f89a975 4a8e1dc0 713cec4a",
    Gy = "16d8c42 052f07e7 713e7490 eff318ba 1abd6fef 8a5433c8 94b24f5c 817aeb79 852496fb ee803a47 bc8a2038 78ebf1c4 99afd7d6"
)

const Curve_K_571_PB = Koblitz_PB(
    f = [571, 10, 5, 2, 0],
    n = 1932268761508629172347675945465993672149463664853217499328617625725759571144780212268133978522706711834706712800825351461273674974066617311929682421617092503555733685276673,
    a = 0,
    Gx = "26eb7a8 59923fbc 82189631 f8103fe4 ac9ca297 0012d5d4 60248048 01841ca4 43709584 93b205e6 47da304d b4ceb08c bbd1ba39 494776fb 988b4717 4dca88c7 e2945283 a01c8972",
    Gy = "349dc80 7f4fbf37 4f4aeade 3bca9531 4dd58cec 9f307a54 ffc61efc 006d8a2c 9d4979c0 ac44aea7 4fbebbb9 f772aedc b620b01a 7ba7af1b 320430c8 591984f6 01cd4c14 3ef1c7a3"
)

const Curve_K_571_GNB = Koblitz_GNB(
    m = 571,
    T = 10,
    a = 0,
    n = 1932268761508629172347675945465993672149463664853217499328617625725759571144780212268133978522706711834706712800825351461273674974066617311929682421617092503555733685276673,
    Gx = "04bb2db a418d0db 107adae0 03427e5d 7cc139ac b465e593 4f0bea2a b2f3622b c29b3d5b 9aa7a1fd fd5d8be6 6057c100 8e71e484 bcd98f22 bf847642 37673674 29ef2ec5 bc3ebcf7",
    Gy = "44cbb57 de20788d 2c952d7b 56cf39bd 3e89b189 84bd124e 751ceff4 369dd8da c6a59e6e 745df44d 8220ce22 aa2c852c fcbbef49 ebaa98bd 2483e331 80e04286 feaa2530 50caff60"
)

##################### Binary curves ############################

const Curve_B_163_PB = BEC_PB(
    f = [163, 7, 6, 3, 0],
    a = 1,
    b = "2 0a601907 b8c953ca 1481eb10 512f7874 4a3205fd",
    n = 5846006549323611672814742442876390689256843201587,
    Gx = "3 f0eba162 86a2d57e a0991168 d4994637 e8343e36",
    Gy = "0 d51fbc6c 71a0094f a2cdd545 b11c5c0c 797324f1"
)

const Curve_B_163_GNB = BEC_GNB(
    m = 163,
    T = 4,
    a = 1,
    b = "6 645f3cac f1638e13 9c6cd13e f61734fb c9e3d9fb",
    n = 5846006549323611672814742442876390689256843201587,
    Gx = "0 311103c1 7167564a ce77ccb0 9c681f88 6ba54ee8",
    Gy = "3 33ac13c6 447f2e67 613bf700 9daf98c8 7bb50c7f"
)

const Curve_B_233_PB = BEC_PB(
    f = [233, 74, 0],
    a = 1,
    b = "066 647ede6c 332c7f8c 0923bb58 213b333b 20e9ce42 81fe115f 7d8f90ad",
    n = 6901746346790563787434755862277025555839812737345013555379383634485463,
    Gx = "0fa c9dfcbac 8313bb21 39f1bb75 5fef65bc 391f8b36 f8f8eb73 71fd558b",
    Gy = "100 6a08a419 03350678 e58528be bf8a0bef f867a7ca 36716f7e 01f81052"
)

const Curve_B_233_GNB = BEC_GNB(
    m = 233,
    T = 2,
    a = 1,
    b = "1a0 03e0962d 4f9a8e40 7c904a95 38163adb 82521260 0c7752ad 52233279",
    n = 6901746346790563787434755862277025555839812737345013555379383634485463,
    Gx = "18b 863524b3 cdfefb94 f2784e0b 116faac5 4404bc91 62a363ba b84a14c5",
    Gy = "049 25df77bd 8b8ff1a5 ff519417 822bfedf 2bbd7526 44292c98 c7af6e02"
)

const Curve_B_283_PB = BEC_PB(
    f = [283, 12, 7, 5, 0],
    n = 770675568902916283677847627294075626569625924376904889109196526770044277787378692871,
    a = 1,
    b = "27b680a c8b8596d a5a4af8a 19a0303f ca97fd76 45309fa2 a581485a f6263e31 3b79a2f5",
    Gx = "5f93925 8db7dd90 e1934f8c 70b0dfec 2eed25b8 557eac9c 80e2e198 f8cdbecd 86b12053",
    Gy = "3676854 fe24141c b98fe6d4 b20d02b4 516ff702 350eddb0 826779c8 13f0df45 be8112f4"
)

const Curve_B_283_GNB = BEC_GNB(
    m = 283,
    T = 6,
    a = 1,
    b = "157261b 894739fb 5a13503f 55f0b3f1 0c560116 66331022 01138cc1 80c0206b dafbc951",
    n = 7770675568902916283677847627294075626569625924376904889109196526770044277787378692871,
    Gx = "749468e 464ee468 634b21f7 f61cb700 701817e6 bc36a236 4cb8906e 940948ea a463c35d",
    Gy = "62968bd 3b489ac5 c9b859da 68475c31 5bafcdc4 ccd0dc90 5b70f624 46f49c05 2f49c08c"
)

const Curve_B_409_PB = BEC_PB(
    f = [409, 87, 0],
    n = 661055968790248598951915308032771039828404682964281219284648798304157774827374805208143723762179110965979867288366567526771,
    a = 1,
    b = "021a5c2 c8ee9feb 5c4b9a75 3b7b476b 7fd6422e f1f3dd67 4761fa99 d6ac27c8 a9a197b2 72822f6c d57a55aa 4f50ae31 7b13545f",
    Gx = "15d4860 d088ddb3 496b0c60 64756260 441cde4a f1771d4d b01ffe5b 34e59703 dc255a86 8a118051 5603aeab 60794e54 bb7996a7",
    Gy = "061b1cf ab6be5f3 2bbfa783 24ed106a 7636b9c5 a7bd198d 0158aa4f 5488d08f 38514f1f df4b4f40 d2181b36 81c364ba 0273c706"
)

const Curve_B_409_GNB = BEC_GNB(
    m = 409,
    T = 4,
    a = 1,
    b = "124d065 1c3d3772 f7f5a1fe 6e715559 e2129bdf a04d52f7 b6ac7c53 2cf0ed06 f610072d 88ad2fdc c50c6fde 72843670 f8b3742a",
    n = 661055968790248598951915308032771039828404682964281219284648798304157774827374805208143723762179110965979867288366567526771,
    Gx = "0ceacbc 9f475767 d8e69f3b 5dfab398 13685262 bcacf22b 84c7b6dd 981899e7 318c96f0 761f77c6 02c016ce d7c548de 830d708f",
    Gy = "199d64b a8f089c6 db0e0b61 e80bb959 34afd0ca f2e8be76 d1c5e9af fc7476df 49142691 ad303902 88aa09bc c59c1573 aa3c009a"
)

const Curve_B_571_PB = BEC_PB(
    f = [571, 10, 5, 2, 0],
    n = 3864537523017258344695351890931987344298927329706434998657235251451519142289560424536143999389415773083133881121926944486246872462816813070234528288303332411393191105285703,
    a = 1,
    b = "2f40e7e 2221f295 de297117 b7f3d62f 5c6a97ff cb8ceff1 cd6ba8ce 4a9a18ad 84ffabbd 8efa5933 2be7ad67 56a66e29 4afd185a 78ff12aa 520e4de7 39baca0c 7ffeff7f 2955727a",
    Gx = "303001d 34b85629 6c16c0d4 0d3cd775 0a93d1d2 955fa80a a5f40fc8 db7b2abd bde53950 f4c0d293 cdd711a3 5b67fb14 99ae6003 8614f139 4abfa3b4 c850d927 e1e7769c 8eec2d19",
    Gy = "37bf273 42da639b 6dccfffe b73d69d7 8c6c27a6 009cbbca 1980f853 3921e8a6 84423e43 bab08a57 6291af8f 461bb2a8 b3531d2f 0485c19b 16e2f151 6e23dd3c 1a4827af 1b8ac15b"
)

const Curve_B_571_GNB = BEC_GNB(
    m = 571,
    T = 10,
    a = 1,
    b = "3762d0d 47116006 179da356 88eeaccf 591a5cde a7500011 8d9608c5 9132d434 26101a1d fb377411 5f586623 f75f0000 1ce61198 3c1275fa 31f5bc9f 4be1a0f4 67f01ca8 85c74777",
    n = 3864537523017258344695351890931987344298927329706434998657235251451519142289560424536143999389415773083133881121926944486246872462816813070234528288303332411393191105285703,
    Gx = "0735e03 5def5925 cc33173e b2a8ce77 67522b46 6d278b65 0a291612 7dfea9d2 d361089f 0a7a0247 a184e1c7 0d417866 e0fe0feb 0ff8f2f3 f9176418 f97d117e 624e2015 df1662a8",
    Gy = "04a3642 0572616c df7e606f ccadaecf c3b76dab 0eb1248d d03fbdfc 9cd3242c 4726be57 9855e812 de7ec5c5 00b4576a 24628048 b6a72d88 0062eed0 dd34b109 6d3acbb6 b01a4a97"
)

max_stars_repo_name: PeaceFounder/DiffieHellmanGroups

max_issues_repo_name: PeaceFounder/DiffieHellmanGroups

max_forks_repo_name: PeaceFounder/DiffieHellmanGroups


text:
# Julia wrapper for header: niScopeCal.h
# Automatically generated using Clang.jl

function niScope_CalStart(resourceName, password, newSessionHandle)
    ccall((:niScope_CalStart, libniscope), ViStatus, (ViRsrc, ViConstString, Ptr{ViSession}), resourceName, password, newSessionHandle)
end

function niScope_CalEnd(vi, action)
    ccall((:niScope_CalEnd, libniscope), ViStatus, (ViSession, ViInt32), vi, action)
end

function niScope_CalChangePassword(vi, oldPassword, newPassword)
    ccall((:niScope_CalChangePassword, libniscope), ViStatus, (ViSession, ViConstString, ViConstString), vi, oldPassword, newPassword)
end

function niScope_CalFetchCount(vi, whichOne, calibrationCount)
    ccall((:niScope_CalFetchCount, libniscope), ViStatus, (ViSession, ViInt32, Ptr{ViInt32}), vi, whichOne, calibrationCount)
end

function niScope_CalFetchDate(vi, whichOne, year, month, day)
    ccall((:niScope_CalFetchDate, libniscope), ViStatus, (ViSession, ViInt32, Ptr{ViInt32}, Ptr{ViInt32}, Ptr{ViInt32}), vi, whichOne, year, month, day)
end

function niScope_CalFetchTemperature(vi, whichOne, temperature)
    ccall((:niScope_CalFetchTemperature, libniscope), ViStatus, (ViSession, ViInt32, Ptr{ViReal64}), vi, whichOne, temperature)
end

function niScope_CalFetchMiscInfo(vi, miscInfo)
    ccall((:niScope_CalFetchMiscInfo, libniscope), ViStatus, (ViSession, Ptr{ViChar}), vi, miscInfo)
end

function niScope_CalFetchInternalReference(vi, whichReference, internalRefValue)
    ccall((:niScope_CalFetchInternalReference, libniscope), ViStatus, (ViSession, ViInt32, Ptr{ViReal64}), vi, whichReference, internalRefValue)
end

function niScope_CalStoreMiscInfo(vi, miscInfo)
    ccall((:niScope_CalStoreMiscInfo, libniscope), ViStatus, (ViSession, ViConstString), vi, miscInfo)
end

function niScope_CalStoreInternalReference(vi, whichReference, internalRefValue)
    ccall((:niScope_CalStoreInternalReference, libniscope), ViStatus, (ViSession, ViInt32, ViReal64), vi, whichReference, internalRefValue)
end

function niScope_CalAdjustRange(vi, channelName, rng, stimulus)
    ccall((:niScope_CalAdjustRange, libniscope), ViStatus, (ViSession, ViConstString, ViReal64, ViReal64), vi, channelName, rng, stimulus)
end

function niScope_CalAdjustVCXO(vi, stimulusFreq)
    ccall((:niScope_CalAdjustVCXO, libniscope), ViStatus, (ViSession, ViReal64), vi, stimulusFreq)
end

function niScope_CalAdjustDCM(vi, channelName, stimulusFreq)
    ccall((:niScope_CalAdjustDCM, libniscope), ViStatus, (ViSession, ViConstString, ViReal64), vi, channelName, stimulusFreq)
end

function niScope_CalAdjustOffset(vi, channelName, rng)
    ccall((:niScope_CalAdjustOffset, libniscope), ViStatus, (ViSession, ViConstString, ViReal64), vi, channelName, rng)
end

function niScope_CalAdjustOffsetRange(vi, channelName, rng, stimulus)
    ccall((:niScope_CalAdjustOffsetRange, libniscope), ViStatus, (ViSession, ViConstString, ViReal64, ViReal64), vi, channelName, rng, stimulus)
end

function niScope_CalAdjustCompensationAttenuator(vi, channelName, rng)
    ccall((:niScope_CalAdjustCompensationAttenuator, libniscope), ViStatus, (ViSession, ViConstString, ViReal64), vi, channelName, rng)
end

function niScope_CalAdjustFrequencyResponse(vi, channelName, rng, stimulusFreq, stimulusAmp)
    ccall((:niScope_CalAdjustFrequencyResponse, libniscope), ViStatus, (ViSession, ViConstString, ViReal64, ViReal64, ViReal64), vi, channelName, rng, stimulusFreq, stimulusAmp)
end

function niScope_CalAdjustInternalReference(vi, option, stimulus)
    ccall((:niScope_CalAdjustInternalReference, libniscope), ViStatus, (ViSession, ViInt32, ViReal64), vi, option, stimulus)
end

function niScope_CalRouteInternalReference(vi, option, whichReference)
    ccall((:niScope_CalRouteInternalReference, libniscope), ViStatus, (ViSession, ViInt32, ViInt32), vi, option, whichReference)
end

function niScope_CalAdjustAccessoryGainAndOffset(vi, channelName, posFs, gnd, negFs)
    ccall((:niScope_CalAdjustAccessoryGainAndOffset, libniscope), ViStatus, (ViSession, ViConstString, ViReal64, ViReal64, ViReal64), vi, channelName, posFs, gnd, negFs)
end

function niScope_CalSetAccessorySource(vi, channelName, calSource)
    ccall((:niScope_CalSetAccessorySource, libniscope), ViStatus, (ViSession, ViConstString, ViInt32), vi, channelName, calSource)
end

function niScope_CalMeasureRISDistribution(vi, channelName, maxTime, minBinPercent, distributionSize, distribution)
    ccall((:niScope_CalMeasureRISDistribution, libniscope), ViStatus, (ViSession, ViConstString, ViInt32, Ptr{ViReal64}, ViInt32, Ptr{ViInt32}), vi, channelName, maxTime, minBinPercent, distributionSize, distribution)
end