text:
#! format: off

abstract type AbstractRegulationFormulation <: AbstractDeviceFormulation end
struct ReserveLimitedRegulation <: AbstractRegulationFormulation end
struct DeviceLimitedRegulation <: AbstractRegulationFormulation end

get_variable_sign(_, ::Type{PSY.RegulationDevice{PSY.ThermalStandard}}, ::DeviceLimitedRegulation) = NaN
############################ DeltaActivePowerUpVariable, RegulationDevice ###########################

get_variable_binary(::DeltaActivePowerUpVariable, ::Type{<:PSY.RegulationDevice}, ::AbstractRegulationFormulation) = false
get_variable_lower_bound(::DeltaActivePowerUpVariable, ::PSY.RegulationDevice, ::AbstractRegulationFormulation) = 0.0

############################ DeltaActivePowerDownVariable, RegulationDevice ###########################

get_variable_binary(::DeltaActivePowerDownVariable, ::Type{<:PSY.RegulationDevice}, ::AbstractRegulationFormulation) = false
get_variable_lower_bound(::DeltaActivePowerDownVariable, ::PSY.RegulationDevice, ::AbstractRegulationFormulation) = 0.0

############################ AdditionalDeltaActivePowerUpVariable, RegulationDevice ###########################

get_variable_binary(::AdditionalDeltaActivePowerUpVariable, ::Type{<:PSY.RegulationDevice}, ::AbstractRegulationFormulation) = false
get_variable_lower_bound(::AdditionalDeltaActivePowerUpVariable, ::PSY.RegulationDevice, ::AbstractRegulationFormulation) = 0.0

############################ AdditionalDeltaActivePowerDownVariable, RegulationDevice ###########################

get_variable_binary(::AdditionalDeltaActivePowerDownVariable, ::Type{<:PSY.RegulationDevice}, ::AbstractRegulationFormulation) = false
get_variable_lower_bound(::AdditionalDeltaActivePowerDownVariable, ::PSY.RegulationDevice, ::AbstractRegulationFormulation) = 0.0

#! format: on

function add_constraints!(
    optimization_container::OptimizationContainer,
    ::Type{RangeConstraint},
    ::Type{DeltaActivePowerUpVariable},
    devices::IS.FlattenIteratorWrapper{PSY.RegulationDevice{T}},
    ::DeviceModel{PSY.RegulationDevice{T}, DeviceLimitedRegulation},
    ::Type{AreaBalancePowerModel},
    ::Nothing,
) where {T <: PSY.StaticInjection}
    parameters = model_has_parameters(optimization_container)
    var_name_up = make_variable_name(DeltaActivePowerUpVariable, T)
    var_up = get_variable(optimization_container, var_name_up)

    names = [PSY.get_name(g) for g in devices]
    time_steps = model_time_steps(optimization_container)

    up = Symbol("regulation_limits_up_$(T)")
    container_up = add_cons_container!(optimization_container, up, names, time_steps)

    constraint_infos = Vector{DeviceTimeSeriesConstraintInfo}(undef, length(devices))
    for (ix, d) in enumerate(devices)
        ts_vector = get_time_series(optimization_container, d, "max_active_power")
        constraint_info = DeviceTimeSeriesConstraintInfo(
            d,
            x -> PSY.get_max_active_power(x),
            ts_vector,
            x -> PSY.get_active_power_limits(x),
        )
        constraint_infos[ix] = constraint_info
    end

    if parameters
        base_points_param = get_parameter_container(
            optimization_container,
            make_variable_name(ACTIVE_POWER, T),
        )
        multiplier = get_multiplier_array(base_points_param)
        base_points = get_parameter_array(base_points_param)
    end

    for d in constraint_infos
        name = get_component_name(d)
        limits = get_limits(d)
        for t in time_steps
            rating = parameters ? multiplier[name, t] : d.multiplier
            base_point = parameters ? base_points[name, t] : get_timeseries(d)[t]
            container_up[name, t] = JuMP.@constraint(
                optimization_container.JuMPmodel,
                var_up[name, t] <= limits.max - base_point * rating
            )
        end
    end
    return
end

function add_constraints!(
    optimization_container::OptimizationContainer,
    ::Type{RangeConstraint},
    ::Type{DeltaActivePowerDownVariable},
    devices::IS.FlattenIteratorWrapper{PSY.RegulationDevice{T}},
    ::DeviceModel{PSY.RegulationDevice{T}, DeviceLimitedRegulation},
    ::Type{AreaBalancePowerModel},
    ::Nothing,
) where {T <: PSY.StaticInjection}
    parameters = model_has_parameters(optimization_container)
    var_name_dn = make_variable_name(DeltaActivePowerDownVariable, T)
    var_dn = get_variable(optimization_container, var_name_dn)

    names = [PSY.get_name(g) for g in devices]
    time_steps = model_time_steps(optimization_container)

    dn = Symbol("regulation_limits_dn_$(T)")
    container_dn = add_cons_container!(optimization_container, dn, names, time_steps)

    constraint_infos = Vector{DeviceTimeSeriesConstraintInfo}(undef, length(devices))
    for (ix, d) in enumerate(devices)
        ts_vector = get_time_series(optimization_container, d, "max_active_power")
        constraint_info = DeviceTimeSeriesConstraintInfo(
            d,
            x -> PSY.get_max_active_power(x),
            ts_vector,
            x -> PSY.get_active_power_limits(x),
        )
        constraint_infos[ix] = constraint_info
    end

    if parameters
        base_points_param = get_parameter_container(
            optimization_container,
            make_variable_name(ACTIVE_POWER, T),
        )
        multiplier = get_multiplier_array(base_points_param)
        base_points = get_parameter_array(base_points_param)
    end

    for d in constraint_infos
        name = get_component_name(d)
        limits = get_limits(d)
        for t in time_steps
            rating = parameters ? multiplier[name, t] : d.multiplier
            base_point = parameters ? base_points[name, t] : get_timeseries(d)[t]
            container_dn[name, t] = JuMP.@constraint(
                optimization_container.JuMPmodel,
                var_dn[name, t] <= base_point * rating - limits.min
            )
        end
    end
    return
end

function add_constraints!(
    optimization_container::OptimizationContainer,
    ::Type{RangeConstraint},
    ::Type{DeltaActivePowerUpVariable},
    devices::IS.FlattenIteratorWrapper{PSY.RegulationDevice{T}},
    ::DeviceModel{PSY.RegulationDevice{T}, ReserveLimitedRegulation},
    ::Type{AreaBalancePowerModel},
    ::Nothing,
) where {T <: PSY.StaticInjection}
    var_name_up = make_variable_name(DeltaActivePowerUpVariable, T)
    var_up = get_variable(optimization_container, var_name_up)

    names = [PSY.get_name(g) for g in devices]
    time_steps = model_time_steps(optimization_container)

    up = Symbol("regulation_limits_up_$(T)")
    container_up = add_cons_container!(optimization_container, up, names, time_steps)

    for d in devices
        name = PSY.get_name(d)
        limit_up = PSY.get_reserve_limit_up(d)
        for t in time_steps
            container_up[name, t] = JuMP.@constraint(
                optimization_container.JuMPmodel,
                var_up[name, t] <= limit_up
            )
        end
    end
    return
end

function add_constraints!(
    optimization_container::OptimizationContainer,
    ::Type{RangeConstraint},
    ::Type{DeltaActivePowerDownVariable},
    devices::IS.FlattenIteratorWrapper{PSY.RegulationDevice{T}},
    ::DeviceModel{PSY.RegulationDevice{T}, ReserveLimitedRegulation},
    ::Type{AreaBalancePowerModel},
    ::Nothing,
) where {T <: PSY.StaticInjection}
    var_name_dn = make_variable_name(DeltaActivePowerDownVariable, T)
    var_dn = get_variable(optimization_container, var_name_dn)

    names = [PSY.get_name(g) for g in devices]
    time_steps = model_time_steps(optimization_container)

    dn = Symbol("regulation_limits_dn_$(T)")
    container_dn = add_cons_container!(optimization_container, dn, names, time_steps)

    for d in devices
        name = PSY.get_name(d)
        limit_up = PSY.get_reserve_limit_dn(d)
        for t in time_steps
            container_dn[name, t] = JuMP.@constraint(
                optimization_container.JuMPmodel,
                var_dn[name, t] <= limit_up
            )
        end
    end
    return
end

function ramp_constraints!(
    optimization_container::OptimizationContainer,
    devices::IS.FlattenIteratorWrapper{PSY.RegulationDevice{T}},
    ::DeviceModel{PSY.RegulationDevice{T}, DeviceLimitedRegulation},
    ::Type{AreaBalancePowerModel},
    ::Nothing,
) where {T <: PSY.ThermalStandard}
    R_up = get_variable(optimization_container, DeltaActivePowerUpVariable, T)
    R_dn = get_variable(optimization_container, DeltaActivePowerDownVariable, T)

    resolution = Dates.value(Dates.Second(model_resolution(optimization_container)))
    names = [PSY.get_name(g) for g in devices]
    time_steps = model_time_steps(optimization_container)

    container_up =
        add_cons_container!(optimization_container, :ramp_limits_up, names, time_steps)
    container_dn =
        add_cons_container!(optimization_container, :ramp_limits_dn, names, time_steps)

    for d in devices
        ramp_limits = PSY.get_ramp_limits(d)
        ramp_limits === nothing && continue
        scaling_factor = resolution * SECONDS_IN_MINUTE
        name = PSY.get_name(d)
        for t in time_steps
            container_up[name, t] = JuMP.@constraint(
                optimization_container.JuMPmodel,
                R_up[name, t] <= ramp_limits.up * scaling_factor
            )
            container_dn[name, t] = JuMP.@constraint(
                optimization_container.JuMPmodel,
                R_dn[name, t] <= ramp_limits.down * scaling_factor
            )
        end
    end
    return
end

function participation_assignment!(
    optimization_container::OptimizationContainer,
    devices::IS.FlattenIteratorWrapper{PSY.RegulationDevice{T}},
    ::DeviceModel{PSY.RegulationDevice{T}, <:AbstractRegulationFormulation},
    ::Type{AreaBalancePowerModel},
    ::Nothing,
) where {T <: PSY.StaticInjection}
    time_steps = model_time_steps(optimization_container)
    R_up = get_variable(optimization_container, DeltaActivePowerUpVariable, T)
    R_dn = get_variable(optimization_container, DeltaActivePowerDownVariable, T)
    R_up_emergency =
        get_variable(optimization_container, AdditionalDeltaActivePowerUpVariable, T)
    R_dn_emergency =
        get_variable(optimization_container, AdditionalDeltaActivePowerUpVariable, T)
    area_reserve_up =
        get_variable(optimization_container, DeltaActivePowerUpVariable, PSY.Area)
    area_reserve_dn =
        get_variable(optimization_container, DeltaActivePowerDownVariable, PSY.Area)

    component_names = [PSY.get_name(d) for d in devices]
    participation_assignment_up = JuMPConstraintArray(undef, component_names, time_steps)
    participation_assignment_dn = JuMPConstraintArray(undef, component_names, time_steps)
    assign_constraint!(
        optimization_container,
        "participation_assignment_up",
        participation_assignment_up,
    )
    assign_constraint!(
        optimization_container,
        "participation_assignment_dn",
        participation_assignment_dn,
    )

    expr_up = get_expression(optimization_container, :emergency_up)
    expr_dn = get_expression(optimization_container, :emergency_dn)
    for d in devices
        name = PSY.get_name(d)
        services = PSY.get_services(d)
        if length(services) > 1
            device_agc = (a for a in PSY.get_services(d) if isa(a, PSY.AGC))
            area_name = PSY.get_name.(PSY.get_area.(device_agc))[1]
        else
            device_agc = first(services)
            area_name = PSY.get_name(PSY.get_area(device_agc))
        end
        p_factor = PSY.get_participation_factor(d)
        for t in time_steps
            participation_assignment_up[name, t] = JuMP.@constraint(
                optimization_container.JuMPmodel,
                R_up[name, t] ==
                (p_factor.up * area_reserve_up[area_name, t]) + R_up_emergency[name, t]
            )
            participation_assignment_dn[name, t] = JuMP.@constraint(
                optimization_container.JuMPmodel,
                R_dn[name, t] ==
                (p_factor.dn * area_reserve_dn[area_name, t]) + R_dn_emergency[name, t]
            )
            JuMP.add_to_expression!(expr_up[area_name, t], -1 * R_up_emergency[name, t])
            JuMP.add_to_expression!(expr_dn[area_name, t], -1 * R_dn_emergency[name, t])
        end
    end

    return
end

function regulation_cost!(
    optimization_container::OptimizationContainer,
    devices::IS.FlattenIteratorWrapper{PSY.RegulationDevice{T}},
    ::DeviceModel{PSY.RegulationDevice{T}, <:AbstractRegulationFormulation},
) where {T <: PSY.StaticInjection}
    time_steps = model_time_steps(optimization_container)
    R_up = get_variable(optimization_container, DeltaActivePowerUpVariable, T)
    R_dn = get_variable(optimization_container, DeltaActivePowerDownVariable, T)
    R_up_emergency =
        get_variable(optimization_container, AdditionalDeltaActivePowerUpVariable, T)
    R_dn_emergency =
        get_variable(optimization_container, AdditionalDeltaActivePowerUpVariable, T)

    for d in devices
        cost = PSY.get_cost(d)
        p_factor = PSY.get_participation_factor(d)
        up_cost =
            isapprox(p_factor.up, 0.0; atol = 1e-2) ? SERVICES_SLACK_COST : 1 / p_factor.up
        dn_cost =
            isapprox(p_factor.dn, 0.0; atol = 1e-2) ? SERVICES_SLACK_COST : 1 / p_factor.dn
        for t in time_steps
            JuMP.add_to_expression!(
                optimization_container.cost_function,
                R_up_emergency[PSY.get_name(d), t],
                up_cost,
            )
            JuMP.add_to_expression!(
                optimization_container.cost_function,
                R_dn_emergency[PSY.get_name(d), t],
                dn_cost,
            )
        end
    end
    return
end

function NodalExpressionSpec(
    ::Type{<:PSY.RegulationDevice{T}},
    ::Type{AreaBalancePowerModel},
    use_forecasts::Bool,
) where {T <: PSY.StaticInjection}
    return NodalExpressionSpec(
        "max_active_power",
        make_variable_name(ActivePowerVariable, T),
        use_forecasts ? x -> PSY.get_max_active_power(x) : x -> PSY.get_active_power(x),
        1.0,
        JuMP.VariableRef,
    )
end


text:
include("graph.jl")

println("*************************")
println("* _____   ____   ____   _____  ")
println("*|_   _| | ___| | ___| |_   _| ")
println("*  | |   | ___| |___ |   | |   "_)
println("*  |_|   |____| |____|   |_|   ")
println("*    ")
println("*")
println("")
println("")
println("comamndes : ")
println(" 1 - graphe aléatoire ")
println(" 2 - graphe tiré d'un fichier")

ext: jl


text:
# using ImageFeatures, Images
struct BlockTracker
	search_size::Int
	flow_feature_threshold::Int
	flow_value_threshold::Int
	features::Keypoints
	"Function used for block matching (compute_sad, compute_ssd, compute_ncc)"
	matchFunction::Function
	REGION_SIZE::Int # this is used as a constant for implimentation of BlockTracker and should not be changed
	BlockTracker() = new()
	BlockTracker(search_size,flow_feature_threshold,flow_value_threshold,keypoints,matchFunction,REGION_SIZE) = new(search_size,flow_feature_threshold,flow_value_threshold,keypoints,matchFunction,REGION_SIZE)
end
BlockTracker(keypoints::Keypoints; search_size = 10, flow_feature_threshold = 1000, flow_value_threshold = 50000, matchFunction = compute_ssd,REGION_SIZE = 10) = BlockTracker(search_size,flow_feature_threshold,flow_value_threshold,keypoints,matchFunction,REGION_SIZE)

##

function compute_diff(image, offX::T, offY::T, REGION_SIZE::T) where {T<:Integer}

	im_roi = image[offX:offX+REGION_SIZE-1,offY:offY+REGION_SIZE-1]
	acc = sum(abs.(diff(im_roi,1))) + sum(abs.(diff(im_roi,2)))

	return acc;

end

"""
    compute_sad(image1, image2, off1X, off1Y, off2X, off2Y, REGION_SIZE)

  Compute Sum of Absolute Differences of two regions with size REGION_SIZE.

"""
function compute_sad(image1, image2, off1X::T, off1Y::T, off2X::T, off2Y::T, REGION_SIZE::T) where {T<:Integer}

	im1_r = view(image1,off1X:off1X+REGION_SIZE-1,off1Y:off1Y+REGION_SIZE-1)
	im2_r = view(image2,off2X:off2X+REGION_SIZE-1,off2Y:off2Y+REGION_SIZE-1)

	acc = sum(abs.(im1_r .- im2_r))

	return acc;
end

"""
    compute_ssd(image1, image2, off1X, off1Y, off2X, off2Y, REGION_SIZE)

  Compute Sum of Squared Differences of two regions with REGION_SIZE.

"""
function compute_ssd(image1, image2, off1X::T, off1Y::T, off2X::T, off2Y::T, REGION_SIZE::T) where {T<:Integer}

	im1_r = view(image1,off1X:off1X+REGION_SIZE-1,off1Y:off1Y+REGION_SIZE-1)
	im2_r = view(image2,off2X:off2X+REGION_SIZE-1,off2Y:off2Y+REGION_SIZE-1)

	acc = sum((im1_r .- im2_r).^2)

	return acc;
end

"""
    compute_ncc(image1, image2, off1X, off1Y, off2X, off2Y, REGION_SIZE)

  Compute the normalized cross-correlation of two regions with size REGION_SIZE.

"""
function compute_ncc(image1, image2, off1X::T, off1Y::T, off2X::T, off2Y::T, REGION_SIZE::T) where {T<:Integer}

	im1_r = Float32.(image1[off1X:off1X+REGION_SIZE-1,off1Y:off1Y+REGION_SIZE-1])
	im2_r = Float32.(image2[off2X:off2X+REGION_SIZE-1,off2Y:off2Y+REGION_SIZE-1])

	acc = (1 - ncc(im1_r,im2_r))

	return acc;
end

"""
    block_tracker(tracker::BlockTracker, image1, image2)

  Track features between two images.

"""
function block_tracker!(tracker::BlockTracker, image1::Array{Int32}, image2::Array{Int32})
	REGION_SIZE = tracker.REGION_SIZE # x & y tile size
	#constants
	ro,co = size(image1)
	winmin = -tracker.search_size
	winmax = tracker.search_size

	# hist_size = 2 * (winmax - winmin + 1) + 1

	#variables
	pixLo = tracker.search_size + 1
	pixHiro = ro - (tracker.search_size + 1) - REGION_SIZE
	pixHico = co - (tracker.search_size + 1) - REGION_SIZE

	# return if no features exists
	if (size(tracker.features[:],1) == 0)
		println("no features!")
		return 0
	end

	meanflowx = 0.0
	meanflowy = 0.0
	meancount = 0

	for f_inx = 1:size(tracker.features,1)

		#indexes of upper left corner
		i = tracker.features[f_inx][1] - div(REGION_SIZE,2)
		j = tracker.features[f_inx][2] - div(REGION_SIZE,2)

		#check if feautes is to close to edge
		if !((pixLo < i < pixHiro) && (pixLo < j < pixHico))
			#(trow away by making 0)???
			tracker.features[f_inx] = CartesianIndex(0,0)
			continue;
		end

		#test if pixel is ok for tracking
		if (compute_diff(image1, i, j, REGION_SIZE) < tracker.flow_feature_threshold)
			tracker.features[f_inx] = CartesianIndex(0,0)
			continue;
		end

		dist = tracker.flow_value_threshold*10000  # set initial distance to "infinity"
		sumx = 0
		sumy = 0

		for jj = winmin:winmax
			for ii = winmin:winmax
				temp_dist = tracker.matchFunction(image1, image2, i, j, i + ii, j + jj, REGION_SIZE)

				if (temp_dist < dist)
					sumx = ii;
					sumy = jj;
					dist = temp_dist;
				end
			end
		end

		#= acceptance SAD distance threshhold =#
		if (dist < tracker.flow_value_threshold)
			meanflowx += sumx;
			meanflowy += sumy;
			meancount+=1

			#update feature positions
			tracker.features[f_inx] += CartesianIndex(sumx,sumy)
		else
			# (trow away by making 0)?????
			tracker.features[f_inx] = CartesianIndex(0,0)
		end
	end

	#return number of features under threshold
	return meancount
end

function block_tracker!(tracker::BlockTracker, image1::Matrix{Gray{N0f8}}, image2::Matrix{Gray{N0f8}})
	return block_tracker!(tracker, Int32.(reinterpret(UInt8,image1)), Int32.(reinterpret(UInt8,image2)))
end

function grid_features!(tracker::BlockTracker, image_width, image_height; NUM_BLOCKS = 10)

	regionOffset = div(tracker.REGION_SIZE,2)
    pixLo = tracker.search_size + 1
    pixHiro = image_height - (tracker.search_size + 1) - tracker.REGION_SIZE
	pixHico = image_width  - (tracker.search_size + 1) - tracker.REGION_SIZE
    pixStep = div((min(pixHiro,pixHico) - pixLo), NUM_BLOCKS + 1)

    # add block features to existing
    # must be a better way??
    for i = pixLo:pixStep:pixHiro
        for j = pixLo:pixStep:pixHico
            push!(tracker.features, CartesianIndex.(i+regionOffset,j+regionOffset))
        end
    end

end

max_stars_repo_name: dehann/SensorFeatureTracking

max_issues_repo_name: dehann/SensorFeatureTracking

max_forks_repo_name: dehann/SensorFeatureTracking


text:
#A whole bunch of splatting...
u(x; p...) = x^(1-p[:γ])/(1-p[:γ])
g(; a, γ) = a + γ #Splatting the exact named parameters!
function f(x; p...)
    x2 = g(; p...) + x * p[:a]
    return u(x2; p...)
end

#Trying
u2(x, γ) = x^(1-γ)/(1-γ)
function f2(x; p...)
    x2 = g(;p...) + x * p[:a]
    return u(x2, p[:γ])
end
kw = (a=1, γ=0.5)
f(2.0;kw...)

@btime f(2.0;$kw...)
@btime f2(2.0;$kw...) #The same.

#With a structure and no types
struct Params
    a
    γ
end
param = Params(1, 0.5)


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

mutable struct HTTPConfiguration <: SwaggerModel
    method::Any # spec type: Union{ Nothing, String } # spec name: method
    headers::Any # spec type: Union{ Nothing, Vector{HTTPHeader} } # spec name: headers
    validStatusCodes::Any # spec type: Union{ Nothing, Vector{Int32} } # spec name: validStatusCodes

    function HTTPConfiguration(;method=nothing, headers=nothing, validStatusCodes=nothing)
        o = new()
        validate_property(HTTPConfiguration, Symbol("method"), method)
        setfield!(o, Symbol("method"), method)
        validate_property(HTTPConfiguration, Symbol("headers"), headers)
        setfield!(o, Symbol("headers"), headers)
        validate_property(HTTPConfiguration, Symbol("validStatusCodes"), validStatusCodes)
        setfield!(o, Symbol("validStatusCodes"), validStatusCodes)
        o
    end
end # type HTTPConfiguration

const _property_map_HTTPConfiguration = Dict{Symbol,Symbol}(Symbol("method")=>Symbol("method"), Symbol("headers")=>Symbol("headers"), Symbol("validStatusCodes")=>Symbol("validStatusCodes"))
const _property_types_HTTPConfiguration = Dict{Symbol,String}(Symbol("method")=>"String", Symbol("headers")=>"Vector{HTTPHeader}", Symbol("validStatusCodes")=>"Vector{Int32}")
Base.propertynames(::Type{ HTTPConfiguration }) = collect(keys(_property_map_HTTPConfiguration))
Swagger.property_type(::Type{ HTTPConfiguration }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_HTTPConfiguration[name]))}
Swagger.field_name(::Type{ HTTPConfiguration }, property_name::Symbol) =  _property_map_HTTPConfiguration[property_name]

const _allowed_HTTPConfiguration_method = ["Get"]

function check_required(o::HTTPConfiguration)
    true
end

function validate_property(::Type{ HTTPConfiguration }, name::Symbol, val)
    if name === Symbol("method")
        Swagger.validate_param(name, "HTTPConfiguration", :enum, val, _allowed_HTTPConfiguration_method)
    end
end


text:
using CallGraphs
using Base.Test

const JULIA_ROOT = splitdir(splitdir(JULIA_HOME)[1])[1]
const CallGraphs_ROOT = Pkg.dir("CallGraphs")
const jlsrc_script = joinpath(CallGraphs_ROOT, "callgraph_jlsrc.bash")

gcnames = cd(joinpath(JULIA_ROOT, "src")) do
    run(`bash $jlsrc_script`)
    gcnames = findgc()
end
@test "array_resize_buffer" in gcnames


text:
module Obj
@enum ObjCode::UInt8 commit=1 tree=2 blob=3 tag=4 offset_delta=6 ref_delta=7
end
import .Obj.ObjCode

function ObjCode(name::AbstractString)
    name == "commit" ? Obj.commit :
    name == "tree"   ? Obj.tree   :
    name == "blob"   ? Obj.blob   :
    name == "tag"    ? Obj.tag    :
    error("unknown tag type $name")
end

struct GitRawObject <: GitObject
    objcode::ObjCode
    data::Vector{UInt8}
end

function oid(raw::GitRawObject)
    ctx = SHA.SHA1_CTX()
    SHA.update!(ctx, Vector{UInt8}("$(raw.objcode) $(sizeof(raw.data))\0"))
    SHA.update!(ctx, raw.data)
    return SHA1(SHA.digest!(ctx))
end

max_stars_repo_name: simonbyrne/GitX

max_issues_repo_name: simonbyrne/GitX

max_forks_repo_name: simonbyrne/GitX


text:
# initialize train_nodes
function grow_tree(δ, δ², 𝑤,
    hist_δ, hist_δ², hist_𝑤,
    params::Union{EvoTreeRegressor,EvoTreeCount,EvoTreeClassifier,EvoTreeGaussian},
    train_nodes::Vector{TrainNode{L,T,S}},
    splits::Vector{SplitInfo{L,T,Int}},
    edges, X_bin) where {R<:Real, T<:AbstractFloat, S<:Int, L}

    active_id = ones(Int, 1)
    leaf_count = one(Int)
    tree_depth = one(Int)
    tree = Tree(Vector{TreeNode{params.K, T, Int, Bool}}())

    # grow while there are remaining active nodes
    while size(active_id, 1) > 0 && tree_depth <= params.max_depth
        next_active_id = ones(Int, 0)
        # grow nodes
        for id in active_id
            node = train_nodes[id]
            if tree_depth == params.max_depth || node.∑𝑤[1] <= params.min_weight
                push!(tree.nodes, TreeNode(pred_leaf(params.loss, node, params, δ²)))
            else
                @threads for feat in node.𝑗
                    splits[feat].gain = node.gain
                    find_split_static!(hist_δ[feat], hist_δ²[feat], hist_𝑤[feat], view(X_bin,:,feat), δ, δ², 𝑤, node.∑δ, node.∑δ², node.∑𝑤, params, splits[feat], edges[feat], node.𝑖)
                    # update_hist!(hist_δ, hist_δ², hist_𝑤, X_bin, δ, δ², 𝑤, set, feat)
                    # find_split!(hist_δ[feat], hist_δ²[feat], hist_𝑤[feat], node.∑δ, node.∑δ², node.∑𝑤, params, splits[feat], edges[feat], feat)
                end
                # assign best split
                best = get_max_gain(splits)
                # grow node if best split improve gain
                if best.gain > node.gain + params.γ
                    left, right = update_set(node.𝑖, best.𝑖, view(X_bin,:,best.feat))
                    train_nodes[leaf_count + 1] = TrainNode(node.depth + 1, best.∑δL, best.∑δ²L, best.∑𝑤L, best.gainL, left, node.𝑗)
                    train_nodes[leaf_count + 2] = TrainNode(node.depth + 1, best.∑δR, best.∑δ²R, best.∑𝑤R, best.gainR, right, node.𝑗)
                    # push split Node
                    push!(tree.nodes, TreeNode(leaf_count + 1, leaf_count + 2, best.feat, best.cond, params.K))
                    push!(next_active_id, leaf_count + 1)
                    push!(next_active_id, leaf_count + 2)
                    leaf_count += 2
                else
                    push!(tree.nodes, TreeNode(pred_leaf(params.loss, node, params, δ²)))
                end # end of single node split search
            end
        end # end of loop over active ids for a given depth
        active_id = next_active_id
        tree_depth += 1
    end # end of tree growth
    return tree
end

# extract the gain value from the vector of best splits and return the split info associated with best split
function get_max_gain(splits::Vector{SplitInfo{L,T,S}}) where {L,T,S}
    gains = (x -> x.gain).(splits)
    feat = findmax(gains)[2]
    best = splits[feat]
    return best
end

# grow_gbtree
function grow_gbtree(X::AbstractArray{R, 2}, Y::AbstractVector{S}, params::Union{EvoTreeRegressor,EvoTreeCount,EvoTreeClassifier,EvoTreeGaussian};
    X_eval::AbstractArray{R, 2} = Array{R, 2}(undef, (0,0)), Y_eval::AbstractVector{S} = Vector{S}(undef, 0),
    early_stopping_rounds=Int(1e5), print_every_n=100, verbosity=1) where {R<:Real, S<:Real}

    seed!(params.seed)

    μ = ones(params.K)
    μ .*= mean(Y)
    if typeof(params.loss) == Logistic
        μ .= logit.(μ)
    elseif typeof(params.loss) == Poisson
        μ .= log.(μ)
    elseif typeof(params.loss) == Softmax
        μ .*= 0.0
    elseif typeof(params.loss) == Gaussian
        μ = SVector{2}([mean(Y), log(var(Y))])
    end

    # initialize preds
    pred = zeros(SVector{params.K,Float64}, size(X,1))
    for i in eachindex(pred)
        pred[i] += μ
    end

    # eval init
    if size(Y_eval, 1) > 0
        # pred_eval = ones(size(Y_eval, 1), params.K) .* μ'
        pred_eval = zeros(SVector{params.K,Float64}, size(X_eval,1))
        for i in eachindex(pred_eval)
            pred_eval[i] += μ
        end
    end

    # bias = Tree([TreeNode(SVector{1, Float64}(μ))])
    bias = Tree([TreeNode(SVector{params.K,Float64}(μ))])
    gbtree = GBTree([bias], params, Metric())

    X_size = size(X)
    𝑖_ = collect(1:X_size[1])
    𝑗_ = collect(1:X_size[2])

    # initialize gradients and weights
    δ = zeros(SVector{params.K, Float64}, X_size[1])
    δ² = zeros(SVector{params.K, Float64}, X_size[1])
    𝑤 = zeros(SVector{1, Float64}, X_size[1])
    for i in eachindex(𝑤)
        𝑤[i] += ones(1)
    end

    edges = get_edges(X, params.nbins)
    X_bin = binarize(X, edges)

    # initialize train nodes
    train_nodes = Vector{TrainNode{params.K, Float64, Int64}}(undef, 2^params.max_depth-1)
    for node in 1:2^params.max_depth-1
        train_nodes[node] = TrainNode(0, SVector{params.K, Float64}(fill(-Inf, params.K)), SVector{params.K, Float64}(fill(-Inf, params.K)), SVector{1, Float64}(fill(-Inf, 1)), -Inf, [0], [0])
    end

    # initializde node splits info and tracks - colsample size (𝑗)
    splits = Vector{SplitInfo{params.K, Float64, Int64}}(undef, X_size[2])
    hist_δ = Vector{Vector{SVector{params.K, Float64}}}(undef, X_size[2])
    hist_δ² = Vector{Vector{SVector{params.K, Float64}}}(undef, X_size[2])
    hist_𝑤 = Vector{Vector{SVector{1, Float64}}}(undef, X_size[2])
    for feat in 𝑗_
        splits[feat] = SplitInfo{params.K, Float64, Int}(-Inf, SVector{params.K, Float64}(zeros(params.K)), SVector{params.K, Float64}(zeros(params.K)), SVector{1, Float64}(zeros(1)), SVector{params.K, Float64}(zeros(params.K)), SVector{params.K, Float64}(zeros(params.K)), SVector{1, Float64}(zeros(1)), -Inf, -Inf, 0, feat, 0.0)
        hist_δ[feat] = zeros(SVector{params.K, Float64}, length(edges[feat]))
        hist_δ²[feat] = zeros(SVector{params.K, Float64}, length(edges[feat]))
        hist_𝑤[feat] = zeros(SVector{1, Float64}, length(edges[feat]))
    end

    # initialize metric
    if params.metric != :none
        metric_track = Metric()
        metric_best = Metric()
        iter_since_best = 0
    end

    # loop over nrounds
    for i in 1:params.nrounds
        # select random rows and cols
        𝑖 = 𝑖_[sample(𝑖_, ceil(Int, params.rowsample * X_size[1]), replace=false, ordered=true)]
        𝑗 = 𝑗_[sample(𝑗_, ceil(Int, params.colsample * X_size[2]), replace=false, ordered=true)]

        # reset gain to -Inf
        for feat in 𝑗_
            splits[feat].gain = -Inf
        end

        # get gradients
        update_grads!(params.loss, params.α, pred, Y, δ, δ², 𝑤)
        ∑δ, ∑δ², ∑𝑤 = sum(δ[𝑖]), sum(δ²[𝑖]), sum(𝑤[𝑖])
        gain = get_gain(params.loss, ∑δ, ∑δ², ∑𝑤, params.λ)

        # assign a root and grow tree
        train_nodes[1] = TrainNode(1, ∑δ, ∑δ², ∑𝑤, gain, 𝑖, 𝑗)
        tree = grow_tree(δ, δ², 𝑤, hist_δ, hist_δ², hist_𝑤, params, train_nodes, splits, edges, X_bin)
        # push new tree to model
        push!(gbtree.trees, tree)
        # update predictions
        predict!(pred, tree, X)
        # eval predictions
        if size(Y_eval, 1) > 0
            predict!(pred_eval, tree, X_eval)
        end

        # callback function
        if params.metric != :none
            if size(Y_eval, 1) > 0
                metric_track.metric .= eval_metric(Val{params.metric}(), pred_eval, Y_eval, params.α)
            else
                metric_track.metric .= eval_metric(Val{params.metric}(), pred, Y, params.α)
            end

            if metric_track.metric < metric_best.metric
                metric_best.metric .=  metric_track.metric
                metric_best.iter .=  i
            else
                iter_since_best += 1
            end

            if mod(i, print_every_n) == 0 && verbosity > 0
                display(string("iter:", i, ", eval: ", metric_track.metric))
            end
            iter_since_best >= early_stopping_rounds ? break : nothing
        end # end of callback

    end #end of nrounds

    if params.metric != :none
        gbtree.metric.iter .= metric_best.iter
        gbtree.metric.metric .= metric_best.metric
    end
    return gbtree
end

# grow_gbtree - continue training
function grow_gbtree!(model::GBTree, X::AbstractArray{R, 2}, Y::AbstractVector{S};
    X_eval::AbstractArray{R, 2} = Array{R, 2}(undef, (0,0)), Y_eval::AbstractVector{S} = Vector{S}(undef, 0),
    early_stopping_rounds=Int(1e5), print_every_n=100, verbosity=1) where {R<:Real, S<:Real}

    params = model.params
    seed!(params.seed)

    # initialize predictions - efficiency to be improved
    pred = zeros(SVector{params.K,Float64}, size(X,1))
    pred_ = predict(model, X)
    for i in eachindex(pred)
        pred[i] = SVector{params.K,Float64}(pred_[i])
    end
    # eval init
    if size(Y_eval, 1) > 0
        pred_eval = zeros(SVector{params.K,Float64}, size(X_eval,1))
        pred_eval_ = predict(model, X_eval)
        for i in eachindex(pred_eval)
            pred_eval[i] = SVector{params.K,Float64}(pred_eval_[i])
        end
    end

    X_size = size(X)
    𝑖_ = collect(1:X_size[1])
    𝑗_ = collect(1:X_size[2])

    # initialize gradients and weights
    δ, δ² = zeros(SVector{params.K, Float64}, X_size[1]), zeros(SVector{params.K, Float64}, X_size[1])
    𝑤 = zeros(SVector{1, Float64}, X_size[1]) .+ 1

    edges = get_edges(X, params.nbins)
    X_bin = binarize(X, edges)

    # initialize train nodes
    train_nodes = Vector{TrainNode{params.K, Float64, Int64}}(undef, 2^params.max_depth-1)
    for node in 1:2^params.max_depth-1
        train_nodes[node] = TrainNode(0, SVector{params.K, Float64}(fill(-Inf, params.K)), SVector{params.K, Float64}(fill(-Inf, params.K)), SVector{1, Float64}(fill(-Inf, 1)), -Inf, [0], [0])
    end

    # initializde node splits info and tracks - colsample size (𝑗)
    splits = Vector{SplitInfo{params.K, Float64, Int64}}(undef, X_size[2])
    hist_δ = Vector{Vector{SVector{params.K, Float64}}}(undef, X_size[2])
    hist_δ² = Vector{Vector{SVector{params.K, Float64}}}(undef, X_size[2])
    hist_𝑤 = Vector{Vector{SVector{1, Float64}}}(undef, X_size[2])
    for feat in 𝑗_
        splits[feat] = SplitInfo{params.K, Float64, Int}(-Inf, SVector{params.K, Float64}(zeros(params.K)), SVector{params.K, Float64}(zeros(params.K)), SVector{1, Float64}(zeros(1)), SVector{params.K, Float64}(zeros(params.K)), SVector{params.K, Float64}(zeros(params.K)), SVector{1, Float64}(zeros(1)), -Inf, -Inf, 0, feat, 0.0)
        hist_δ[feat] = zeros(SVector{params.K, Float64}, length(edges[feat]))
        hist_δ²[feat] = zeros(SVector{params.K, Float64}, length(edges[feat]))
        hist_𝑤[feat] = zeros(SVector{1, Float64}, length(edges[feat]))
    end

    # initialize metric
    if params.metric != :none
        metric_track = model.metric
        metric_best = model.metric
        iter_since_best = 0
    end

    # loop over nrounds
    for i in 1:params.nrounds
        # select random rows and cols
        𝑖 = 𝑖_[sample(𝑖_, ceil(Int, params.rowsample * X_size[1]), replace=false, ordered=true)]
        𝑗 = 𝑗_[sample(𝑗_, ceil(Int, params.colsample * X_size[2]), replace=false, ordered=true)]

        # reset gain to -Inf
        for feat in 𝑗_
            splits[feat].gain = -Inf
        end

        # get gradients
        update_grads!(params.loss, params.α, pred, Y, δ, δ², 𝑤)
        ∑δ, ∑δ², ∑𝑤 = sum(δ[𝑖]), sum(δ²[𝑖]), sum(𝑤[𝑖])
        gain = get_gain(params.loss, ∑δ, ∑δ², ∑𝑤, params.λ)

        # assign a root and grow tree
        train_nodes[1] = TrainNode(1, ∑δ, ∑δ², ∑𝑤, gain, 𝑖, 𝑗)
        tree = grow_tree(δ, δ², 𝑤, hist_δ, hist_δ², hist_𝑤, params, train_nodes, splits, edges, X_bin)

        # update push tree to model
        push!(model.trees, tree)

        # get update predictions
        predict!(pred, tree, X)
        # eval predictions
        if size(Y_eval, 1) > 0
            predict!(pred_eval, tree, X_eval)
        end

        # callback function
        if params.metric != :none

            if size(Y_eval, 1) > 0
                metric_track.metric .= eval_metric(Val{params.metric}(), pred_eval, Y_eval, params.α)
            else
                metric_track.metric .= eval_metric(Val{params.metric}(), pred, Y, params.α)
            end

            if metric_track.metric < metric_best.metric
                metric_best.metric .=  metric_track.metric
                metric_best.iter .=  i
            else
                iter_since_best += 1
            end

            if mod(i, print_every_n) == 0 && verbosity > 0
                display(string("iter:", i, ", eval: ", metric_track.metric))
            end
            iter_since_best >= early_stopping_rounds ? break : nothing
        end
    end #end of nrounds

    if params.metric != :none
        model.metric.iter .= metric_best.iter
        model.metric.metric .= metric_best.metric
    end
    return model
end

# grow_gbtree
function grow_gbtree_MLJ(X::AbstractMatrix{R}, Y::AbstractVector{S}, params::Union{EvoTreeRegressor,EvoTreeCount,EvoTreeClassifier,EvoTreeGaussian}; verbosity=1) where {R<:Real, S<:Real}

    seed!(params.seed)

    μ = ones(params.K)
    μ .*= mean(Y)
    if typeof(params.loss) == Logistic
        μ .= logit.(μ)
    elseif typeof(params.loss) == Poisson
        μ .= log.(μ)
    elseif typeof(params.loss) == Softmax
        μ .*= 0.0
    elseif typeof(params.loss) == Gaussian
        μ = SVector{2}([mean(Y), log(var(Y))])
    end

    # initialize preds
    pred = zeros(SVector{params.K,Float64}, size(X,1))
    for i in eachindex(pred)
        pred[i] += μ
    end

    # bias = Tree([TreeNode(SVector{1, Float64}(μ))])
    bias = Tree([TreeNode(SVector{params.K,Float64}(μ))])
    gbtree = GBTree([bias], params, Metric())

    X_size = size(X)
    𝑖_ = collect(1:X_size[1])
    𝑗_ = collect(1:X_size[2])

    # initialize gradients and weights
    δ, δ² = zeros(SVector{params.K, Float64}, X_size[1]), zeros(SVector{params.K, Float64}, X_size[1])
    𝑤 = zeros(SVector{1, Float64}, X_size[1]) .+ 1

    edges = get_edges(X, params.nbins)
    X_bin = binarize(X, edges)

    # initialize train nodes
    train_nodes = Vector{TrainNode{params.K, Float64, Int64}}(undef, 2^params.max_depth-1)
    for node in 1:2^params.max_depth-1
        train_nodes[node] = TrainNode(0, SVector{params.K, Float64}(fill(-Inf, params.K)), SVector{params.K, Float64}(fill(-Inf, params.K)), SVector{1, Float64}(fill(-Inf, 1)), -Inf, [0], [0])
    end

    # initializde node splits info and tracks - colsample size (𝑗)
    splits = Vector{SplitInfo{params.K, Float64, Int64}}(undef, X_size[2])
    hist_δ = Vector{Vector{SVector{params.K, Float64}}}(undef, X_size[2])
    hist_δ² = Vector{Vector{SVector{params.K, Float64}}}(undef, X_size[2])
    hist_𝑤 = Vector{Vector{SVector{1, Float64}}}(undef, X_size[2])
    for feat in 𝑗_
        splits[feat] = SplitInfo{params.K, Float64, Int}(-Inf, SVector{params.K, Float64}(zeros(params.K)), SVector{params.K, Float64}(zeros(params.K)), SVector{1, Float64}(zeros(1)), SVector{params.K, Float64}(zeros(params.K)), SVector{params.K, Float64}(zeros(params.K)), SVector{1, Float64}(zeros(1)), -Inf, -Inf, 0, feat, 0.0)
        hist_δ[feat] = zeros(SVector{params.K, Float64}, length(edges[feat]))
        hist_δ²[feat] = zeros(SVector{params.K, Float64}, length(edges[feat]))
        hist_𝑤[feat] = zeros(SVector{1, Float64}, length(edges[feat]))
    end

    # loop over nrounds
    for i in 1:params.nrounds
        # select random rows and cols
        𝑖 = 𝑖_[sample(𝑖_, ceil(Int, params.rowsample * X_size[1]), replace=false, ordered=true)]
        𝑗 = 𝑗_[sample(𝑗_, ceil(Int, params.colsample * X_size[2]), replace=false, ordered=true)]

        # reset gain to -Inf
        for feat in 𝑗_
            splits[feat].gain = -Inf
        end

        # get gradients
        update_grads!(params.loss, params.α, pred, Y, δ, δ², 𝑤)
        ∑δ, ∑δ², ∑𝑤 = sum(δ[𝑖]), sum(δ²[𝑖]), sum(𝑤[𝑖])
        gain = get_gain(params.loss, ∑δ, ∑δ², ∑𝑤, params.λ)

        # assign a root and grow tree
        train_nodes[1] = TrainNode(1, ∑δ, ∑δ², ∑𝑤, gain, 𝑖, 𝑗)
        tree = grow_tree(δ, δ², 𝑤, hist_δ, hist_δ², hist_𝑤, params, train_nodes, splits, edges, X_bin)
        # push new tree to model
        push!(gbtree.trees, tree)

        # get update predictions
        predict!(pred, tree, X)

    end #end of nrounds

    cache = (params=deepcopy(params), X=X, Y=Y, pred=pred, 𝑖_=𝑖_, 𝑗_=𝑗_, δ=δ, δ²=δ², 𝑤=𝑤, edges=edges, X_bin=X_bin,
        train_nodes=train_nodes, splits=splits, hist_δ=hist_δ, hist_δ²=hist_δ², hist_𝑤=hist_𝑤)
    # cache = (deepcopy(params), X, Y, pred, 𝑖_, 𝑗_, δ, δ², 𝑤, edges, X_bin, train_nodes, splits, hist_δ, hist_δ², hist_𝑤)
    return gbtree, cache
end

# continue training for MLJ - continue training from same dataset - all preprocessed elements passed as cache
function grow_gbtree_MLJ!(model::GBTree, cache; verbosity=1)

    params = model.params

    # initialize predictions
    # cache_params, X, Y, pred, 𝑖_, 𝑗_, δ, δ², 𝑤, edges, X_bin, train_nodes, splits, hist_δ, hist_δ², hist_𝑤 = cache
    train_nodes = cache.train_nodes
    splits = cache.splits

    X_size = size(cache.X_bin)
    δnrounds = params.nrounds - cache.params.nrounds
    # println("MLJ! δnrounds: ", δnrounds)

    # loop over nrounds
    for i in 1:δnrounds

        # select random rows and cols
        𝑖 = cache.𝑖_[sample(cache.𝑖_, ceil(Int, params.rowsample * X_size[1]), replace=false, ordered=true)]
        𝑗 = cache.𝑗_[sample(cache.𝑗_, ceil(Int, params.colsample * X_size[2]), replace=false, ordered=true)]

        # reset gain to -Inf
        for feat in cache.𝑗_
            splits[feat].gain = -Inf
        end

        # get gradients
        update_grads!(params.loss, params.α, cache.pred, cache.Y, cache.δ, cache.δ², cache.𝑤)
        ∑δ, ∑δ², ∑𝑤 = sum(cache.δ[𝑖]), sum(cache.δ²[𝑖]), sum(cache.𝑤[𝑖])
        gain = get_gain(params.loss, ∑δ, ∑δ², ∑𝑤, params.λ)

        # assign a root and grow tree
        train_nodes[1] = TrainNode(1, ∑δ, ∑δ², ∑𝑤, gain, 𝑖, 𝑗)
        tree = grow_tree(cache.δ, cache.δ², cache.𝑤, cache.hist_δ, cache.hist_δ², cache.hist_𝑤, params, train_nodes, splits, cache.edges, cache.X_bin)

        # update push tree to model
        push!(model.trees, tree)

        # get update predictions
        predict!(cache.pred, tree, cache.X)

    end #end of nrounds

    cache.params.nrounds = params.nrounds
    # cache = (deepcopy(params), X, Y, pred, 𝑖_, 𝑗_, δ, δ², 𝑤, edges, X_bin, train_nodes, splits, hist_δ, hist_δ², hist_𝑤)

    # return model, cache
    return model
end


text:
#=
Copyright 2021 BlackRock, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=#

module SeparableOptimization

using LinearAlgebra
using LDLFactorizations
using SparseArrays
using Parameters
using PiecewiseQuadratics

import Base: show

# Input data structures:
export AdmmParams, Settings, Stats, Vars

# Optimization function:
export optimize, factorize_kkt

# Utility functions:
export get_num_vars, get_num_constrs, assert_valid, show

# Termination condition types:
export CONVERGE_TERM_COND_FLAG, FIRST_VARS_TERM_COND_FLAG

include("admm_structs.jl")
include("term_conds.jl")
include("prox_cache.jl")
include("admm.jl")

end


text:
using ModernGL
using FileIO, MeshIO, GLAbstraction, GLVisualize, Reactive, GLWindow
using GeometryTypes, ColorTypes, Colors
using FactCheck

has_opengl = false
window = 0
windows = 0
number_of_windows = 6

# Allow window creation to fail, since there is enough to test even without
# OpenGL being present. This is important for travis, since we don't have OpenGL
# there
window = glscreen()
has_opengl = true

function view_boundingboxes(w, camera)
    bbs = []
    for renderlist in w.renderlist
        for robj in renderlist
            bb = boundingbox(robj)
            push!(bbs, visualize(value(bb), :lines, model=robj[:model]))
        end
    end
    for elem in bbs
        _view(elem, w, camera=camera)
    end
end

windows = ntuple(number_of_windows) do i
    a = map(window.area) do wa
        h = wa.h÷number_of_windows
        SimpleRectangle(wa.x, (i-1)h, wa.w, h)
    end
    Screen(window, area=a)
end

function scale_gen(v0, nv)
	l = length(v0)
	@inbounds for i=1:l
		v0[i] = Vec3f0(1,1,sin((nv*l)/i))/3f0
	end
	v0
end
function color_gen(v0, nv)
    l = length(v0)
    @inbounds for x=1:l
        v0[x] = RGBA{U8}(x/l, (sin(nv)+1)/2, (sin(x/l/3)+1)/2.,1.)
    end
    v0
end
prima = centered(HyperRectangle)
primb = GLNormalMesh(centered(Sphere), 8)
cat   = GLNormalMesh(loadasset("cat.obj"))
a = rand(Point2f0, 20)
b = rand(Point3f0, 20)
c = collect(linspace(0.1f0,1.0f0,10f0))
d = rand(Float32, 10,10)
e = rand(Vec3f0, 5,5,5)

lastpos = Vec3f0(0)
particles = [
    visualize(elem, scale=Vec3f0(0.03))
    for elem in (b, (prima, a), (primb, b), (primb, c), d)
]

ps 			 = primb.vertices
time         = bounce(Float32(pi):0.01f0:(pi*2.0f0))
scale_start  = Vec3f0[Vec3f0(1,1,rand()) for i=1:length(ps)]
scale_signal = foldp(scale_gen, scale_start, time)
scale 		 = scale_signal
color_signal = foldp(color_gen, zeros(RGBA{U8}, length(ps)), time)
color 		 = color_signal
rotation     = -primb.normals

push!(particles, visualize((cat, ps), scale=scale, color=color, rotation=rotation))
push!(particles, visualize(e, scale=Vec3f0(0.3)))

if has_opengl
    _view(visualize(particles), windows[1])
    view_boundingboxes(windows[1], :perspective)
end

typealias NColor{N, T} Colorant{T, N}
fillcolor{T <: NColor{4}}(::Type{T}) = T(0,1,0,1)
fillcolor{T <: NColor{3}}(::Type{T}) = T(0,1,0)
Base.rand(m::MersenneTwister, ::Type{U8}) = U8(rand(m, UInt8))
Base.rand{T <: Colorant}(m::MersenneTwister, ::Type{T}) = T(ntuple(x->rand(m, eltype(T)), Val{length(T)})...)
xy_data(x,y,i) = Float32(sin(x/i)*sin(y/i))
generate_distfield(i) = Float32[xy_data(x,y,i)+0.5f0 for x=1:64, y=1:64]
const dfdata = const_lift(generate_distfield, bounce(1f0:1f0:10f0))
facts("Image Like") do
    arrays = map(C-> C[fillcolor(C) for x=1:42,y=1:27] ,(RGBA{U8}, RGBA{Float32}, RGB{U8}, BGRA{U8}, BGR{Float32}))
    loaded_imgs = map(x->loadasset("test_images", x), readdir(assetpath("test_images")))
    intensities = GLIntensity[(sin(x/7)*cos(y/20))/sqrt(x) for x=1:50,y=1:50]
    intensities_s = const_lift(i->GLIntensity[(sin(x/i)*cos(y/(i/2f0)))/sqrt(x) for x=1:50,y=1:50], bounce(10f0:0.1f0:30f0))
    parametric_func = frag"""
       float function(float x) {
       	 return 1.0*sin(1/tan(x));
       }
    """

    context("viewable creation") do
        x = Any[arrays..., loaded_imgs..., intensities, intensities_s, loadasset("kittens-look.gif"), parametric_func]
        images = convert(Vector{Context}, map(visualize, x))
        push!(images, visualize(dfdata, :distancefield))
        if has_opengl
            images = visualize(images, direction=1, gap=Vec3f0(5))
            context("viewing") do
                gl_obj = _view(images, windows[2], camera = :orthographic_pixel)
                view_boundingboxes(windows[2], :orthographic_pixel)

            end
        end
    end
end

function interpolate(a,b,t)
    [ae+((be-ae)*t) for (ae, be) in zip(a,b)]
end

function bounce_particles(pos_velo, _)
    positions, velocity = pos_velo
    dt = 0.1f0
    @inbounds for i=1:length(positions)
        pos,velo = positions[i], velocity[i]
        positions[i] = Point2f0(pos[1], pos[2] + velo*dt)
        if pos[2] <= 0f0
            velocity[i] = abs(velo)
        else
            velocity[i] = velo - 9.8*dt
        end
    end
    positions, velocity
end
facts("sprite particles") do

    context("on a 2D plane") do
        prima = SimpleRectangle(0f0,-0.5f0,1f0,1f0)
        primb = HyperSphere(Point2f0(0), 30f0)
        primc = HyperSphere(Point2f0(0), 40f0)

        a = rand(Point2f0, 10).*200f0
        b = rand(10f0:0.01f0:200f0, 10)
        interpolated = foldp((b,b,b), bounce(1f0:0.01f0:10f0)) do v0_v1_ip, td
            v0,v1,ip = v0_v1_ip
            pol = td%1
            if isapprox(pol,0.0)
                v0 = v1
                v1 = map(x-> rand(linspace(-x, 200f0-x, 100)), v0)
            end
            v0,v1,interpolate(v0,v1,pol)
        end
        b_sig = map(last, interpolated)
        c     = rand(Vec2f0, 5,5)
        c_sig = map(i->Vec2f0[(sin(x/i), cos(y/(i/2f0))) for x=1:5, y=1:5], bounce(1f0:0.05f0:5f0))
        a_vis = visualize(a, scale=Vec2f0(30))
        gpu_pos = a_vis.children[][:position]

        position_velocity = foldp(bounce_particles,
            (a, zeros(Float32, 10)),
            bounce(1:10)
        )

        circle_pos = Point2f0[(Point2f0(sin(i), cos(i))*50f0)+25f0 for i=linspace(0, 2pi, 20)]
        rotation   = Vec2f0[normalize(Vec2f0(25)-Vec2f0(p)) for p in circle_pos]
        scales     = map(bounce(0f0:0.1f0:1000f0)) do t
            Vec2f0[Vec2f0(10, ((sin(i+t)+1)/2)*40) for i=linspace(0, 2pi, 20)]
        end
        context("viewable creation") do
            particles = Context[
                a_vis,
                visualize((primb, gpu_pos), stroke_width=4f0, stroke_color=rand(RGBA{Float32}, 10), color=rand(RGBA{Float32}, 10)),
                visualize((DISTANCEFIELD, gpu_pos), stroke_width=4f0, stroke_color=rand(RGBA{Float32}, 10), color=rand(RGBA{Float32}, 10), distancefield=dfdata),
                visualize((primc, map(first, position_velocity)), image=loadasset("doge.png"), stroke_width=3f0, stroke_color=RGBA{Float32}(0.91,0.91,0.91,1), boundingbox=AABB(Vec3f0(0), Vec3f0(300,300,0))),
                visualize(('↺', c), ranges=((0,200),(0,200))),
                visualize(c_sig, ranges=((0,200),(0,200))),
                visualize((prima,b_sig), ranges=((0,200),),intensity=b_sig, color_norm=Vec2f0(10,200), color_map=GLVisualize.default(Vector{RGBA})),
                visualize((CIRCLE, circle_pos), rotation=rotation, scale=scales)
            ]
            if has_opengl
                context("viewing") do
                    gl_obj = _view(visualize(particles, direction=1), windows[3], camera=:orthographic_pixel)
                    view_boundingboxes(windows[3], :orthographic_pixel)
                end
            end
        end
    end
    context("in 3D space") do
        prima = HyperRectangle{2, Float32}(Vec2f0(-0.1),Vec2f0(0.1))
        primb = Circle(Point2f0(0), 0.1f0)
        a = rand(Point3f0, 20)
        b = rand(Float32, 50,50)
        c = rand(Vec3f0, 5,5)
        d = rand(Vec3f0, 5,5,5)
        context("viewable creation") do
            particles = [
                visualize((prima,a)),
                visualize(('❄', a), scale=Vec2f0(0.1), billboard=true),
                visualize(c, scale=Vec3f0(0.1)),
                visualize(('➤', d), scale=Vec2f0(0.1))
            ]

            if has_opengl
                context("viewing") do
                    gl_obj = _view(visualize(particles), windows[4], camera=:perspective)
                    view_boundingboxes(windows[4], :perspective)
                end
            end
        end
    end
end
function mgrid(dim1, dim2)
    X = [i for i in dim1, j in dim2]
    Y = [j for i in dim1, j in dim2]
    return X,Y
end
function mesh_surface(N)
    dphi, dtheta = pi/Float32(N), pi/Float32(N)
    phi,theta = mgrid(0f0:dphi:(pi+dphi*1.5f0), 0f0:dtheta:(2f0*pi+dtheta*1.5f0));
    m0 = 4f0; m1 = 3f0; m2 = 2f0; m3 = 3f0; m4 = 6f0; m5 = 2f0; m6 = 6f0; m7 = 4f0;
    a = sin(m0*phi).^m1;
    b = cos(m2*phi).^m3;
    c = sin(m4*theta).^m5;
    d = cos(m6*theta).^m7;
    r = a + b + c + d;
    x = r.*sin(phi).*cos(theta);
    y = r.*cos(phi);
    z = r.*sin(phi).*sin(theta);
    x,y,z
end
function xy_data(x,y,i, N)
	x = ((x/N)-0.5f0)*i
	y = ((y/N)-0.5f0)*i
	r = sqrt(x*x + y*y)
	Float32(sin(r)/r)
end
generate_surf_data(i, N) = Float32[xy_data(Float32(x),Float32(y),Float32(i), N) for x=1:N, y=1:N]
facts("Surfaces") do
    context("viewable creation") do
        x = Any[mesh_surface(50), generate_surf_data(20f0, 128)]
        surfs = Context[visualize(elem, :surface) for elem in x]
        if has_opengl
            suf_vizz = visualize(surfs, direction=1)
            context("viewing") do
                gl_obj = _view(suf_vizz, windows[5])
                view_boundingboxes(windows[5], :perspective)
            end
        end
    end
end
function lines3Ddata(N, nloops)
    # The scalar parameter for each line
    TL = linspace(-2f0 * pi, 2f0 * pi, N)
    # We create a list of positions and connections, each describing a line.
    # We will collapse them in one array before plotting.
    xyz    = Point3f0[]
    colors = RGBA{Float32}[]
    # The index of the current point in the total amount of points
    base_colors1 = distinguishable_colors(nloops, RGB{Float32}(1,0,0))
    base_colors2 = distinguishable_colors(nloops, RGB{Float32}(1,1,0))
    # Create each line one after the other in a loop
    for i=1:nloops
        append!(xyz, [Point3f0(sin(t), cos((2 + .02 * i) * t), cos((3 + .02 * i) * t)) for t in TL])
        unique_colors = base_colors1[i]
        hsv = HSV(unique_colors)
        color_palette = map(x->RGBA{Float32}(x, 1.0), sequential_palette(hsv.h, N, s=hsv.s))
        append!(colors, color_palette)
    end
    xyz, colors
end

facts("Lines") do
    context("viewable creation") do
        lines, colors = lines3Ddata(200, 10)
        line_vizz = visualize(lines, :lines, color=colors)
        if has_opengl
            #suf_vizz = visualize(line_vizz, direction=1)
            context("viewing") do
                gl_obj = _view(line_vizz, windows[6], camera=:perspective)
                view_boundingboxes(windows[6], :perspective)
            end
        end
    end
end

if has_opengl
    renderloop(window)
end


text:
import Base.Libdl: dlsym
import Base: unsafe_convert

export Stinger,
remove_edge!,
insert_edge!,
remove_edges!,
insert_edges!,
consistency_check,
outdegree,
indegree,
getsuccessors,
edgeweight

"""
The `Stinger` type is the Julia type representing a STINGER data structure
created in C. It stores the handle to the C data structure. The C data structure
is automatically freed when the finalizer runs.
"""
type Stinger
    handle::Ptr{Void}

    #Default constructor to create a Stinger data structure
    function Stinger()
        s = new(ccall(dlsym(stinger_core_lib, "stinger_new"), Ptr{Void}, ()))
        finalizer(s, stinger_free)
        s
    end

    function Stinger(config::StingerConfig)
        s = new(ccall(dlsym(stinger_core_lib, "stinger_new_full"), Ptr{Void}, (Ptr{StingerConfig},), pointer_from_objref(config)))
        finalizer(s, stinger_free)
        s
    end
end

unsafe_convert{T}(::Type{Ptr{T}}, s::Stinger) = s.handle

"""
    loadstingergraph(s::Stinger)

Use this to get a `StingerGraph` representation of your `Stinger` graph. This
representation will not be kept in sync with the graph. If you make changes,
you will need to call this again to load the graph with the new attributes.
"""
loadstingergraph(s::Stinger) = unsafe_load(convert(Ptr{StingerGraph}, s.handle))

function stinger_free(x::Stinger)
    # To prevent segfaults
    if x.handle != C_NULL
        x.handle = ccall(dlsym(stinger_core_lib, "stinger_free"), Ptr{Void}, (Ptr{Void},), x)
    end
end

#Equivalent of stinger_set_initial_edges
function Stinger(
    nv::UInt,
    etype::Int64,
    offsets::Vector{Int64},
    adj::Vector{Int64},
    weights::Vector{Int64},
    timestamps::Vector{Int64},
    firsttimestamps::Vector{Int64},
    singletimestamp::Int64
    )
    s = Stinger()
    if isempty(timestamps)
        timestamps = C_NULL
    end
    if isempty(firsttimestamps)
        firsttimestamps = C_NULL
    end
    ccall(
        dlsym(stinger_core_lib, "stinger_set_initial_edges"),
        Void,
        (Ptr{Void}, UInt, Int64, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Ptr{Int64}, Int64),
        s, nv, etype, offsets, adj, weights, timestamps, firsttimestamps, singletimestamp
    )
    s
end

#Convenience function to not have to specify UInt for nv
function Stinger(
    nv::Int64,
    etype::Int64,
    offsets::Vector{Int64},
    adj::Vector{Int64},
    weights::Vector{Int64},
    timestamps::Vector{Int64},
    firsttimestamps::Vector{Int64},
    singletimestamp::Int64
    )
    if nv<=0
        error("No of vertices must be a positive integer")
    end
    Stinger(UInt(nv), etype, offsets, adj, weights, timestamps, firsttimestamps, singletimestamp)
end

"""
    remove_edge!(s::Stinger, etype::Int64, from::Int64, to::Int64)

Removes the edge of type `etype` from `from` to `to` from the STINGER graph `s`.
Raises an error in the edge was not found or if there was an error while
removing the edge.
"""
function remove_edge!(s::Stinger, etype::Int64, from::Int64, to::Int64)
    status = ccall(
        dlsym(stinger_core_lib, "stinger_remove_edge"),
        Int32,
        (Ptr{Void}, Int64, Int64, Int64),
        s, etype, from, to
    )
    if status == 0
        error("Edge not found")
    end
    if status == -1
        error("Error while removing the edge")
    end
    status
end

"""
    insert_edge!(
        s::Stinger, etype::Int64, from::Int64, to::Int64, weight::Int64,
        timestamp::Int64
    )

Inserts an edge of type `etype` from `from` to `to` into the STINGER graph `s`
with the specified `weight` and `timestamp`.
Raises an error if the operation was not successful.
"""
function insert_edge!(
    s::Stinger, etype::Int64, from::Int64, to::Int64, weight::Int64, timestamp::Int64
    )
    status = ccall(
        dlsym(stinger_core_lib, "stinger_insert_edge"),
        Int32,
        (Ptr{Void}, Int64, Int64, Int64, Int64, Int64),
        s, etype, from, to, weight, timestamp
    )
    if status == -1
        error("Error while adding edge")
    end
    status
end

"""
    insert_edges!(s::Stinger, edges::AbstractArray, numedges::Integer)

Inserts `numedges` edges into the STINGER graph `s`.
Input format is 5×numedges (etype, src, dst, weight, times).
"""
function insert_edges!(s::Stinger, edges::AbstractArray, numedges::Integer)
    m = size(edges,2);
    numedges <= m || throw(DimensionMismatch("requested to insert too many edges $m < $numedges"))
    size(edges, 1) == 5 || throw(DimensionMismatch("Wrong input format should be 5×numedges"))
    for i in 1:numedges
        insert_edge!(s, edges[1,i], edges[2,i], edges[3,i], edges[4,i], edges[5,i])
    end
end

"""
    remove_edges!(s::Stinger, edges::AbstractArray, numedges::Integer)

Removes `numedges` from the STINGER graph `s`.
Input format is 5×numedges (etype, src, dst, weight, times) to make consistent
with `insert_edges!`.
Only the `src`, `dst` and `etype` fields matter.
"""
function remove_edges!(s::Stinger, edges::AbstractArray, numedges::Integer)
    size(edges, 1) == 5 || throw(DimensionMismatch("Input format is 5×numedges (etype, src, dst, weight, times)"))
    for i in 1:numedges
        remove_edge!(s, edges[0,i], edges[2,i], edges[3,i])
    end
end

"""
    consistency_check(s::Stinger, nv::Int64)

Runs a consistency check on the STINGER data structure.
Returns `true` if the check passed and `false` if it fails.
"""
function consistency_check(s::Stinger, nv::Int64)
    status = ccall(
        dlsym(stinger_core_lib, "stinger_consistency_check"),
        Int32,
        (Ptr{Void}, Int64),
        s, nv
    )
    status == 0 #true if 0, else false
end

"""
    outdegree(s::Stinger, src::Int64)

Returns the outdegree of vertex index.
"""
function outdegree(s::Stinger, src::Int64)
    #TODO: Add check if vertex exists in the graph
    ccall(
        dlsym(stinger_core_lib, "stinger_outdegree_get"),
        Int64,
        (Ptr{Void}, Int64),
        s, src
    )
end

"""
    indegree(s::Stinger, src::Int64)

Returns the outdegree of vertex index.
"""
function indegree(s::Stinger, src::Int64)
    #TODO: Add check if vertex exists in the graph
    ccall(
        dlsym(stinger_core_lib, "stinger_indegree_get"),
        Int64,
        (Ptr{Void}, Int64),
        s, src
    )
end

"""
    getsuccessors(s::Stinger, src::Int64)

Returns a `Vector` of indices representing the successors of `src`.
"""
function getsuccessors(s::Stinger, src::Int64)
    #Ideally, allocating a buffer would be preffered.
    #This makes 2 calls to outdegree - one from here and one from inside C
    outdeg = outdegree(s, src)
    vertexneighbors = zeros(Int64, outdeg)
    if outdeg==0
        return vertexneighbors
    end
    ccall(
        dlsym(stinger_core_lib, "stinger_gather_successors"),
        Void,
        (
            Ptr{Void}, #Stinger instance
            Int64, #Source vertex
            Ptr{Int64}, #Outdegree variable
            Ptr{Int64}, #Output buffer
            Ptr{Int64}, #weight
            Ptr{Int64}, #timefirst
            Ptr{Int64}, #timerecent
            Ptr{Int64}, #type
            Int64 #Max Length
        ),
        s,
        src,
        pointer_from_objref(outdeg),
        vertexneighbors,
        C_NULL,
        C_NULL,
        C_NULL,
        C_NULL,
        typemax(Int64)
    )
    vertexneighbors
end

"""
    edgeweight(s::Stinger, src::Int64, dst::Int64, etype::Int64)

Return the weight of the edge between `src` and `dst` of type `etype`.
If it doesn't exist return 0.
"""
function edgeweight(s::Stinger, src::Int64, dst::Int64, etype::Int64)
    ccall(
        dlsym(stinger_core_lib, "stinger_edgeweight"),
        Int64,
        (Ptr{Void}, Int64, Int64, Int64),
        s, src, dst, etype
    )
end


text:
"""Given the name of a file that is assumed to be a single-channel audio file
containing a birdsong, compute the sonogram of the song in the file.

The defaults of this  function have been written to work well on songs of the house wren.
They may or may not do well for other species. See stft for docs on the parameters"""
function sonogram{T}(fileName::AbstractString; window::AbstractArray{T, 1}=STFT.gaussian(windowlength), windowStep::Integer = windowstep, lowHarmonic::Integer = lowharmonic, highHarmonic::Integer = highharmonic, transformation::Function=STFT.powSpec)
	songData::Array{Float64, 1} = collect(wavread(fileName)[1])::Array{T, 1}
	return sonogram(songData, window, windowStep, lowHarmonic, highHarmonic, transformation)
end

"""Given an array containing a birdsong read from an audio file, compute the sonogram of the song in the file.

The defaults of this  function have been written to work well on songs of the house wren.
They may or may not do well for other species. See stft for docs on the parameters"""
function sonogram{T}(songData::AbstractArray{T, 1}; window::AbstractArray{T, 1}=STFT.gaussian(windowlength), windowStep::Integer = windowstep, lowHarmonic::Integer = lowharmonic, highHarmonic::Integer = highharmonic, transformation::Function=STFT.powSpec)
	sono = log10.(stft(songData, window, windowStep, lowHarmonic, highHarmonic, transformation))
	sonoMin = maximum(sono) - lowCutOff

	for (i, x) in enumerate(sono)
	    if x < sonoMin
		sono[i] = sonoMin
	    end
	end

	sono .-= sonoMin
	return sono
end

export sonogram


text:
using Redpitaya

export showMPSData
function showMPSData(u, freq)
  figure(1)
  clf()
  subplot(2,1,1)
  plot(u)
  subplot(2,1,2)
  semilogy(freq, abs(rfft(u)),"o-b",lw=2)
  sleep(0.1)
end

rp = RedPitaya("10.167.6.87")

amplitude = 0.39
  dec = 8
  txFreqDivider = 4836
  freq = div(125e6,txFreqDivider)
  numPeriods = 25
  freqR = roundFreq(rp,dec,freq)
  numSampPerPeriod = numSamplesPerPeriod(rp,dec,freqR)
  numSamp = numSampPerPeriod*numPeriods
  println("Frequency = $freqR Hz")
  println("Number Sampling Points per Period: $numSampPerPeriod")
  # start sending
  send(rp,"GEN:RST")
  sendAnalogSignal(rp,1,"SINE",freqR,amplitude)
  sleep(0.4)
    trigger = "NOW" #"AWG_NE" # or NOW
    uMeas, uRef = receiveAnalogSignalWithTrigger(rp, 0, 0, numSamp, dec=dec, delay=0.01,
                typ="OLD", trigger=trigger, triggerLevel=-0.0,
                binary=true, triggerDelay=numSampPerPeriod)
    uMeas[:] = circshift(uMeas,-phaseShift(uRef, numPeriods))

  disableAnalogOutput(rp,1)

lenFFT = length(rfft(uMeas))
fr = linspace(0,125e6/2/dec,lenFFT)
println(length(fr))

showMPSData(vec(uMeas),fr)

writecsv("MPS.csv",hcat(uMeas,uRef))


text:
using Dates

stime=DateTime(0,7,1)

# time
ΔT=30; #seconds
ndays=100; # duration of simulation in days

n=Int(round(ndays*24*60*60/ΔT)); # number of time steps


text:
module SensorModels

export SensorData, SensorParams, SensorModel, BeamPDF

abstract type AbstractSensorData end
abstract type AbstractSensorParams end
abstract type AbstractSensorModel <: Function end
abstract type AbstractBeamPDF <: Function end

include("beammodel.jl")
include("laserscanmodel.jl")

end


text:
# src/impl.jl
# Implementation of a Bounded Rational type

export BoundedRational

"""```
struct BoundedRational{T,B}
    <: AbstractBoundedRational{T,B}
```
"""
struct BoundedRational{T,B} <: AbstractBoundedRational{T,B}
    num::T
    den::T
    bound::B
end

"""```
build_ratio(::Type{BoundedRational{T,B}}, num, den, bound::B = nothing)
```
"""
function build_ratio(::Type{BoundedRational{T,B}}, num, den, bound::B = nothing) where {T,B}
    return BoundedRational(num, den, bound)
end

"""```
numerator(x::BoundedRational)
    === x.num
```
"""
numerator(x::BoundedRational) = x.num

"""```
denominator(x::BoundedRational)
    === x.den
```
"""
denominator(x::BoundedRational) = x.den

"""```
bound(x::BoundedRational)
    === x.bound
```
"""
bound(x::BoundedRational) = x.bound


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

name = "Clingo"
version = v"5.5.0"

# Collection of sources required to complete build
sources = [
    GitSource("https://github.com/potassco/clingo.git", "e1c20131b708439c7e1c317bb96b58e5a527b1a2")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/clingo
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=$prefix \
    -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
    -DCMAKE_BUILD_TYPE=Release \
    ..
make -j${nproc}
make install
"""

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

# The products that we will ensure are always built
products = [
    ExecutableProduct("lpconvert", :lpconvert),
    ExecutableProduct("clingo", :clingo),
    ExecutableProduct("gringo", :gringo),
    ExecutableProduct("reify", :reify),
    ExecutableProduct("clasp", :clasp),
    LibraryProduct("libclingo",:libclingo)
]

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

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

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
type MArray{Size, T, N, L} <: StaticArray{T, N}
    data::NTuple{L,T}

    function MArray(x::NTuple{L,T})
        check_marray_parameters(Val{Size}, T, Val{N}, Val{L})
        new(x)
    end

    function MArray(x::NTuple{L})
        check_marray_parameters(Val{Size}, T, Val{N}, Val{L})
        new(convert_ntuple(T, x))
    end

    function MArray()
        check_marray_parameters(Val{Size}, T, Val{N}, Val{L})
        new()
    end
end

@generated function check_marray_parameters{Size,T,N,L}(::Type{Val{Size}}, ::Type{T}, ::Type{Val{N}}, ::Type{Val{L}})
    if !(isa(Size, Tuple{Vararg{Int}}))
        error("MArray parameter Size must be a tuple of Ints (e.g. `MArray{(3,3)}`)")
    end

    if L != prod(Size) || L < 0 || minimum(Size) < 0 || length(Size) != N
        error("Size mismatch in MArray parameters. Got size $Size, dimension $N and length $L.")
    end

    return nothing
end

@generated function (::Type{MArray{Size,T,N}}){Size,T,N}(x)
    return quote
        $(Expr(:meta, :inline))
        MArray{Size,T,N,$(prod(Size))}(x)
    end
end

@generated function (::Type{MArray{Size,T}}){Size,T}(x)
    return quote
        $(Expr(:meta, :inline))
        MArray{Size,T,$(length(Size)),$(prod(Size))}(x)
    end
end

@generated function (::Type{MArray{Size}}){Size}(x)
    return quote
        $(Expr(:meta, :inline))
        MArray{Size,$(promote_tuple_eltype(x)),$(length(Size)),$(prod(Size))}(x)
    end
end

@generated function (::Type{MArray{Size,T,N}}){Size,T,N}()
    return quote
        $(Expr(:meta, :inline))
        MArray{Size, T, N, $(prod(Size))}()
    end
end

@generated function (::Type{MArray{Size,T}}){Size,T}()
    return quote
        $(Expr(:meta, :inline))
        MArray{Size, T, $(length(Size)), $(prod(Size))}()
    end
end

@inline MArray(a::StaticArray) = MArray{size(typeof(a))}(Tuple(a))

# Some more advanced constructor-like functions
@inline eye{Size}(::Type{MArray{Size}}) = eye(MArray{Size,Float64})
@inline zeros{Size}(::Type{MArray{Size}}) = zeros(MArray{Size,Float64})
@inline ones{Size}(::Type{MArray{Size}}) = ones(MArray{Size,Float64})

####################
## MArray methods ##
####################

@pure size{Size}(::Union{MArray{Size},Type{MArray{Size}}}) = Size
@pure size{Size,T}(::Type{MArray{Size,T}}) = Size
@pure size{Size,T,N}(::Type{MArray{Size,T,N}}) = Size
@pure size{Size,T,N,L}(::Type{MArray{Size,T,N,L}}) = Size

function getindex(v::MArray, i::Integer)
    Base.@_inline_meta
    v.data[i]
end

@propagate_inbounds setindex!{S,T}(v::MArray{S,T}, val, i::Integer) = setindex!(v, convert(T, val), i)
@inline function setindex!{S,T}(v::MArray{S,T}, val::T, i::Integer)
    @boundscheck if i < 1 || i > length(v)
        throw(BoundsError())
    end

    if isbits(T)
        unsafe_store!(Base.unsafe_convert(Ptr{T}, Base.data_pointer_from_objref(v)), val, i)
    else
        # This one is thought to be unsafe (#27)
        # unsafe_store!(Base.unsafe_convert(Ptr{Ptr{Void}}, Base.data_pointer_from_objref(v.data)), Base.data_pointer_from_objref(val), i)
        error("setindex!() with non-isbits eltype is not supported by StaticArrays")
    end

    return val
end

@inline Tuple(v::MArray) = v.data

@inline function Base.unsafe_convert{Size,T}(::Type{Ptr{T}}, a::MArray{Size,T})
    Base.unsafe_convert(Ptr{T}, Base.data_pointer_from_objref(a))
end

macro MArray(ex)
    if !isa(ex, Expr)
        error("Bad input for @MArray")
    end

    if ex.head == :vect  # vector
        return esc(Expr(:call, MArray{(length(ex.args),)}, Expr(:tuple, ex.args...)))
    elseif ex.head == :ref # typed, vector
        return esc(Expr(:call, Expr(:curly, :MArray, ((length(ex.args)-1),), ex.args[1]), Expr(:tuple, ex.args[2:end]...)))
    elseif ex.head == :hcat # 1 x n
        s1 = 1
        s2 = length(ex.args)
        return esc(Expr(:call, MArray{(s1, s2)}, Expr(:tuple, ex.args...)))
    elseif ex.head == :typed_hcat # typed, 1 x n
        s1 = 1
        s2 = length(ex.args) - 1
        return esc(Expr(:call, Expr(:curly, :MArray, (s1, s2), ex.args[1]), Expr(:tuple, ex.args[2:end]...)))
    elseif ex.head == :vcat
        if isa(ex.args[1], Expr) && ex.args[1].head == :row # n x m
            # Validate
            s1 = length(ex.args)
            s2s = map(i -> ((isa(ex.args[i], Expr) && ex.args[i].head == :row) ? length(ex.args[i].args) : 1), 1:s1)
            s2 = minimum(s2s)
            if maximum(s2s) != s2
                error("Rows must be of matching lengths")
            end

            exprs = [ex.args[i].args[j] for i = 1:s1, j = 1:s2]
            return esc(Expr(:call, MArray{(s1, s2)}, Expr(:tuple, exprs...)))
        else # n x 1
            return esc(Expr(:call, MArray{(length(ex.args), 1)}, Expr(:tuple, ex.args...)))
        end
    elseif ex.head == :typed_vcat
        if isa(ex.args[2], Expr) && ex.args[2].head == :row # typed, n x m
            # Validate
            s1 = length(ex.args) - 1
            s2s = map(i -> ((isa(ex.args[i+1], Expr) && ex.args[i+1].head == :row) ? length(ex.args[i+1].args) : 1), 1:s1)
            s2 = minimum(s2s)
            if maximum(s2s) != s2
                error("Rows must be of matching lengths")
            end

            exprs = [ex.args[i+1].args[j] for i = 1:s1, j = 1:s2]
            return esc(Expr(:call, Expr(:curly, :MArray, (s1, s2), ex.args[1]), Expr(:tuple, exprs...)))
        else # typed, n x 1
            return esc(Expr(:call, Expr(:curly, :MArray, (length(ex.args)-1, 1), ex.args[1]), Expr(:tuple, ex.args[2:end]...)))
        end
    elseif isa(ex, Expr) && ex.head == :comprehension
        if length(ex.args) != 1 || !isa(ex.args[1], Expr) || ex.args[1].head != :generator
            error("Expected generator in comprehension, e.g. [f(i,j) for i = 1:3, j = 1:3]")
        end
        ex = ex.args[1]
        n_rng = length(ex.args) - 1
        rng_args = [ex.args[i+1].args[1] for i = 1:n_rng]
        rngs = [eval(current_module(), ex.args[i+1].args[2]) for i = 1:n_rng]
        rng_lengths = map(length, rngs)

        f = gensym()
        f_expr = :($f = ($(Expr(:tuple, rng_args...)) -> $(ex.args[1])))

        # TODO figure out a generic way of doing this...
        if n_rng == 1
            exprs = [:($f($j1)) for j1 in rngs[1]]
        elseif n_rng == 2
            exprs = [:($f($j1, $j2)) for j1 in rngs[1], j2 in rngs[2]]
        elseif n_rng == 3
            exprs = [:($f($j1, $j2, $j3)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3]]
        elseif n_rng == 4
            exprs = [:($f($j1, $j2, $j3, $j4)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4]]
        elseif n_rng == 5
            exprs = [:($f($j1, $j2, $j3, $j4, $j5)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4], j5 in rngs[5]]
        elseif n_rng == 6
            exprs = [:($f($j1, $j2, $j3, $j4, $j5, $j6)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4], j5 in rngs[5], j6 in rngs[6]]
        elseif n_rng == 7
            exprs = [:($f($j1, $j2, $j3, $j4, $j5, $j6, $j7)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4], j5 in rngs[5], j6 in rngs[6], j7 in rngs[7]]
        elseif n_rng == 8
            exprs = [:($f($j1, $j2, $j3, $j4, $j5, $j6, $j7, $j8)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4], j5 in rngs[5], j6 in rngs[6], j7 in rngs[7], j8 in rngs[8]]
        else
            error("@MArray only supports up to 8-dimensional comprehensions")
        end

        return quote
            $(Expr(:meta, :inline))
            $(esc(f_expr))
            $(esc(Expr(:call, Expr(:curly, :MArray, (rng_lengths...)), Expr(:tuple, exprs...))))
        end
    elseif isa(ex, Expr) && ex.head == :typed_comprehension
        if length(ex.args) != 2 || !isa(ex.args[2], Expr) || ex.args[2].head != :generator
            error("Expected generator in typed comprehension, e.g. Float64[f(i,j) for i = 1:3, j = 1:3]")
        end
        T = ex.args[1]
        ex = ex.args[2]
        n_rng = length(ex.args) - 1
        rng_args = [ex.args[i+1].args[1] for i = 1:n_rng]
        rngs = [eval(current_module(), ex.args[i+1].args[2]) for i = 1:n_rng]
        rng_lengths = map(length, rngs)

        f = gensym()
        f_expr = :($f = ($(Expr(:tuple, rng_args...)) -> $(ex.args[1])))

        # TODO figure out a generic way of doing this...
        if n_rng == 1
            exprs = [:($f($j1)) for j1 in rngs[1]]
        elseif n_rng == 2
            exprs = [:($f($j1, $j2)) for j1 in rngs[1], j2 in rngs[2]]
        elseif n_rng == 3
            exprs = [:($f($j1, $j2, $j3)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3]]
        elseif n_rng == 4
            exprs = [:($f($j1, $j2, $j3, $j4)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4]]
        elseif n_rng == 5
            exprs = [:($f($j1, $j2, $j3, $j4, $j5)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4], j5 in rngs[5]]
        elseif n_rng == 6
            exprs = [:($f($j1, $j2, $j3, $j4, $j5, $j6)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4], j5 in rngs[5], j6 in rngs[6]]
        elseif n_rng == 7
            exprs = [:($f($j1, $j2, $j3, $j4, $j5, $j6, $j7)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4], j5 in rngs[5], j6 in rngs[6], j7 in rngs[7]]
        elseif n_rng == 8
            exprs = [:($f($j1, $j2, $j3, $j4, $j5, $j6, $j7, $j8)) for j1 in rngs[1], j2 in rngs[2], j3 in rngs[3], j4 in rngs[4], j5 in rngs[5], j6 in rngs[6], j7 in rngs[7], j8 in rngs[8]]
        else
            error("@MArray only supports up to 8-dimensional comprehensions")
        end

        return quote
            $(Expr(:meta, :inline))
            $(esc(f_expr))
            $(esc(Expr(:call, Expr(:curly, :MArray, (rng_lengths...), T), Expr(:tuple, exprs...))))
        end
    elseif isa(ex, Expr) && ex.head == :call
        if ex.args[1] == :zeros || ex.args[1] == :ones || ex.args[1] == :rand || ex.args[1] == :randn
            if length(ex.args) == 1
                error("@MArray got bad expression: $(ex.args[1])()")
            else
                return quote
                    $(Expr(:meta, :inline))
                    if isa($(esc(ex.args[2])), DataType)
                        $(ex.args[1])($(esc(Expr(:curly, MArray, Expr(:tuple, ex.args[3:end]...), ex.args[2]))))
                    else
                        $(ex.args[1])($(esc(Expr(:curly, MArray, Expr(:tuple, ex.args[2:end]...)))))
                    end
                end
            end
        elseif ex.args[1] == :fill
            if length(ex.args) == 1
                error("@MArray got bad expression: $(ex.args[1])()")
            elseif length(ex.args) == 2
                error("@MArray got bad expression: $(ex.args[1])($(ex.args[2]))")
            else
                return quote
                    $(Expr(:meta, :inline))
                    $(esc(ex.args[1]))($(esc(ex.args[2])), MArray{$(esc(Expr(:tuple, ex.args[3:end]...)))})
                end
            end
        elseif ex.args[1] == :eye
            if length(ex.args) == 2
                return quote
                    $(Expr(:meta, :inline))
                    eye(MArray{($(esc(ex.args[2])), $(esc(ex.args[2])))})
                end
            elseif length(ex.args) == 3
                # We need a branch, depending if the first argument is a type or a size.
                return quote
                    $(Expr(:meta, :inline))
                    if isa($(esc(ex.args[2])), DataType)
                        eye(MArray{($(esc(ex.args[3])), $(esc(ex.args[3]))), $(esc(ex.args[2]))})
                    else
                        eye(MArray{($(esc(ex.args[2])), $(esc(ex.args[3])))})
                    end
                end
            elseif length(ex.args) == 4
                return quote
                    $(Expr(:meta, :inline))
                    eye(MArray{($(esc(ex.args[3])), $(esc(ex.args[4]))), $(esc(ex.args[2]))})
                end
            else
                error("Bad eye() expression for @MArray")
            end
        else
            error("@MArray only supports the zeros(), ones(), rand(), randn() and eye() functions.")
        end
    else
        error("Bad input for @MArray")
    end

end


text:
#
# This file is a part of MolecularGraph.jl
# Licensed under the MIT License http://opensource.org/licenses/MIT
#

export
    coordgen!

using coordgenlibs_jll

function coordgen!(mol::GraphMol)
    minmol = ccall((:getSketcherMinimizer, libcoordgen), Ptr{Cvoid}, ())
    atoms = Ptr{Cvoid}[]
    bonds = Ptr{Cvoid}[]

    # Atoms
    for nattr in nodeattrs(mol)
        atom = ccall(
            (:setAtom, libcoordgen), Ptr{Cvoid},
            (Ptr{Cvoid}, Int), minmol, atomnumber(nattr)
        )
        push!(atoms, atom)
    end

    # Bonds
    for (i, (u, v)) in enumerate(edgesiter(mol))
        bond = ccall(
            (:setBond, libcoordgen), Ptr{Cvoid},
            (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Int),
            minmol, atoms[u], atoms[v], edgeattr(mol, i).order
        )
        push!(bonds, bond)
    end

    ccall(
        (:assignBondsAndNeighbors, libcoordgen), Cvoid,
        (Ptr{Cvoid},), minmol
    )

    # Stereocenter
    for i in 1:nodecount(mol)
        nattr = nodeattr(mol, i)
        nattr.stereo in (:clockwise, :anticlockwise) || continue
        direction = nattr.stereo === :clockwise
        if degree(mol, i) == 4
            f, s, t, _ = sort(collect(adjacencies(mol, i)))
        elseif degree(mol, i) == 3
            f, s, t = sort(collect(adjacencies(mol, i)))
            if i < f || (i > s && i < t) # implicit H is the 1st or 3rd
                direction = !direction
            end
        else
            continue
        end
        ccall(
            (:setStereoCenter, libcoordgen), Cvoid,
            (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Int),
            atoms[i], atoms[f], atoms[s], atoms[t], direction
        )
    end

    # StereoBond
    for (i, (n1, n2)) in enumerate(edgesiter(mol))
        eattr = edgeattr(mol, i)
        eattr.stereo in (:cis, :trans) || continue
        iscis = eattr.stereo === :cis
        u = sort([adj for adj in adjacencies(mol, n1) if adj != n2])[1]
        v = sort([adj for adj in adjacencies(mol, n2) if adj != n1])[1]
        ccall(
            (:setStereoBond, libcoordgen), Cvoid,
            (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Int),
            bonds[i], atoms[u], atoms[v], iscis
        )
    end

    # Optimize
    ccall(
        (:runGenerateCoordinates, libcoordgen), Cvoid,
        (Ptr{Cvoid},), minmol
    )

    # Output
    coords = zeros(Float64, nodecount(mol), 2)
    for i in 1:nodecount(mol)
        px = ccall(
            (:getAtomX, libcoordgen), Float32, (Ptr{Cvoid},), atoms[i])
        py = ccall(
            (:getAtomY, libcoordgen), Float32, (Ptr{Cvoid},), atoms[i])
        coords[i, :] = [px, py]
    end
    notation = Int[]
    for i in 1:edgecount(mol)
        hasstereo = ccall(
            (:hasStereochemistryDisplay, libcoordgen), Bool,
            (Ptr{Cvoid},), bonds[i])
        if !hasstereo
            push!(notation, 0)
            continue
        end
        iswedge = ccall(
            (:isWedge, libcoordgen), Bool, (Ptr{Cvoid},), bonds[i])
        isrev = ccall(
            (:isReversed, libcoordgen), Bool, (Ptr{Cvoid},), bonds[i])
        push!(notation, iswedge ? 1 : 6)
        u, v = mol.edges[i]
        if isrev
            mol.edges[i] = (v, u)
        end
    end
    mol.cache[:coords2d] = coords
    mol.cache[:coordgenbond] = notation
end


text:
module adapters_sql_structured_test

using Test # @test
using Octo.Adapters.SQL # Schema from SELECT FROM WHERE COUNT SUM AVG BIGINT

struct User
end

u = from(User)
@test_throws Schema.TableNameError to_sql([FROM u])

Schema.model(User, table_name="users")

@test to_sql([FROM u]) == "FROM users"
@test to_sql([SELECT * FROM u]) == "SELECT * FROM users"
@test to_sql([SELECT u.id FROM u]) == "SELECT id FROM users"
@test to_sql([SELECT (u.id, u.name) FROM u]) == "SELECT id, name FROM users"
@test to_sql([WHERE u.id == 2]) == "WHERE id = 2"

u = from(User, :u)
@test to_sql([FROM u]) == "FROM users AS u"
@test to_sql([SELECT (u.id, u.name) FROM u]) == "SELECT u.id, u.name FROM users AS u"
@test to_sql([WHERE u.id == 2]) == "WHERE u.id = 2"
@test to_sql([SELECT (u.id, u.name) FROM u WHERE u.id == 2]) == "SELECT u.id, u.name FROM users AS u WHERE u.id = 2"

@test to_sql([COUNT(*)]) == "COUNT(*)"
@test to_sql([as(COUNT(*), :c)]) == "COUNT(*) AS c"
@test to_sql([SUM(u.age)]) == "SUM(u.age)"
@test to_sql([AVG(u.age)]) == "AVG(u.age)"

Repo.connect(adapter=Octo.Adapters.SQL)
buf = IOBuffer()
show(IOContext(buf, :color=>true), MIME"text/plain"(), [FROM u])
@test String(take!(buf)) == "\e[36mFROM\e[39m \e[0musers \e[36mAS\e[39m \e[0m\e[1mu\e[22m"
show(IOContext(buf, :color=>true), MIME"text/plain"(), [1,2,3])
@test String(take!(buf)) == "[1, 2, 3]"

@test BIGINT isa Octo.SQLKeyword

end # module adapters_sql_structured_test