text:
module TimeWarp

import ProgressMeter
using StatsBase
using Parameters

# reexport to let user specify dtw(⋅,⋅,distance)
using Reexport
@reexport using Distances

export Sequence,
       SequenceArray,
       seq_to_array,
       dtw,
       DTWDistance,
       DTWMethod,
       ClassicDTW,
       FastDTW,
       distpath,
       dba,
       dbaclust,
       dtw_cost_matrix,
       DBAResult,
       fastdtw

include("utils.jl")
include("sequence.jl")

include("distance_interface.jl")

include("dtw.jl")
include("dba.jl")
include("dbaclust.jl")
include("windowed_matrix.jl")
include("fastdtw.jl")
include("datasets/datasets.jl")
include("plots.jl")

end # module


text:
# By default, Julia/LLVM does not use fused multiply-add operations (FMAs).
# Since these FMAs can increase the performance of many numerical algorithms,
# we need to opt-in explicitly.
# See https://ranocha.de/blog/Optimizing_EC_Trixi for further details.
@muladd begin

# This file contains general numerical fluxes that are not specific to certain equations

"""
    flux_central(u_ll, u_rr, orientation_or_normal_direction, equations::AbstractEquations)

The classical central numerical flux `f((u_ll) + f(u_rr)) / 2`. When this flux is
used as volume flux, the discretization is equivalent to the classical weak form
DG method (except floating point errors).
"""
@inline function flux_central(u_ll, u_rr, orientation_or_normal_direction,
                              equations::AbstractEquations)
  # Calculate regular 1D fluxes
  f_ll = flux(u_ll, orientation_or_normal_direction, equations)
  f_rr = flux(u_rr, orientation_or_normal_direction, equations)

  # Average regular fluxes
  return 0.5 * (f_ll + f_rr)
end

"""
    FluxPlusDissipation(numerical_flux, dissipation)

Combine a `numerical_flux` with a `dissipation` operator to create a new numerical flux.
"""
struct FluxPlusDissipation{NumericalFlux, Dissipation}
  numerical_flux::NumericalFlux
  dissipation::Dissipation
end

@inline function (numflux::FluxPlusDissipation)(u_ll, u_rr, orientation_or_normal_direction, equations)
  @unpack numerical_flux, dissipation = numflux

  return ( numerical_flux(u_ll, u_rr, orientation_or_normal_direction, equations)
            + dissipation(u_ll, u_rr, orientation_or_normal_direction, equations) )
end

Base.show(io::IO, f::FluxPlusDissipation) = print(io, "FluxPlusDissipation(",  f.numerical_flux, ", ", f.dissipation, ")")

"""
    FluxRotated(numerical_flux)

Compute a `numerical_flux` flux in direction of a normal vector by rotating the solution,
computing the numerical flux in x-direction, and rotating the calculated flux back.

Requires a rotationally invariant equation with equation-specific functions
[`rotate_to_x`](@ref) and [`rotate_from_x`](@ref).
"""
struct FluxRotated{NumericalFlux}
  numerical_flux::NumericalFlux
end

# Rotated surface flux computation (2D version)
@inline function (flux_rotated::FluxRotated)(u_ll, u_rr, normal_direction::AbstractVector,
                                             equations::AbstractEquations{2})
  @unpack numerical_flux = flux_rotated

  norm_ = norm(normal_direction)
  # Normalize the vector without using `normalize` since we need to multiply by the `norm_` later
  normal_vector = normal_direction / norm_

  u_ll_rotated = rotate_to_x(u_ll, normal_vector, equations)
  u_rr_rotated = rotate_to_x(u_rr, normal_vector, equations)

  f = numerical_flux(u_ll_rotated, u_rr_rotated, 1, equations)

  return rotate_from_x(f, normal_vector, equations) * norm_
end

# Rotated surface flux computation (3D version)
@inline function (flux_rotated::FluxRotated)(u_ll, u_rr, normal_direction::AbstractVector,
                                             equations::AbstractEquations{3})
  @unpack numerical_flux = flux_rotated

  # Storing these vectors could increase the performance by 20 percent
  norm_ = norm(normal_direction)
  # Normalize the vector without using `normalize` since we need to multiply by the `norm_` later
  normal_vector = normal_direction / norm_

  # Some vector that can't be identical to normal_vector (unless normal_vector == 0)
  tangent1 = SVector(normal_direction[2], normal_direction[3], -normal_direction[1])
  # Orthogonal projection
  tangent1 -= dot(normal_vector, tangent1) * normal_vector
  tangent1 = normalize(tangent1)

  # Third orthogonal vector
  tangent2 = normalize(cross(normal_direction, tangent1))

  u_ll_rotated = rotate_to_x(u_ll, normal_vector, tangent1, tangent2, equations)
  u_rr_rotated = rotate_to_x(u_rr, normal_vector, tangent1, tangent2, equations)

  f = numerical_flux(u_ll_rotated, u_rr_rotated, 1, equations)

  return rotate_from_x(f, normal_vector, tangent1, tangent2, equations) * norm_
end

Base.show(io::IO, f::FluxRotated) = print(io, "FluxRotated(",  f.numerical_flux, ")")

"""
    DissipationGlobalLaxFriedrichs(λ)

Create a global Lax-Friedrichs dissipation operator with dissipation coefficient `λ`.
"""
struct DissipationGlobalLaxFriedrichs{RealT}
  λ::RealT
end

@inline function (dissipation::DissipationGlobalLaxFriedrichs)(u_ll, u_rr, orientation::Integer, equations)
  @unpack λ = dissipation
  return -λ/2 * (u_rr - u_ll)
end

@inline function (dissipation::DissipationGlobalLaxFriedrichs)(u_ll, u_rr, normal_direction::AbstractVector, equations)
  @unpack λ = dissipation
  return -λ/2 * norm(normal_direction) * (u_rr - u_ll)
end

Base.show(io::IO, d::DissipationGlobalLaxFriedrichs) = print(io, "DissipationGlobalLaxFriedrichs(", d.λ, ")")

"""
    DissipationLocalLaxFriedrichs(max_abs_speed=max_abs_speed_naive)

Create a local Lax-Friedrichs dissipation operator where the maximum absolute wave speed
is estimated as
`max_abs_speed(u_ll, u_rr, orientation_or_normal_direction, equations)`,
defaulting to [`max_abs_speed_naive`](@ref).
"""
struct DissipationLocalLaxFriedrichs{MaxAbsSpeed}
  max_abs_speed::MaxAbsSpeed
end

DissipationLocalLaxFriedrichs() = DissipationLocalLaxFriedrichs(max_abs_speed_naive)

@inline function (dissipation::DissipationLocalLaxFriedrichs)(u_ll, u_rr, orientation_or_normal_direction, equations)
  λ = dissipation.max_abs_speed(u_ll, u_rr, orientation_or_normal_direction, equations)
  return -0.5 * λ * (u_rr - u_ll)
end

Base.show(io::IO, d::DissipationLocalLaxFriedrichs) = print(io, "DissipationLocalLaxFriedrichs(", d.max_abs_speed, ")")

"""
    max_abs_speed_naive(u_ll, u_rr, orientation::Integer,   equations)
    max_abs_speed_naive(u_ll, u_rr, normal_direction::AbstractVector, equations)

Simple and fast estimate of the maximal wave speed of the Riemann problem with left and right states
`u_ll, u_rr`, based only on the local wave speeds associated to `u_ll` and `u_rr`.
"""
function max_abs_speed_naive end

const FluxLaxFriedrichs{MaxAbsSpeed} = FluxPlusDissipation{typeof(flux_central), DissipationLocalLaxFriedrichs{MaxAbsSpeed}}
"""
    FluxLaxFriedrichs(max_abs_speed=max_abs_speed_naive)

Local Lax-Friedrichs (Rusanov) flux with maximum wave speed estimate provided by
`max_abs_speed`, cf. [`DissipationLocalLaxFriedrichs`](@ref) and
[`max_abs_speed_naive`](@ref).
"""
function FluxLaxFriedrichs(max_abs_speed=max_abs_speed_naive)
  FluxPlusDissipation(flux_central, DissipationLocalLaxFriedrichs(max_abs_speed))
end

Base.show(io::IO, f::FluxLaxFriedrichs) = print(io, "FluxLaxFriedrichs(", f.dissipation.max_abs_speed, ")")

# TODO: Shall we deprecate `flux_lax_friedrichs`?
"""
    flux_lax_friedrichs

See [`FluxLaxFriedrichs`](@ref).
"""
const flux_lax_friedrichs = FluxLaxFriedrichs()

"""
    FluxHLL(min_max_speed=min_max_speed_naive)

Create an HLL (Harten, Lax, van Leer) numerical flux where the minimum and maximum
wave speeds are estimated as
`λ_min, λ_max = min_max_speed(u_ll, u_rr, orientation_or_normal_direction, equations)`,
defaulting to [`min_max_speed_naive`](@ref).
"""
struct FluxHLL{MinMaxSpeed}
  min_max_speed::MinMaxSpeed
end

FluxHLL() = FluxHLL(min_max_speed_naive)

"""
    min_max_speed_naive(u_ll, u_rr, orientation::Integer,   equations)
    min_max_speed_naive(u_ll, u_rr, normal_direction::AbstractVector, equations)

Simple and fast estimate of the minimal and maximal wave speed of the Riemann problem with
left and right states `u_ll, u_rr`, usually based only on the local wave speeds associated to
`u_ll` and `u_rr`.
- Amiram Harten, Peter D. Lax, Bram van Leer (1983)
  On Upstream Differencing and Godunov-Type Schemes for Hyperbolic Conservation Laws
  [DOI: 10.1137/1025002](https://doi.org/10.1137/1025002)
"""
function min_max_speed_naive end

@inline function (numflux::FluxHLL)(u_ll, u_rr, orientation_or_normal_direction, equations)
  λ_min, λ_max = numflux.min_max_speed(u_ll, u_rr, orientation_or_normal_direction, equations)

  if λ_min >= 0 && λ_max >= 0
    return flux(u_ll, orientation_or_normal_direction, equations)
  elseif λ_max <= 0 && λ_min <= 0
    return flux(u_rr, orientation_or_normal_direction, equations)
  else
    f_ll = flux(u_ll, orientation_or_normal_direction, equations)
    f_rr = flux(u_rr, orientation_or_normal_direction, equations)
    inv_λ_max_minus_λ_min = inv(λ_max - λ_min)
    factor_ll = λ_max * inv_λ_max_minus_λ_min
    factor_rr = λ_min * inv_λ_max_minus_λ_min
    factor_diss = λ_min * λ_max * inv_λ_max_minus_λ_min
    return factor_ll * f_ll - factor_rr * f_rr + factor_diss * (u_rr - u_ll)
  end
end

Base.show(io::IO, numflux::FluxHLL) = print(io, "FluxHLL(", numflux.min_max_speed, ")")

# TODO: Shall we deprecate `flux_hll`?
"""
    flux_hll

See [`FluxHLL`](@ref).
"""
const flux_hll = FluxHLL()

end # @muladd

ext: jl


text:
immutable Trainer
    net::Net
    sgdUpdaters::Vector{Vector{SGDUpdater}}

    function Trainer(net::Net, learningRate::Float64)
        buildUpdater(state) = MomentumUpdater(learningRate, 0.0, 0.0, 0.0, zeros(length(state.vol)))
        new(net, map(layer -> [buildUpdater(state) for state in gradientStates(layer)],  net.layers))
    end
end

train(t::Trainer, inputActivation::Vol, class::Int) = train(t.net, inputActivation, class)
predict(t::Trainer, inputActivation::Vol) = predict(t.net, inputActivation)

function updateGradients(t::Trainer, batchSize::Int)
    for (updaters, layer) in zip(t.sgdUpdaters, t.net.layers)
        priorW = copy(gradientStates(layer))
        println("Prior state: ", priorW)
        for (updater, state) in zip(updaters, gradientStates(layer))
            updateGradients(updater, state, batchSize)
        end
        postW = copy(gradientStates(layer))
        println("Post state: ", postW)
        @assert length(priorW) == 0 || priorW != postW
    end
end


text:
function Diffusion!(array,width::Int64,boxwidth,Df,t)

	changelist = fill(0.0,width)

	changelist[1] = - Df*t*( array[1] - array[2] )/boxwidth

	for iterator in 2:width-1
		changelist[iterator] = Df * t * (array[iterator-1] - array[iterator]) / boxwidth - Df * t * (array[iterator] - array[iterator+1]) / boxwidth
	end

	changelist[width] = Df*t* ( array[width-1] - array[width] )/(boxwidth)/boxwidth

	for iterator in 1:width
		array[iterator] = array[iterator] + changelist[iterator]
	end

end

function mixing!(array,pos)
	temp = array[pos]
	array[pos] = array[pos+1]
	array[pos + 1] = temp
end

function diffusionin1d(heatspeed::Float64,cuttemp::Float64,width::Int64,boxwidth::Float64,Df::Float64,t::Float64,iteration::Int64,outputfilename; heatpos = [1], mixpos = 0, mixcountmax = 1, roomtemp::Float64 = 25.0 , tempdetectpos = 3, recordpos = [3])

	open(outputfilename,"w") do f

		write(f,"Initial condition:\n",
				"The speed of heating: $heatspeed \n",
				"Cut of temperature: $cuttemp \n",
				"width of the system: $width \n",
				"width of the box: $boxwidth \n",
				"Diffusion coefficient: $Df \n",
				"Δt: $t \n",
				"total iteration: $iteration \n",
				"mixing position: $mixpos \n",
				"max counter of mixing: $mixcountmax \n",
				"room temperature: $roomtemp \n",
				"The position of detecting temp: $tempdetectpos \n")

		array = fill(roomtemp,width)

		mixcount = 1

		for i in 1:iteration
			elapsedtime = i * t

			if(array[tempdetectpos] <= cuttemp)
				for h in heatpos
					array[h] = array[h] + heatspeed * t
				end
			end

			Diffusion!(array,width,boxwidth,Df,t)

			array[width] = roomtemp

				write(f,"t = $elapsedtime  : \n")

				for k in recordpos
					write(f,"$(array[k])    ")
				end

				write(f,"\n")

			if(mixpos != 0)
				if(mixcount >= mixcountmax)
					mixing!(array,mixpos)
					mixcount = 0
				end
				mixcount = mixcount + 1
			end

		end
	end
end

function executor(filename)
	open(filename) do f
		tempstring = readline(f)
		while tempstring != ""
			eval(Meta.parse(tempstring))
			tempstring = readline(f)
		end
	end
end

function indextable(q)
	temp = fill(0,q)
	for i in 1:q
		temp[i] = i
	end
end

max_stars_repo_name: Walter-Feng/heat-conduct-in-julia

max_issues_repo_name: Walter-Feng/heat-conduct-in-julia

max_forks_repo_name: Walter-Feng/heat-conduct-in-julia


text:
struct MatrixConvolution{T} <: AbstractArray{T,3}
    arr::Array{T,3}
end

function Base.:+(x::MatrixConvolution, y::MatrixConvolution)

    A = x.arr
    B = y.arr

    T = promote_type(eltype(A), eltype(B))
    @assert axes(A)[1:2] == axes(B)[1:2]

    kmax = max(size(A,3), size(B,3))
    C = zeros(T,size(A)[1:2]...,kmax)

    for k in axes(A,3)
        C[:,:,k] += A[:,:,k]
    end

    for k in axes(B,3)
        C[:,:,k] += B[:,:,k]
    end

    return MatrixConvolution(C)
end

Base.size(x::MatrixConvolution) = size(x.arr)
Base.getindex(x::MatrixConvolution, i::Int) = x.arr[i]
Base.IndexStyle(x::MatrixConvolution) = IndexLinear()

function Base.:*(x::MatrixConvolution, y::Matrix)

    A = x.arr

    T = promote_type(eltype(A), eltype(y))
    @assert axes(A,2) == axes(y,1)

    C = zeros(T, size(A)...)
    for k in axes(C,3)
        C[:,:,k] = A[:,:,k]*y
    end

    return MatrixConvolution(C)
end

function Base.:*(y::Matrix, x::MatrixConvolution)

    A = x.arr

    T = promote_type(eltype(A), eltype(y))
    @assert axes(A,2) == axes(y,1)

    C = zeros(T, size(A)...)
    for k in axes(C,3)
        C[:,:,k] = y*A[:,:,k]
    end

    return MatrixConvolution(C)
end

Base.:*(a::Number, x::MatrixConvolution) = MatrixConvolution(a * x.arr)
Base.:*(x::MatrixConvolution, a::Number) = MatrixConvolution(x.arr * a)
Base.:/(x::MatrixConvolution, a::Number) = MatrixConvolution(x.arr / a)
Base.:-(x::MatrixConvolution) = (-1) * x

function convolve(Z::Array,x,j,k0)
    M,N,K = size(Z)
    y = similar(Z,M)
    fill!(y,0)
    for k ∈ k0 : min(j,K)
        i = j - k + 1
        y += Z[:,:,k] * x[:,i]
    end
    return y
end

convolve(x::MatrixConvolution, y::Matrix, i, j) = convolve(x.arr, y, i, j)

function Base.hvcat((M,N)::Tuple{Int,Int}, as::MatrixConvolution...)
    kmax = maximum(size(a,3) for a in as)

    @assert length(as) == M*N

    li = LinearIndices((1:N,1:M))
    for m in 1:M
        a = as[li[1,m]]
        M1 = size(a,1)
        for n in 2:N
            a = as[li[n,m]]
            @assert size(a,1) == M1
        end
    end

    for n in 1:N
        a = as[li[n,1]]
        N1 = size(a,2)
        for m in 2:M
            a = as[li[n,m]]
            @assert size(a,2) == N1
        end
    end

    Ms = [size(as[li[1,i]],1) for i in 1:M]
    Ns = [size(as[li[j,1]],2) for j in 1:N]

    cMs = pushfirst!(cumsum(Ms),0)
    cNs = pushfirst!(cumsum(Ns),0)
    T = promote_type(eltype.(as)...)
    data = zeros(T, last(cMs), last(cNs), kmax)

    @show size(data)
    @show eltype(data)

    for m in 1:M
        I = cMs[m]+1 : cMs[m+1]
        for n in 1:N
            J = cNs[n]+1 : cNs[n+1]
            a = as[li[n,m]]
            K = 1:size(a,3)
            data[I,J,K] .= a
        end
    end

    return MatrixConvolution(data)
end


text:
@testset "sghmc.jl" begin
    @turing_testset "sghmc constructor" begin
        alg = SGHMC(; learning_rate=0.01, momentum_decay=0.1)
        @test alg isa SGHMC
        sampler = Turing.Sampler(alg)
        @test sampler isa Turing.Sampler{<:SGHMC}

        alg = SGHMC(:m; learning_rate=0.01, momentum_decay=0.1)
        @test alg isa SGHMC
        sampler = Turing.Sampler(alg)
        @test sampler isa Turing.Sampler{<:SGHMC}

        alg = SGHMC(:s; learning_rate=0.01, momentum_decay=0.1)
        @test alg isa SGHMC
        sampler = Turing.Sampler(alg)
        @test sampler isa Turing.Sampler{<:SGHMC}
    end
    @numerical_testset "sghmc inference" begin
        rng = StableRNG(123)

        alg = SGHMC(; learning_rate=0.02, momentum_decay=0.5)
        chain = sample(rng, gdemo_default, alg, 10_000)
        check_gdemo(chain, atol = 0.1)
    end
end

@testset "sgld.jl" begin
    @turing_testset "sgld constructor" begin
        alg = SGLD(; stepsize = PolynomialStepsize(0.25))
        @test alg isa SGLD
        sampler = Turing.Sampler(alg)
        @test sampler isa Turing.Sampler{<:SGLD}

        alg = SGLD(:m; stepsize = PolynomialStepsize(0.25))
        @test alg isa SGLD
        sampler = Turing.Sampler(alg)
        @test sampler isa Turing.Sampler{<:SGLD}

        alg = SGLD(:s; stepsize = PolynomialStepsize(0.25))
        @test alg isa SGLD
        sampler = Turing.Sampler(alg)
        @test sampler isa Turing.Sampler{<:SGLD}
    end
    @numerical_testset "sgld inference" begin
        rng = StableRNG(1)

        chain = sample(rng, gdemo_default, SGLD(; stepsize = PolynomialStepsize(0.5)), 20_000)
        check_gdemo(chain, atol = 0.2)

        # Weight samples by step sizes (cf section 4.2 in the paper by Welling and Teh)
        v = get(chain, [:SGLD_stepsize, :s, :m])
        s_weighted = dot(v.SGLD_stepsize, v.s) / sum(v.SGLD_stepsize)
        m_weighted = dot(v.SGLD_stepsize, v.m) / sum(v.SGLD_stepsize)
        @test s_weighted ≈ 49/24 atol=0.2
        @test m_weighted ≈ 7/6 atol=0.2
    end
end


text:
"""
    number_of_steps(distance::Int64, step_size::Int64)

Number of step_size is calculating the total number of combinations for walking a `distance`
for a given number of step_size. For example, for a `distance` of 3 with a maximum
`step_size` of 3 will provide for possible combinations:

    - 1 step + 1 step + 1 step
    - 1 step + 2 step
    - 2 step + 1 step
    - 3 step

# Arguments
- `distance::Int64`: Distance to go
- `step_size::Int64`: Maximum step size of walking a distance

# Examples
```julia-repl
julia> import ClassicAlgorithmsCollections
julia> ClassicAlgorithmsCollections.number_of_steps(8,3)
81
```
"""
function number_of_steps(distance::Int64, step_size::Int64)

    if distance < 0
        return 0
    end
    if distance == 0
        return 1
    end
    result = 0
    for i in 1:step_size
        result += number_of_steps(distance - i, step_size)
    end
    return result
end

max_stars_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_issues_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_forks_repo_name: Anselmoo/ClassicAlgorithmsCollections


text:
"""
## module Potentials

### Summary

This module implements some basic interatomic potentials in pure Julia, as well
as provides building blocks and prototypes for further implementations
The implementation is done in such a way that they can be used either in "raw"
form or within abstract frameworks.

### Types

### `evaluate`, `evaluate_d`, `evaluate_dd`, `grad`

### The `@D`, `@DD`, `@GRAD` macros

TODO: write documentation

"""
module Potentials

using JuLIP: AbstractAtoms, AbstractNeighbourList, AbstractCalculator,
      bonds, sites,
      JVec, JVecs, mat, vec

# we also import grad from JuLIP, but to define derivatives
import JuLIP: grad, energy, forces, cutoff

export Potential, PairPotential, SitePotential

"""
`Potential`: generic abstract supertype for all potential-like things
"""
abstract Potential <: AbstractCalculator

"""
`PairPotential`: abstract supertype for pair potentials
"""
abstract PairPotential <: Potential

"""
`SitePotential`: abstract supertype for generic site potentials
"""
abstract SitePotential <: Potential

include("potentials_base.jl")
# * @pot, @D, @DD, @GRAD and related things

# Implementation of a generic site potential
# ================================================

energies(pot::SitePotential, at::AbstractAtoms) =
   Float64[ pot(r, R) for (_1,_2, r, R,_4) in sites(at, cutoff(pot)) ]

energy(pot::SitePotential, at::AbstractAtoms) = sum_kbn(energies(pot, at))

function forces(pot::SitePotential, at::AbstractAtoms)
   frc = zerovecs(length(at))
   for (i, j, r, R, _) in sites(at, cutoff(pot))
      dpot = @D pot(r, R)
      frc[j] -= dpot
      frc[i] += sum(dpot)
   end
   return frc
end

include("analyticpotential.jl")
# * AnalyticPotential

include("cutoffs.jl")
#   * SWCutoff
#   * ShiftCutoff
#   * SplineCutoff

include("pairpotentials.jl")
# * PairCalculator
# * LennardJonesPotential
# * MorsePotential
# * SimpleExponential

try
   include("adsite.jl")
   # * FDPotential : Site potential using ForwardDiff
catch
   warn("""adsite.jl could not be included; most likely some AD package is missing;
      at the moment it needs `ForwardDiff, ReverseDiffPrototype`""")
end

include("EMT.jl")
# * EMTCalculator

include("stillingerweber.jl")
# * type StillingerWeber

export ZeroSitePotential

@pot type ZeroSitePotential <: Potential
end

"a site potential that just returns zero"
ZeroSitePotential

evaluate(p::ZeroSitePotential, r, R) = 0.0
evaluate_d(p::ZeroSitePotential, r, R) = zeros(r)
cutoff(::ZeroSitePotential) = 0.0

end


text:
using DelimitedFiles

function step_day(count_vec)
    num_breeding_fish = count_vec[1]
    for i in 1:8
        count_vec[i] = count_vec[i+1]
    end
    count_vec[9] = num_breeding_fish
    count_vec[7] += num_breeding_fish
    return count_vec
end

function test_step_day()
    test_list = [1,2,3,4,5,6,7,8,9]
    @assert step_day(test_list) == [2,3,4,5,6,7,9,9,1]
end

test_step_day()

function step_multiple_days(fish_countvec, num_days)
    for i in 1:num_days
        println("Processing day ", i, " num_fish is ", sum(fish_countvec))
        fish_list = step_day(fish_countvec)
    end
    return fish_countvec
end

# read input file, note single quotes around the delimiter
input = readdlm("input.txt", ',',Int)
# convert to a column vector
input = vec(input)
# create a vector of counts
vector_of_counts = Int64[]
for i in 0:8
    push!(vector_of_counts, count(x->(x==i), input))
end

# step 256 days
output = step_multiple_days(vector_of_counts, 256)
print("number of fish is ", sum(output))


text:
function fake_imgs(nconditions, ntrials, best_condition; best_img::AbstractArray{T,2} = rand(2,2)) where {T}
    output = rand(size(best_img)..., nconditions*ntrials)
    fake_imgs!(output, nconditions, ntrials, best_condition; best_img = best_img)
end

function fake_imgs!(output_img::AbstractArray{T,3}, nconditions, ntrials, best_condition; best_img::AbstractArray{T,2} = rand(2,2)) where {T}
    @assert size(output_img)[1:2] == size(best_img)
    nimgs = nconditions * ntrials
    @assert isinteger(nconditions)
    for c = 1:nconditions
        if c == best_condition
            output_img[:,:, Int((c-1)*ntrials+1):2:Int((c*ntrials))] = best_img #at optimal lag
        else
            output_img[:,:, Int((c-1)*ntrials+1):2:Int((c*ntrials))] = rand(size(best_img)...)
        end
    end
    return output_img
end

function fake_slicetiming_run(nconditions, ntrials, nslices, best_conds_fwd, best_conds_back)
    @assert nslices == length(best_conds_fwd) == length(best_conds_back)
    output = zeros(30,30,2*nconditions*ntrials*nslices + nslices)
    output_fwd = view(output, :,:,nslices+1:2:size(output,3))
    output_back = view(output, :,:,nslices+2:2:size(output,3))
    template =rand(30,30,nslices)
    output[:,:,1:nslices] = template
    for i = 1:nslices
        fwd_sub = view(output_fwd, :,:,1+(i-1)*nconditions*ntrials:i*nconditions*ntrials)
        fake_imgs!(fwd_sub, nconditions, ntrials, best_conds_fwd[i]; best_img = template[:,:,i])
        back_sub = view(output_back, :,:,1+(i-1)*nconditions*ntrials:i*nconditions*ntrials)
        fake_imgs!(back_sub, nconditions, ntrials, best_conds_back[i]; best_img = template[:,:,i])
    end
    return output
end


text:
"""
Implementation of different function systems for the representation of spectral
expansions. Currently, only orthogonal polynomials (for gpc) are supported.

@show recurrence_coeff(HermitePolynomials(),Array(0:3))
@show recurrence_coeff(LegendrePolynomials(),Array(0:3))
@show recurrence_coeff(ChebyshevTPolynomials(),Array(0:5))
@show recurrence_coeff(ChebyshevUPolynomials(),Array(0:5))

@show [gauss_rule(HermitePolynomials(), i) for i in 2:5]
@show [gauss_rule(LaguerrePolynomials(1.2), i) for i in 3:5]

"""
module Bases

include("orthpoly.jl")

end


text:
# Practical Machine learning
# Artificial Neural Network
# Chapter 11

include("nnCostFunction.jl")
include("computeNumericalGradient.jl")
include("debugInitializeWeights.jl")

function checkNNGradients(lambda = 0)
  input_layer_size = 3
  hidden_layer_size = 5
  num_labels = 3
  m = 5

  # We generate some 'random' test data
  Theta1 = debugInitializeWeights(hidden_layer_size, input_layer_size)
  Theta2 = debugInitializeWeights(num_labels, hidden_layer_size)
  # Reusing debugInitializeWeights to generate X
  X  = debugInitializeWeights(m, input_layer_size - 1)
  y  = (1 + mod(1:m, num_labels)')'

  # Unroll parameters
  nn_params = [Theta1[:] ; Theta2[:]]

  # Short hand for cost function
  costFunc = p -> nnCostFunction(p, input_layer_size, hidden_layer_size,
                                 num_labels, X, y, lambda)
	CHECKNNGRADIENTS(lambda)
  cost, grad = costFunc(nn_params)
  numgrad = computeNumericalGradient(costFunc, nn_params)

  # Visually examine the two gradient computations.  The two columns
  # you get should be very similar.
  show([numgrad grad])
  @printf("""

    The above two columns you get should be very similar.
    (Left-Your Numerical Gradient, Right-Analytical Gradient)

  """)

  # Evaluate the norm of the difference between two solutions.
  # If you have a correct implementation, and assuming you used EPSILON = 0.0001
  # in computeNumericalGradient.m, then diff below should be less than 1e-9
  diff = norm(numgrad - grad) / norm(numgrad + grad)

  @printf("""
    If your backpropagation implementation is correct, then
    the relative difference will be small (less than 1e-9).

    Relative Difference: %g
    """, diff)

end


text:
using GoogleMaps
using Dates
using Test

if haskey(ENV, "GOOGLE_MAPS_KEY")

    @testset "Geocode" begin
        response = geocode("1600+Amphitheatre+Parkway,+Mountain+View,+CA")
        @test response["status"] == "OK"
        @test response["results"][1]["formatted_address"] == "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"
        @test response["results"][1]["geometry"]["location"] == Dict{String,Any}("lat" => 37.4226128, "lng" => -122.0854158)
    end

    @testset "Timezone" begin
        location = (37.4226128, -122.0854158)
        timestamp = DateTime("2018-10-30T21:50:31.673")
        response = timezone(location, timestamp)
        @test response["status"] == "OK"
        @test response["timeZoneId"] == "America/Los_Angeles"
    end

else
    @info "Google Maps API key was not found in environment variables, skipping tests..."
end


text:
#===================================================================================================
  Kernel Kernels Module
===================================================================================================#

module MLKernels

import Base: convert, eltype, print, show, string, ==, *, /, +, -, ^, exp, tanh

export

    # Memory
    Orientation,

    # Kernel Functions
    Kernel,
        MercerKernel,
            AbstractExponentialKernel,
                ExponentialKernel,
                LaplacianKernel,
                SquaredExponentialKernel,
                GaussianKernel,
                RadialBasisKernel,
                GammaExponentialKernel,
            AbstractRationalQuadraticKernel,
                RationalQuadraticKernel,
                GammaRationalQuadraticKernel,
            MaternKernel,
            LinearKernel,
            PolynomialKernel,
            ExponentiatedKernel,
            PeriodicKernel,
        NegativeDefiniteKernel,
            PowerKernel,
            LogKernel,
        SigmoidKernel,

    # Kernel Function Properties
    ismercer,
    isnegdef,
    isstationary,
    isisotropic,

    # Kernel Matrix
    kernel,
    kernelmatrix,
    kernelmatrix!,
    centerkernelmatrix!,
    centerkernelmatrix,

    # Kernel Approximation
    NystromFact,
    nystrom

using SpecialFunctions: besselk, gamma
import LinearAlgebra
import Statistics

@doc raw"""
    Orientation

Union of the two `Val` types representing the data matrix orientations:

  1. `Val{:row}` identifies when observation vector corresponds to a row of the data matrix
  2. `Val{:col}` identifies when each observation vector corresponds to a column of the data
     matrix
"""
const Orientation = Union{Val{:row}, Val{:col}}

include("utils.jl")

include("basefunctions.jl")
include("basematrix.jl")

include("kernelfunctions.jl")
include("kernelmatrix.jl")
include("nystrom.jl")

include("deprecated.jl")

end # MLKernels


text:
## Exercise 4-3
## Write a function call that passes t as an argument to square, and then run the macro again.
using ThinkJulia

println("Ans: ")

function square(turtle::Turtle, distance::Int = 100)
    @svg begin
        for i in 1:3
            forward(turtle, distance)
            turn(turtle, -90)
        end

        forward(turtle, distance)
    end
end

function drawSquare()
    turtle = Turtle()
    square(turtle)
end

drawSquare()

println("End.")


text:
using DelayDiffEq, DiffEqProblemLibrary.DDEProblemLibrary
using Test

DDEProblemLibrary.importddeproblems()

# Check that numerical solutions approximate analytical solutions,
# independent of problem structure

const alg = MethodOfSteps(BS3(); constrained = true)

# Single constant delay
@testset "single constant delay" begin
  ## Scalar function
  sol_scalar = solve(DDEProblemLibrary.prob_dde_constant_1delay_scalar, alg; dt = 0.1)

  @test sol_scalar.errors[:l∞] < 3.0e-5
  @test sol_scalar.errors[:final] < 2.1e-5
  @test sol_scalar.errors[:l2] < 1.3e-5

  ## Out-of-place function
  sol_oop = solve(DDEProblemLibrary.prob_dde_constant_1delay_oop, alg; dt = 0.1)

  @test sol_scalar.t ≈ sol_oop.t && sol_scalar.u ≈ sol_oop[1, :]

  ## In-place function
  sol_ip = solve(DDEProblemLibrary.prob_dde_constant_1delay_ip, alg; dt=0.1)

  @test sol_scalar.t ≈ sol_ip.t && sol_scalar.u ≈ sol_ip[1, :]
end

# Two constant delays
@testset "two constant delays" begin
  ## Scalar function
  sol_scalar = solve(DDEProblemLibrary.prob_dde_constant_2delays_scalar, alg; dt = 0.1)

  @test sol_scalar.errors[:l∞] < 4.1e-6
  @test sol_scalar.errors[:final] < 1.5e-6
  @test sol_scalar.errors[:l2] < 2.3e-6

  ## Out-of-place function
  sol_oop = solve(DDEProblemLibrary.prob_dde_constant_2delays_oop, alg; dt=0.1)

  @test sol_scalar.t ≈ sol_oop.t && sol_scalar.u ≈ sol_oop[1, :]

  ## In-place function
  sol_ip = solve(DDEProblemLibrary.prob_dde_constant_2delays_ip, alg; dt=0.1)

  @test sol_scalar.t ≈ sol_ip.t && sol_scalar.u ≈ sol_ip[1, :]
end

max_stars_repo_name: JuliaDiffEq/DelayDiffEq

max_issues_repo_name: JuliaDiffEq/DelayDiffEq

max_forks_repo_name: JuliaDiffEq/DelayDiffEq


text:
# generic lattice plotting in 2D (with fance everything)
function plotLattice(
    		lattice :: L
            ;
            figsize :: Tuple{<:Real, <:Real} = (8,5),
            coordinate_system :: Bool = false,
            kwargs...
        ) where {LS,LB,N,S<:AbstractSite{LS,2},B<:AbstractBond{LB,N},U,L<:AbstractLattice{S,B,U}}

    # make a copy of the lattice
    lattice = deepcopy(lattice)
    # shift the new lattice to the center
    center = sum(point.(sites(lattice))) ./ length(sites(lattice))
    for s in sites(lattice)
        point!(s, point(s) .- center)
    end

    # create a new figure
    fig = PyPlot.figure(figsize = figsize)

    # plot the lattice
    plot(lattice; kwargs...)

    # get the limits
    max_value = maximum([abs(p[i]) for i in 1:2 for p in point.(sites(lattice))])
    # set the axis limits
    xlim(-max_value, max_value)
    ylim(-max_value, max_value)

    # get the current axis
    ax = fig.gca()
    # turn off everthing but the plot
    if !coordinate_system
        ax.set_axis_off()
    end
    # equal aspect ratio
    ax.set_aspect("equal")
    # tighten layout
    tight_layout()
    # reduce the boundaries
    fig.subplots_adjust(bottom=0, top=1, right=1, left=0)
    # returns the figure
    return fig
end

# export plotting function
export plotLattice


text:
using Distributions
using Turing
using Test
using Random

Random.seed!(125)

D = [1.0 1.0 4.0 4.0]

@model MoGtest(D) = begin
  mu1 ~ Normal(1, 1)
  mu2 ~ Normal(4, 1)
  z1 ~ Categorical(2)
  if z1 == 1
    D[1] ~ Normal(mu1, 1)
  else
    D[1] ~ Normal(mu2, 1)
  end
  z2 ~ Categorical(2)
  if z2 == 1
    D[2] ~ Normal(mu1, 1)
  else
    D[2] ~ Normal(mu2, 1)
  end
  z3 ~ Categorical(2)
  if z3 == 1
    D[3] ~ Normal(mu1, 1)
  else
    D[3] ~ Normal(mu2, 1)
  end
  z4 ~ Categorical(2)
  if z4 == 1
    D[4] ~ Normal(mu1, 1)
  else
    D[4] ~ Normal(mu2, 1)
  end
  z1, z2, z3, z4, mu1, mu2
end

pmmh = PMMH(500, SMC(10, :z1, :z2, :z3, :z4), MH(1, :mu1, :mu2))
chain = sample(MoGtest(D), pmmh)

@test mean(chain[:z1]) ≈ 1.0 atol=0.1
@test mean(chain[:z2]) ≈ 1.0 atol=0.1
@test mean(chain[:z3]) ≈ 2.0 atol=0.1
@test mean(chain[:z4]) ≈ 2.0 atol=0.1
@test mean(chain[:mu1]) ≈ 1.0 atol=0.1
@test mean(chain[:mu2]) ≈ 4.0 atol=0.1


text:
# Generates and updates cell list object, and generates mapping for
# finite element mesh elements to a corresponding cell list cells

using BenchmarkTools

include("../../src/part/CellLists.jl")
include("../../src/part/ParticleTypes.jl")  # to load in Point2D type

function isInsideRect_TEST()
  sampleRect = [0.0, 1.0, 0.0, 1.0]
  samplePt = Point2D(rand(),rand())

  @btime isInsideRect($sampleRect,$samplePt)
end

function generateCellList_TEST()
  N = 3
  nodeList = [Point2D(rand(),rand()) for i=1:N]
  TotalBounds = [0.0,1.0,0.0,1.0]
  L = 0.1

  #@code_warntype generateCellList(nodeList,TotalBounds,L)
  @btime generateCellList($nodeList,$TotalBounds,$L)

  cellList = generateCellList(nodeList,TotalBounds,L)

  sum = 0
  for i=1:length(cellList.cells)
    sum += length(cellList.cells[i].nodeList)
  end
  println(N," = ",sum," ?")

  return cellList, nodeList
end

function updateCellList!_TEST()
  N = 1_000
  # generate cell list
  nodeList = [Point2D(rand(),rand()) for i=1:N]
  TotalBounds = [0.0,1.0,0.0,1.0]
  L = 0.1

  cl = generateCellList(nodeList,TotalBounds,L)

  # greate new cell list
  nodeList2 = [Point2D(rand(),rand()) for i=1:N]
  @code_warntype updateCellList!(cl,nodeList2)
  #@btime updateCellList!(deepcopy($(cl)),$nodeList2)

  sum = 0
  for i=1:length(cl.cells)
    sum += length(cl.cells[i].nodeList)
  end
  println(sum)

  nothing
end

"""
  not actually faster
"""
function updateCellList_SMART!_TEST()
  N = 1_000
  # generate cell list
  nodeList = [Point2D(rand(),rand()) for i=1:N]
  TotalBounds = [0.0,1.0,0.0,1.0]
  L = 0.1

  cl = generateCellList(nodeList,TotalBounds,L)

  # greate new cell list
  for i=1:N
    nodeList[i].x += 2*L*(2*rand() - 1.0)
    nodeList[i].y += 2*L*(2*rand() - 1.0)
  end
  @btime updateCellList_SMART!(deepcopy($(cl)),$nodeList)

  sum = 0
  for i=1:cl.nCells
    sum += length(cl.cells[i].nodeList)
  end
  println(sum)

  nothing
end

function femGenerateMap_TEST()
  # generate mesh
  Dom = [-1.0,1.0,-1.0,1.0]
  N    = 64
  mesh = squareMesh(Dom,N,2)

  L = 0.1
  totalBounds = [Dom[1]-L,Dom[2]+L,Dom[3]-L,Dom[4]+L]

  #@code_warntype FEMgenerateMap(mesh,totalBounds,L)
  @btime femGenerateMap($mesh,$totalBounds,$L)
  femCLmap = femGenerateMap(mesh,totalBounds,L)

  println(typeof(femCLmap))

  return femCLmap
end

function getElementFromNode!_TEST()
    # generate mesh
    Dom = [-1.0,1.0,-1.0,1.0]
    N    = 5
    mesh = squareMesh(Dom,N,1)

    elementArray = zeros(Int,4)

    nodeInd = 12

    #@code_warntype getElementFromNode!(elementArray,mesh,nodeInd)
    @btime getElementFromNode!($elementArray,$mesh,$nodeInd)
    #getElementFromNode!(elementArray,mesh,nodeInd)

    if false
      println("node #",nodeInd)
      println("elm array: ",elementArray)
      for ti=1:4
        if elementArray[ti] != 0
          println("cm",elementArray[ti],": ",mesh.cm[elementArray[ti]].NodeList)
        end
      end
    end

    nothing
end

max_stars_repo_name: pseastham/eFEMpart

max_issues_repo_name: pseastham/eFEMpart


text:
function push_clock(cur_player::AbstractPlayer)

  cur_uuid = Base.Random.uuid1()

  cur_player.clock.push = cur_uuid

  one_second = Base.Dates.Millisecond(1000)

  sleep_time = 5 * one_second

  min_logs = 10

  @async while cur_player.round.is_keeping_score && check_clock(cur_player, :push, cur_uuid)

    init_logs = length(cur_player.round.logs)

    if init_logs < min_logs
      sleep(sleep_time)
      continue
    end

    send_logs(cur_player)

    logs_diff = init_logs - length(cur_player.round.logs)

    tetris_js(
      cur_player.game.scope,
      JSString("""
        console.log("Sent $(logs_diff) logs to score api.");
      """)
    )

    sleep(sleep_time)

  end

end


text:
abstract type SolverResult end
abstract type SolverType end
abstract type SolverSubtype end

struct Displacement <: SolverResult end

struct Direct <: SolverType end
struct CG  <: SolverType end

struct MatrixFree <: SolverSubtype end
struct Assembly <: SolverSubtype end

Utilities.getpenalty(solver::AbstractFEASolver) = solver.penalty
function Utilities.setpenalty!(solver::AbstractFEASolver, p)
    solver.prev_penalty = solver.penalty
    penalty = solver.penalty
    solver.penalty = @set penalty.p = p
    solver
end
Utilities.getprevpenalty(solver::AbstractFEASolver) = solver.prev_penalty

function FEASolver(::Type{Displacement}, ::Type{Direct}, problem; kwargs...)
    DirectDisplacementSolver(problem; kwargs...)
end

function FEASolver(::Type{Displacement}, ::Type{CG}, problem; kwargs...)
    FEASolver(Displacement, CG, MatrixFree, problem; kwargs...)
end

function FEASolver(::Type{Displacement}, ::Type{CG}, ::Type{MatrixFree}, problem; kwargs...)
    StaticMatrixFreeDisplacementSolver(problem; kwargs...)
end

function FEASolver(::Type{Displacement}, ::Type{CG}, ::Type{Assembly}, problem; kwargs...)
    PCGDisplacementSolver(problem; kwargs...)
end

default_quad_order(problem) = TopOptProblems.getgeomorder(problem) == 2 ? 6 : 4


text:
using Test

include("../../utils/preprocesado_datos.jl")

file_path= "src/Instancias_APC/"

struct DataFile
    route::String
    class_atributte::String
end

files = [
    DataFile(file_path*"ionosphere.arff", "class"),
    DataFile(file_path*"parkinsons.arff", "Class"),
    DataFile(file_path*"spectf-heart.arff", "Class"),
]

@testset "Carga y normalizacición de los datos" begin
    for file in files
        data , labels = DataLabelArff(file.route, file.class_atributte)
        for col in data
            @test 0 <= minimum(col)
            @test 1 >= maximum(col)
        end
    end
end


text:
using Statistics

"""calculate number of hydrogenerators"""
function countgenerators!(data::Dict)
    data["hydro"]["nHyd"] = size(data["hydro"]["Hydrogenerators"],1)
end

"""compoute upstream_hydro"""
function upstream_hydro!(data::Dict)
    for i in 1:data["hydro"]["nHyd"]
        data["hydro"]["Hydrogenerators"][i]["upstrem_hydros_turn"] = []
        data["hydro"]["Hydrogenerators"][i]["upstrem_hydros_spill"] = []
    end
    for i in 1:data["hydro"]["nHyd"]
        for idx in data["hydro"]["Hydrogenerators"][i]["downstream_turn"]
            j = findall(x->x["index"]==idx,data["hydro"]["Hydrogenerators"])
            if length(j)!=1
                error("Incoherent downstream_turn list")
            end
            j = j[1]
            data["hydro"]["Hydrogenerators"][j]["upstrem_hydros_turn"] = append!(data["hydro"]["Hydrogenerators"][j]["upstrem_hydros_turn"],i)
        end
        for idx in data["hydro"]["Hydrogenerators"][i]["downstream_spill"]
            j = findall(x->x["index"]==idx,data["hydro"]["Hydrogenerators"])
            if length(j)!=1
                error("Incoherent downstream_spill list")
            end
            j = j[1]
            data["hydro"]["Hydrogenerators"][j]["upstrem_hydros_spill"] = append!(data["hydro"]["Hydrogenerators"][j]["upstrem_hydros_spill"],i)
        end
    end
    for i in 1:data["hydro"]["nHyd"]
        unique!(data["hydro"]["Hydrogenerators"][i]["upstrem_hydros_turn"])
        unique!(data["hydro"]["Hydrogenerators"][i]["upstrem_hydros_spill"])
    end
    return nothing
end

"""create ref for anonimous variables on model"""
function createvarrefs!(sp::JuMP.Model,pm::AbstractPowerModel)
    for listvarref in values(PowerModels.var(pm,pm.cnw,pm.ccnd))
        for variableref in values(listvarref)
            if typeof(variableref) == JuMP.VariableRef
                sp[Symbol(name(variableref))] = variableref
            end
        end
    end
end

"""count available inflow data"""
function countavailableinflow!(data::Dict)
    data["hydro"]["size_inflow"] = size(data["hydro"]["Hydrogenerators"][1]["inflow"])
end

"""circular index"""
function cidx(i::Int,n::Int)
    mod(i,n)==0 ? n : mod(i,n)
end

"""hydrogenerators indexes"""
function idx_hydro(data::Dict)
    [hydro["i_grid"] for hydro in data["hydro"]["Hydrogenerators"] if hydro["index_grid"] != nothing]
end

"""find vector index of hydrogenerators on grid"""
function index2i!(data::Dict)
    for i=1:data["hydro"]["nHyd"]
        if data["hydro"]["Hydrogenerators"][i]["index_grid"] != nothing
            i_grid = findall(x->x["index"] == data["hydro"]["Hydrogenerators"][i]["index_grid"],data["powersystem"]["gen"])
            if length(i_grid) != 1
                error("Generator of hydro with index $(data["hydro"]["Hydrogenerators"][i]["index"]) not identifiable")
            end
            data["hydro"]["Hydrogenerators"][i]["i_grid"] = parse(Int64,i_grid[1])
        end
    end
    return nothing
end

"""gather useful information from data"""
function gatherusefulinfo!(data::Dict)
    # calculate number of hydrogenerators
    countgenerators!(data)

    # compoute upstream_hydro
    upstream_hydro!(data)

    # count available inflow data
    countavailableinflow!(data)

    # find index hydrogen
    index2i!(data)

    # add zeroed loads on buses w no loads for deficit coherence
    add_loads!(data)

    return nothing
end

"""Quantile Scenarios"""
function quantile_scen(scen::Array{Float64,2},quant::Float64)
    return quantile_scen(scen,[quant])[:,1]
end

"""Quantile Scenarios"""
function quantile_scen(scen::Array{Float64,2},quants::Array{Float64};output_dict::Bool=false)
    quantiles = [Statistics.quantile(scen[i, :], quant) for i = 1:size(scen, 1),quant in quants]
    if output_dict
        output = Dict()
        for col = 1:length(quants)
            quant = quants[col]
            output["$(quant*100)%"] = quantiles[:,col]
        end
        return output
    end

    return quantiles
end

"""Multilayer Dict to Onelayer Dict"""
function flat_dict(mlt_dict::Dict{Any,Any})
    if typeof(collect(values(mlt_dict))[1]) != Dict{Any,Any}
        return mlt_dict
    end

    one_dict = Dict()
    kws = collect(keys(mlt_dict))

    recursion_ret = [flat_dict(i) for i in values(mlt_dict)]
    for i = 1:size(recursion_ret,1)
        item = recursion_ret[i]
        for (ikw,val) in item
            one_dict[kws[i]*"_"*ikw] = val
        end
    end

    return one_dict

end

"""truncate values dict"""
function signif_dict(one_dict::Dict, digts::Integer)
    for kw in keys(one_dict)
        if typeof(one_dict[kw]) <: AbstractFloat
            one_dict[kw] = round.(one_dict[kw],digits=digts)
        end
    end
    return one_dict
end

"""add zeroed loads on buses w no loads for deficit coherence"""
function add_loads!(data::Dict)
    locked_buses = unique([load["load_bus"] for load in values(data["powersystem"]["load"])])
    free_buses = setdiff(collect(1:length(data["powersystem"]["bus"])),locked_buses)

    load_idx = length(data["powersystem"]["load"])+1
    for bus in free_buses
        data["powersystem"]["load"]["$load_idx"] = load_dict(   load_bus = bus,
                                                                pd = 0,
                                                                index = load_idx)
        load_idx +=1
    end
end

""" creates a load dictionary """
function load_dict(;
        load_bus= 1, # bus where load is present
        status= 1, # status (ON: 1, OFF:0)
        pd= 1, # reactive power demand
        qd= 0.12*pd, # real power demand
        index= 1) # index

    lod = Dict( "load_bus"=> load_bus,
        "status"=> status,
        "qd"=> qd,
        "pd"=> pd,
        "index"=> index)
end

""" water value """
function water_energy!(data::Dict)
    countgenerators!(data)
    for i in 1:data["hydro"]["nHyd"]
        if !haskey(data["hydro"]["Hydrogenerators"][i],"water_energy")
            water_energy_res!(data,i)
        end
    end
    return nothing
end

""" water value """
function water_energy_res!(data::Dict,res::Int)
    data["hydro"]["Hydrogenerators"][res]["water_energy"] = 0.0
    water_val_turn = data["hydro"]["Hydrogenerators"][res]["production_factor"]
    for idx in data["hydro"]["Hydrogenerators"][res]["downstream_turn"]
        j = findall(x->x["index"]==idx,data["hydro"]["Hydrogenerators"])
        if length(j)!=1
            error("Incoherent downstream_turn list")
        end
        j = j[1]
        water_val_turn += water_energy_res!(data,j)
    end
    water_val_spill = 0.0
    for idx in data["hydro"]["Hydrogenerators"][res]["downstream_spill"]
        j = findall(x->x["index"]==idx,data["hydro"]["Hydrogenerators"])
        if length(j)!=1
            error("Incoherent downstream_spill list")
        end
        j = j[1]
        water_val_spill += water_energy_res!(data,j)
    end

    data["hydro"]["Hydrogenerators"][res]["water_energy"] += water_val_turn >= water_val_spill ? water_val_turn : water_val_spill

    return data["hydro"]["Hydrogenerators"][res]["water_energy"]
end


text:
#  Copyright 2017, Iain Dunning, Joey Huchette, Miles Lubin, and contributors
#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
#  file, You can obtain one at https://mozilla.org/MPL/2.0/.
#############################################################################
# JuMP
# An algebraic modeling language for Julia
# See https://github.com/jump-dev/JuMP.jl
#############################################################################

const _JuMPTypes = Union{AbstractJuMPScalar,NonlinearExpression}
_float(x::Number) = convert(Float64, x)
_float(J::UniformScaling) = _float(J.λ)

# Overloads
#
# Different objects that must all interact:
# 1. _Constant
# 2. AbstractVariableRef
# 4. GenericAffExpr
# 5. GenericQuadExpr

# _Constant
# _Constant--_Constant obviously already taken care of!
# _Constant--VariableRef
function Base.:+(lhs::_Constant, rhs::AbstractVariableRef)
    return _build_aff_expr(_float(lhs), 1.0, rhs)
end
function Base.:-(lhs::_Constant, rhs::AbstractVariableRef)
    return _build_aff_expr(_float(lhs), -1.0, rhs)
end
function Base.:*(lhs::_Constant, rhs::AbstractVariableRef)
    if iszero(lhs)
        return zero(GenericAffExpr{Float64,typeof(rhs)})
    else
        return _build_aff_expr(0.0, _float(lhs), rhs)
    end
end
# _Constant--_GenericAffOrQuadExpr
function Base.:+(lhs::_Constant, rhs::_GenericAffOrQuadExpr)
    result = _MA.mutable_copy(rhs)
    add_to_expression!(result, lhs)
    return result
end
function Base.:-(lhs::_Constant, rhs::_GenericAffOrQuadExpr)
    result = -rhs
    add_to_expression!(result, lhs)
    return result
end
function Base.:*(lhs::_Constant, rhs::_GenericAffOrQuadExpr)
    if iszero(lhs)
        return zero(rhs)
    else
        α = _constant_to_number(lhs)
        return map_coefficients(c -> α * c, rhs)
    end
end

# AbstractVariableRef (or, AbstractJuMPScalar)
# TODO: What is the role of AbstractJuMPScalar??
Base.:+(lhs::AbstractJuMPScalar) = lhs
Base.:-(lhs::AbstractVariableRef) = _build_aff_expr(0.0, -1.0, lhs)
Base.:*(lhs::AbstractJuMPScalar) = lhs # make this more generic so extensions don't have to define unary multiplication for our macros
# AbstractVariableRef--_Constant
Base.:+(lhs::AbstractVariableRef, rhs::_Constant) = (+)(rhs, lhs)
Base.:-(lhs::AbstractVariableRef, rhs::_Constant) = (+)(-rhs, lhs)
Base.:*(lhs::AbstractVariableRef, rhs::_Constant) = (*)(rhs, lhs)
Base.:/(lhs::AbstractVariableRef, rhs::_Constant) = (*)(1.0 / rhs, lhs)
# AbstractVariableRef--AbstractVariableRef
function Base.:+(lhs::V, rhs::V) where {V<:AbstractVariableRef}
    return _build_aff_expr(0.0, 1.0, lhs, 1.0, rhs)
end
function Base.:-(lhs::V, rhs::V) where {V<:AbstractVariableRef}
    if lhs == rhs
        return zero(GenericAffExpr{Float64,V})
    else
        return _build_aff_expr(0.0, 1.0, lhs, -1.0, rhs)
    end
end
function Base.:*(lhs::V, rhs::V) where {V<:AbstractVariableRef}
    return GenericQuadExpr(
        GenericAffExpr{Float64,V}(),
        UnorderedPair(lhs, rhs) => 1.0,
    )
end
# AbstractVariableRef--GenericAffExpr
function Base.:+(
    lhs::V,
    rhs::GenericAffExpr{C,V},
) where {C,V<:AbstractVariableRef}
    # For the variables to have the proper order in the result, we need to add the lhs first.
    result = zero(rhs)
    result.constant = rhs.constant
    sizehint!(result, length(linear_terms(rhs)) + 1)
    add_to_expression!(result, one(C), lhs)
    for (coef, var) in linear_terms(rhs)
        add_to_expression!(result, coef, var)
    end
    return result
end

function Base.:-(
    lhs::V,
    rhs::GenericAffExpr{C,V},
) where {C,V<:AbstractVariableRef}
    # For the variables to have the proper order in the result, we need to add the lhs first.
    result = zero(rhs)
    result.constant = -rhs.constant
    sizehint!(result, length(linear_terms(rhs)) + 1)
    add_to_expression!(result, one(C), lhs)
    for (coef, var) in linear_terms(rhs)
        add_to_expression!(result, -coef, var)
    end
    return result
end

function Base.:*(
    lhs::V,
    rhs::GenericAffExpr{C,V},
) where {C,V<:AbstractVariableRef}
    if !iszero(rhs.constant)
        result = GenericQuadExpr{C,V}(lhs * rhs.constant)
    else
        result = zero(GenericQuadExpr{C,V})
    end
    for (coef, var) in linear_terms(rhs)
        add_to_expression!(result, coef, lhs, var)
    end
    return result
end
function Base.:/(lhs::AbstractVariableRef, rhs::GenericAffExpr)
    return error("Cannot divide a variable by an affine expression")
end
# AbstractVariableRef--GenericQuadExpr
function Base.:+(v::AbstractVariableRef, q::GenericQuadExpr)
    return GenericQuadExpr(v + q.aff, copy(q.terms))
end
function Base.:-(v::AbstractVariableRef, q::GenericQuadExpr)
    result = -q
    # This makes an unnecessary copy of aff, but it's important for v to appear
    # first.
    result.aff = v + result.aff
    return result
end

# GenericAffExpr
Base.:+(lhs::GenericAffExpr) = lhs
Base.:-(lhs::GenericAffExpr) = map_coefficients(-, lhs)
# GenericAffExpr--_Constant
Base.:+(lhs::GenericAffExpr, rhs::_Constant) = (+)(rhs, lhs)
Base.:-(lhs::GenericAffExpr, rhs::_Constant) = (+)(-rhs, lhs)
Base.:*(lhs::GenericAffExpr, rhs::_Constant) = (*)(rhs, lhs)
function Base.:/(lhs::GenericAffExpr, rhs::_Constant)
    return map_coefficients(c -> c / rhs, lhs)
end
function Base.:^(lhs::Union{AbstractVariableRef,GenericAffExpr}, rhs::Integer)
    if rhs == 2
        return lhs * lhs
    elseif rhs == 1
        return convert(GenericQuadExpr{Float64,variable_ref_type(lhs)}, lhs)
    elseif rhs == 0
        return one(GenericQuadExpr{Float64,variable_ref_type(lhs)})
    else
        error(
            "Only exponents of 0, 1, or 2 are currently supported. Are you trying to build a nonlinear problem? Make sure you use @NLconstraint/@NLobjective.",
        )
    end
end
function Base.:^(lhs::Union{AbstractVariableRef,GenericAffExpr}, rhs::_Constant)
    return error(
        "Only exponents of 0, 1, or 2 are currently supported. Are you trying to build a nonlinear problem? Make sure you use @NLconstraint/@NLobjective.",
    )
end
# GenericAffExpr--AbstractVariableRef
function Base.:+(
    lhs::GenericAffExpr{C,V},
    rhs::V,
) where {C,V<:AbstractVariableRef}
    return add_to_expression!(copy(lhs), one(C), rhs)
end
function Base.:-(
    lhs::GenericAffExpr{C,V},
    rhs::V,
) where {C,V<:AbstractVariableRef}
    return add_to_expression!(copy(lhs), -one(C), rhs)
end
# Don't fall back on AbstractVariableRef*GenericAffExpr to preserve lhs/rhs
# consistency (appears in printing).
function Base.:*(
    lhs::GenericAffExpr{C,V},
    rhs::V,
) where {C,V<:AbstractVariableRef}
    if !iszero(lhs.constant)
        result = GenericQuadExpr{C,V}(lhs.constant * rhs)
    else
        result = zero(GenericQuadExpr{C,V})
    end
    for (coef, var) in linear_terms(lhs)
        add_to_expression!(result, coef, var, rhs)
    end
    return result
end
function Base.:/(lhs::GenericAffExpr, rhs::AbstractVariableRef)
    return error("Cannot divide affine expression by a variable")
end
# AffExpr--AffExpr
function Base.:+(
    lhs::GenericAffExpr{C,V},
    rhs::GenericAffExpr{C,V},
) where {C,V<:_JuMPTypes}
    if length(linear_terms(lhs)) > 50 || length(linear_terms(rhs)) > 50
        if length(linear_terms(lhs)) > 1
            operator_warn(owner_model(first(linear_terms(lhs))[2]))
        end
    end
    return add_to_expression!(copy(lhs), rhs)
end

function Base.:-(
    lhs::GenericAffExpr{C,V},
    rhs::GenericAffExpr{C,V},
) where {C,V<:_JuMPTypes}
    result = copy(lhs)
    result.constant -= rhs.constant
    sizehint!(result, length(linear_terms(lhs)) + length(linear_terms(rhs)))
    for (coef, var) in linear_terms(rhs)
        add_to_expression!(result, -coef, var)
    end
    return result
end

function Base.:*(
    lhs::GenericAffExpr{C,V},
    rhs::GenericAffExpr{C,V},
) where {C,V<:_JuMPTypes}
    result = zero(GenericQuadExpr{C,V})
    add_to_expression!(result, lhs, rhs)
    return result
end
# GenericAffExpr--GenericQuadExpr
function Base.:+(a::GenericAffExpr, q::GenericQuadExpr)
    return GenericQuadExpr(a + q.aff, copy(q.terms))
end
function Base.:-(a::GenericAffExpr, q::GenericQuadExpr)
    result = -q
    # This makes an unnecessary copy of aff, but it's important for a to appear
    # first.
    result.aff = a + result.aff
    return result
end

# GenericQuadExpr
Base.:+(lhs::GenericQuadExpr) = lhs
Base.:-(lhs::GenericQuadExpr) = map_coefficients(-, lhs)
# GenericQuadExpr--_Constant
# We don't do `+rhs` as `UniformScaling` does not support unary `+`
Base.:+(lhs::GenericQuadExpr, rhs::_Constant) = (+)(rhs, lhs)
Base.:-(lhs::GenericQuadExpr, rhs::_Constant) = (+)(-rhs, lhs)
Base.:*(lhs::GenericQuadExpr, rhs::_Constant) = (*)(rhs, lhs)
Base.:/(lhs::GenericQuadExpr, rhs::_Constant) = (*)(inv(rhs), lhs)
# GenericQuadExpr--AbstractVariableRef
function Base.:+(q::GenericQuadExpr, v::AbstractVariableRef)
    return GenericQuadExpr(q.aff + v, copy(q.terms))
end
function Base.:-(q::GenericQuadExpr, v::AbstractVariableRef)
    return GenericQuadExpr(q.aff - v, copy(q.terms))
end
function Base.:*(q::GenericQuadExpr, v::AbstractVariableRef)
    return error("Cannot multiply a quadratic expression by a variable")
end
function Base.:/(q::GenericQuadExpr, v::AbstractVariableRef)
    return error("Cannot divide a quadratic expression by a variable")
end
# GenericQuadExpr--GenericAffExpr
function Base.:+(q::GenericQuadExpr, a::GenericAffExpr)
    return GenericQuadExpr(q.aff + a, copy(q.terms))
end
function Base.:-(q::GenericQuadExpr, a::GenericAffExpr)
    return GenericQuadExpr(q.aff - a, copy(q.terms))
end
function Base.:*(q::GenericQuadExpr, a::GenericAffExpr)
    return error("Cannot multiply a quadratic expression by an aff. expression")
end
function Base.:/(q::GenericQuadExpr, a::GenericAffExpr)
    return error("Cannot divide a quadratic expression by an aff. expression")
end
# GenericQuadExpr--GenericQuadExpr
function Base.:+(q1::GenericQuadExpr, q2::GenericQuadExpr)
    result = copy(q1)
    for (coef, var1, var2) in quad_terms(q2)
        add_to_expression!(result, coef, var1, var2)
    end
    for (coef, var) in linear_terms(q2)
        add_to_expression!(result, coef, var)
    end
    result.aff.constant += q2.aff.constant
    return result
end
function Base.:-(q1::GenericQuadExpr, q2::GenericQuadExpr)
    result = copy(q1)
    for (coef, var1, var2) in quad_terms(q2)
        add_to_expression!(result, -coef, var1, var2)
    end
    for (coef, var) in linear_terms(q2)
        add_to_expression!(result, -coef, var)
    end
    result.aff.constant -= q2.aff.constant
    return result
end

function Base.:(==)(lhs::GenericAffExpr, rhs::GenericAffExpr)
    return (lhs.terms == rhs.terms) && (lhs.constant == rhs.constant)
end
function Base.:(==)(lhs::GenericQuadExpr, rhs::GenericQuadExpr)
    return (lhs.terms == rhs.terms) && (lhs.aff == rhs.aff)
end

# Base Julia's generic fallback vecdot, aka dot, requires that dot, aka LinearAlgebra.dot, be defined
# for scalars, so instead of defining them one-by-one, we will
# fallback to the multiplication operator
LinearAlgebra.dot(lhs::_JuMPTypes, rhs::_JuMPTypes) = lhs * rhs
LinearAlgebra.dot(lhs::_JuMPTypes, rhs::_Constant) = lhs * rhs
LinearAlgebra.dot(lhs::_Constant, rhs::_JuMPTypes) = lhs * rhs

function Base.promote_rule(V::Type{<:AbstractVariableRef}, R::Type{<:Real})
    return GenericAffExpr{Float64,V}
end
function Base.promote_rule(
    V::Type{<:AbstractVariableRef},
    ::Type{<:GenericAffExpr{T}},
) where {T}
    return GenericAffExpr{T,V}
end
function Base.promote_rule(
    V::Type{<:AbstractVariableRef},
    ::Type{<:GenericQuadExpr{T}},
) where {T}
    return GenericQuadExpr{T,V}
end
function Base.promote_rule(
    ::Type{GenericAffExpr{S,V}},
    R::Type{<:Real},
) where {S,V}
    return GenericAffExpr{promote_type(S, R),V}
end
function Base.promote_rule(
    ::Type{<:GenericAffExpr{S,V}},
    ::Type{<:GenericQuadExpr{T,V}},
) where {S,T,V}
    return GenericQuadExpr{promote_type(S, T),V}
end
function Base.promote_rule(
    ::Type{GenericQuadExpr{S,V}},
    R::Type{<:Real},
) where {S,V}
    return GenericQuadExpr{promote_type(S, R),V}
end

Base.transpose(x::AbstractJuMPScalar) = x

# only real scalars are supported
Base.conj(x::AbstractJuMPScalar) = x

# Can remove the following code once == overloading is removed

function LinearAlgebra.issymmetric(x::Matrix{T}) where {T<:_JuMPTypes}
    (n = size(x, 1)) == size(x, 2) || return false
    for i in 1:n, j in (i+1):n
        isequal(x[i, j], x[j, i]) || return false
    end
    return true
end

###############################################################################
# nonlinear function fallbacks for JuMP built-in types
###############################################################################

const op_hint = "Are you trying to build a nonlinear problem? Make sure you use @NLconstraint/@NLobjective."
for (func, _) in Calculus.symbolic_derivatives_1arg(),
    typ in [:AbstractVariableRef, :GenericAffExpr, :GenericQuadExpr]

    errstr = "$func is not defined for type $typ. $op_hint"
    if isdefined(Base, func)
        @eval Base.$(func)(::$typ) = error($errstr)
    end
end

function Base.:*(
    ::T,
    ::S,
) where {
    T<:GenericQuadExpr,
    S<:Union{AbstractVariableRef,GenericAffExpr,GenericQuadExpr},
}
    return error("*(::$T,::$S) is not defined. $op_hint")
end
function Base.:*(lhs::GenericQuadExpr, rhs::GenericQuadExpr)
    return error(
        "*(::GenericQuadExpr,::GenericQuadExpr) is not defined. $op_hint",
    )
end
function Base.:*(
    ::S,
    ::T,
) where {
    T<:GenericQuadExpr,
    S<:Union{AbstractVariableRef,GenericAffExpr,GenericQuadExpr},
}
    return error("*(::$S,::$T) is not defined. $op_hint")
end
function Base.:/(
    ::S,
    ::T,
) where {
    S<:Union{_Constant,AbstractVariableRef,GenericAffExpr,GenericQuadExpr},
    T<:Union{AbstractVariableRef,GenericAffExpr,GenericQuadExpr},
}
    return error("/(::$S,::$T) is not defined. $op_hint")
end

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
__precompile__(true)
module DoloLinter
    import YAML
    include("../src/linter.jl")
end

import DoloLinter: lint
using ArgParse

s = ArgParseSettings()
@add_arg_table s begin
    "--format"
        arg_type = String
        default = "human"
        help = "output format"
    "filename"
        help = "filename"
        required = true
end

parsed_args = parse_args(ARGS, s)

filename = parsed_args["filename"]
format = parsed_args["format"]

lint(filename)


text:
__precompile__()

module MeshCat

using WebIO
import AssetRegistry
using GeometryTypes, CoordinateTransformations
using Rotations: rotation_between, Rotation
using Colors: Color, Colorant, RGB, RGBA, alpha
using StaticArrays: StaticVector, SVector, SDiagonal
using GeometryTypes: raw
using Parameters: @with_kw
using Base.Random: UUID, uuid1
using DocStringExtensions: SIGNATURES
using JSExpr: @js, @new, @var
using Base.Filesystem: rm
using BinDeps: download_cmd, unpack_cmd

import Base: delete!, length
import MsgPack: pack, Ext
import GeometryTypes: origin, radius

export Visualizer,
       ViewerWindow,
       IJuliaCell

export setobject!,
       settransform!,
       delete!,
       setprop!,
       setanimation!

export AbstractVisualizer,
       AbstractMaterial,
       AbstractObject,
       GeometryLike

export Object,
       HyperEllipsoid,
       HyperCylinder,
       PointCloud,
       Triad,
       Mesh,
       Points,
       LineSegments

export PointsMaterial,
       MeshLambertMaterial,
       MeshBasicMaterial,
       MeshPhongMaterial,
       LineBasicMaterial,
       Texture,
       PngImage

export Animation,
       atframe

include("trees.jl")
using .SceneTrees
include("geometry.jl")
include("objects.jl")
include("animations.jl")
include("commands.jl")
include("abstract_visualizer.jl")
include("lowering.jl")
include("msgpack.jl")
include("visualizer.jl")
include("animation_visualizer.jl")
include("servers.jl")

const VIEWER_ROOT = joinpath(@__DIR__, "..", "assets", "meshcat", "dist")

function develop_meshcat_assets(skip_confirmation=false)
    meshcat_dir = abspath(joinpath(@__DIR__, "..", "assets", "meshcat"))
    if !skip_confirmation
        println("CAUTION: This will delete all downloaded meshcat assets and replace them with a git clone.")
        println("The following path will be overwritten:")
        println(meshcat_dir)
        println("To undo this operation, you will need to manually remove that directory and then run `Pkg.build(\"MeshCat\")`")
        print("Proceed? (y/n) ")
        choice = chomp(readline())
        if isempty(choice) || lowercase(choice[1]) != 'y'
            println("Canceled.")
            return
        end
    end
    println("Removing $meshcat_dir")
    rm(meshcat_dir, force=true, recursive=true)
    run(`git clone https://github.com/rdeits/meshcat $meshcat_dir`)
    rm(joinpath(meshcat_dir, "..", "meshcat.stamp"))
end

const ASSET_KEYS = String[]

function __init__()
    push!(ASSET_KEYS, AssetRegistry.register(abspath(joinpath(VIEWER_ROOT, "main.min.js"))))
end

end


text:
typedef struct Node *list;

struct Node {
  int elem;
  list next;
};

int main() {
  printInt(length(fromTo(1,50)));
  printInt(length2(fromTo(1,100)));
  return 0;
}

int head (list xs) {
  return xs -> elem;
}

list cons (int x, list xs) {
  list n;
  n = new Node;
  n->elem = x;
  n->next = xs;
  return n;
}

int length (list xs) {
  if (xs==(list)null)
    return 0;
  else
    return 1 + length (xs->next);
}

list fromTo (int m, int n) {
  if (m>n)
    return (list)null;
  else
    return cons (m,fromTo (m+1,n));
}

int length2 (list xs) {
  int res = 0;
  while (xs != (list)null) {
    res++;
    xs = xs->next;
  }
  return res;
}

max_stars_repo_name: carlostome/Javalette-Compiler

max_issues_repo_name: carlostome/Javalette-Compiler

max_forks_repo_name: carlostome/Javalette-Compiler


text:
abstract ValueSupport
type Discrete   <: ValueSupport end
type Continuous <: ValueSupport end

eltype(::Type{Discrete}) = Int
eltype(::Type{Continuous}) = Float64

abstract VariateForm
type Univariate    <: VariateForm end
type Multivariate  <: VariateForm end
type Matrixvariate <: VariateForm end

abstract Sampleable{F<:VariateForm,S<:ValueSupport}

length(::Sampleable{Univariate}) = 1
size(::Sampleable{Univariate}) = ()

## generic batch rand methods

function rand!(s::Sampleable{Univariate}, A::AbstractArray)
    for i in 1:length(A)
        @inbounds A[i] = rand(s)
    end
    return A
end

rand{S<:ValueSupport}(s::Sampleable{Univariate,S}, shp::Union(Int,(Int...))) =
	rand!(s, Array(eltype(S), shp))

function rand!(s::Sampleable{Multivariate}, A::DenseMatrix)
	for i = 1:size(A,2)
		rand!(s, view(A,:,i))
	end
	return A
end

rand{S<:ValueSupport}(s::Sampleable{Multivariate,S}) =
	rand!(s, Array(eltype(S), length(s)))

rand{S<:ValueSupport}(s::Sampleable{Multivariate,S}, n::Int) =
	rand!(s, Array(eltype(S), length(s), n))

function rand!{M<:Matrix}(s::Sampleable{Matrixvariate}, X::Array{M})
    for i in 1:length(X)
        X[i] = rand(s)
    end
    return X
end

rand{S<:ValueSupport}(s::Sampleable{Matrixvariate,S}, n::Int) =
	rand!(s, Array(Matrix{eltype(S)}, n))


text:
# RanDAGen/src/generator.jl
# Licensed under the MIT License. See LICENSE.md file in the project root for
# full license information.

"""
Configuration Options

    This package provides the following configuration options for customizing the generated
    DAG's.

Local
- `fatness::Float64`: Controls the width of the graph. Higher == more tasks per level. Defaults to 0.5
- `communication_ratio::Float64`: Controls the amount of communication between processes. Defaults to 0.0
- `data_range::UnitRange{Int64}`: Defaults to 2048:11264
- `alpha_range::UnitRange{Float64}`: Defaults to 0.0:0.2
- `regular::Float64`: Defaults to 0.9 | Must be between 0 and 1
- `jump::Int64`: Defaults to 0
- `density::Float64`: Defaults to 0.5
- `max_task::Int64`: Defaults to 100
- `output_stream::IOStream`: Defaults to stdout
"""

function GenerateTasks(max_tasks::Int64;
    communication_ratio::Float64,
    data_range::UnitRange{Int64},
    alpha_range::UnitRange{Float64},
    jump::Int64) begin

    comm = :none
    if 1-rand() < communication_ratio
        comm = :yes
    end

end

function GetTaskPerLevel(fat::Float64, max_tasks::Int64, variation::Float64) begin
    total_tasks = 0
    levels = Array{Int64,1}()

    _, integral = modf(exp(fat * log(max_tasks)))

    tasks_per_level = floor(Int,integral)

    while total_tasks < max_tasks

        tasks = rand(tasks_per_level-variation*tasks_per_level:tasks_per_level+variation*tasks_per_level)

        if total_tasks + tasks > max_tasks
            tasks = max_tasks - total_tasks
        end

        append!(levels, tasks)

        total_tasks += tasks
    end
    return levels
end


text:
export SensFspMatrix

abstract type ForwardSensFspMatrix end

include("./forwardsensfspmatrixsparse/sensfspmatrixsparse.jl")


text:
function currency_exchange_rate(from_currency::String, to_currency::String; client = GLOBAL[], parser = "default")
    uri = _form_uri_head(client, "CURRENCY_EXCHANGE_RATE") * "&from_currency=$from_currency&to_currency=$to_currency" * _form_uri_tail(client, nothing, nothing)
    data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
    p = _parser(parser, "json")
    return p(data)
end

function fx_intraday(from_currency::String, to_currency::String, interval::String="1min"; client = GLOBAL[], outputsize::String="compact", datatype::String="json", parser = "default")
    @argcheck in(interval, ["1min", "5min", "15min", "30min", "60min"])
    @argcheck in(outputsize, ["compact", "full"])
    @argcheck in(datatype, ["json", "csv"])

    uri = _form_uri_head(client, "FX_INTRADAY") * "&from_symbol=$from_currency&to_symbol=$to_currency&interval=$interval" * _form_uri_tail(client, outputsize, datatype)
    data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
    p = _parser(parser, datatype)
    return p(data)
end

function fx_daily(from_currency::String, to_currency::String; client = GLOBAL[], outputsize::String="compact", datatype::String="json", parser = "default")
    @argcheck in(outputsize, ["compact", "full"])
    @argcheck in(datatype, ["json", "csv"])

    uri = _form_uri_head(client, "FX_DAILY") * "&from_symbol=$from_currency&to_symbol=$to_currency" * _form_uri_tail(client, outputsize, datatype)
    data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
    p = _parser(parser, datatype)
    return p(data)
end

for func in (:weekly, :monthly)
    x = "fx_$(func)"
    fname = Symbol(x)
    @eval begin
        function ($fname)(from_currency::String, to_currency::String; client = GLOBAL[], datatype::String="json", parser = "default")
            @argcheck in(datatype, ["json", "csv"])
            uri = _form_uri_head(client, uppercase($x)) * "&from_symbol=$from_currency&to_symbol=$to_currency" * _form_uri_tail(client, nothing, datatype)
            data = retry(_get_request, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))(uri)
            p = _parser(parser, datatype)
            return p(data)
        end
        export $fname
    end
end


text:
@enum PyGILState_STATE::Cint PyGILState_LOCKED = 0 PyGILState_UNLOCKED = 1

const Py_single_input = 256
const Py_file_input = 257
const Py_eval_input = 258
const Py_func_type_input = 345

const Py_LT = Cint(0)
const Py_LE = Cint(1)
const Py_EQ = Cint(2)
const Py_NE = Cint(3)
const Py_GT = Cint(4)
const Py_GE = Cint(5)

const Py_METH_VARARGS = 0x0001 # args are a tuple of arguments
const Py_METH_KEYWORDS = 0x0002  # two arguments: the varargs and the kwargs
const Py_METH_NOARGS = 0x0004  # no arguments (NULL argument pointer)
const Py_METH_O = 0x0008       # single argument (not wrapped in tuple)
const Py_METH_CLASS = 0x0010 # for class methods
const Py_METH_STATIC = 0x0020 # for static methods

const Py_T_SHORT = 0
const Py_T_INT = 1
const Py_T_LONG = 2
const Py_T_FLOAT = 3
const Py_T_DOUBLE = 4
const Py_T_STRING = 5
const Py_T_OBJECT = 6
const Py_T_CHAR = 7
const Py_T_BYTE = 8
const Py_T_UBYTE = 9
const Py_T_USHORT = 10
const Py_T_UINT = 11
const Py_T_ULONG = 12
const Py_T_STRING_INPLACE = 13
const Py_T_BOOL = 14
const Py_T_OBJECT_EX = 16
const Py_T_LONGLONG = 17 # added in Python 2.5
const Py_T_ULONGLONG = 18 # added in Python 2.5
const Py_T_PYSSIZET = 19 # added in Python 2.6
const Py_T_NONE = 20 # added in Python 3.0

const Py_READONLY = 1
const Py_READ_RESTRICTED = 2
const Py_WRITE_RESTRICTED = 4
const Py_RESTRICTED = (Py_READ_RESTRICTED | Py_WRITE_RESTRICTED)

const PyBUF_MAX_NDIM = 64

# Flags for getting buffers
const PyBUF_SIMPLE = 0x0
const PyBUF_WRITABLE = 0x0001
const PyBUF_WRITEABLE = PyBUF_WRITABLE
const PyBUF_FORMAT = 0x0004
const PyBUF_ND = 0x0008
const PyBUF_STRIDES = (0x0010 | PyBUF_ND)
const PyBUF_C_CONTIGUOUS = (0x0020 | PyBUF_STRIDES)
const PyBUF_F_CONTIGUOUS = (0x0040 | PyBUF_STRIDES)
const PyBUF_ANY_CONTIGUOUS = (0x0080 | PyBUF_STRIDES)
const PyBUF_INDIRECT = (0x0100 | PyBUF_STRIDES)

const PyBUF_CONTIG = (PyBUF_ND | PyBUF_WRITABLE)
const PyBUF_CONTIG_RO = (PyBUF_ND)

const PyBUF_STRIDED = (PyBUF_STRIDES | PyBUF_WRITABLE)
const PyBUF_STRIDED_RO = (PyBUF_STRIDES)

const PyBUF_RECORDS = (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
const PyBUF_RECORDS_RO = (PyBUF_STRIDES | PyBUF_FORMAT)

const PyBUF_FULL = (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
const PyBUF_FULL_RO = (PyBUF_INDIRECT | PyBUF_FORMAT)

const PyBUF_READ = 0x100
const PyBUF_WRITE = 0x200

# Python 2.7
const Py_TPFLAGS_HAVE_GETCHARBUFFER = (0x00000001 << 0)
const Py_TPFLAGS_HAVE_SEQUENCE_IN = (0x00000001 << 1)
const Py_TPFLAGS_GC = 0 # was sometimes (0x00000001<<2) in Python <= 2.1
const Py_TPFLAGS_HAVE_INPLACEOPS = (0x00000001 << 3)
const Py_TPFLAGS_CHECKTYPES = (0x00000001 << 4)
const Py_TPFLAGS_HAVE_RICHCOMPARE = (0x00000001 << 5)
const Py_TPFLAGS_HAVE_WEAKREFS = (0x00000001 << 6)
const Py_TPFLAGS_HAVE_ITER = (0x00000001 << 7)
const Py_TPFLAGS_HAVE_CLASS = (0x00000001 << 8)
const Py_TPFLAGS_HAVE_INDEX = (0x00000001 << 17)
const Py_TPFLAGS_HAVE_NEWBUFFER = (0x00000001 << 21)
const Py_TPFLAGS_STRING_SUBCLASS = (0x00000001 << 27)

# Python 3.0+ has only these:
const Py_TPFLAGS_HEAPTYPE = (0x00000001 << 9)
const Py_TPFLAGS_BASETYPE = (0x00000001 << 10)
const Py_TPFLAGS_READY = (0x00000001 << 12)
const Py_TPFLAGS_READYING = (0x00000001 << 13)
const Py_TPFLAGS_HAVE_GC = (0x00000001 << 14)
const Py_TPFLAGS_HAVE_VERSION_TAG = (0x00000001 << 18)
const Py_TPFLAGS_VALID_VERSION_TAG = (0x00000001 << 19)
const Py_TPFLAGS_IS_ABSTRACT = (0x00000001 << 20)
const Py_TPFLAGS_INT_SUBCLASS = (0x00000001 << 23)
const Py_TPFLAGS_LONG_SUBCLASS = (0x00000001 << 24)
const Py_TPFLAGS_LIST_SUBCLASS = (0x00000001 << 25)
const Py_TPFLAGS_TUPLE_SUBCLASS = (0x00000001 << 26)
const Py_TPFLAGS_BYTES_SUBCLASS = (0x00000001 << 27)
const Py_TPFLAGS_UNICODE_SUBCLASS = (0x00000001 << 28)
const Py_TPFLAGS_DICT_SUBCLASS = (0x00000001 << 29)
const Py_TPFLAGS_BASE_EXC_SUBCLASS = (0x00000001 << 30)
const Py_TPFLAGS_TYPE_SUBCLASS = (0x00000001 << 31)

# only use this if we have the stackless extension
const Py_TPFLAGS_HAVE_STACKLESS_EXTENSION = (0x00000003 << 15)

const Py_hash_t = Cssize_t
const Py_ssize_t = Cssize_t

@kwdef struct Py_complex
    real::Cdouble = 0.0
    imag::Cdouble = 0.0
end

@kwdef struct PyObject
    # assumes _PyObject_HEAD_EXTRA is empty
    refcnt::Py_ssize_t = 0
    type::Ptr{Cvoid} = C_NULL # really is Ptr{PyObject} or Ptr{PyTypeObject} but Julia 1.3 and below get the layout incorrect when circular types are involved
end

const PyPtr = Ptr{PyObject}
const PyNULL = PyPtr(0)

struct PyObjectRef
    ptr::PyPtr
end
ispyreftype(::Type{PyObjectRef}) = true
pyptr(o::PyObjectRef) = o.ptr
Base.unsafe_convert(::Type{PyPtr}, o::PyObjectRef) = o.ptr

@kwdef struct PyVarObject
    ob_base::PyObject = PyObject()
    size::Py_ssize_t = 0
end

@kwdef struct PyMethodDef
    name::Cstring = C_NULL
    meth::Ptr{Cvoid} = C_NULL
    flags::Cint = 0
    doc::Cstring = C_NULL
end

@kwdef struct PyGetSetDef
    name::Cstring = C_NULL
    get::Ptr{Cvoid} = C_NULL
    set::Ptr{Cvoid} = C_NULL
    doc::Cstring = C_NULL
    closure::Ptr{Cvoid} = C_NULL
end

@kwdef struct PyMemberDef
    name::Cstring = C_NULL
    typ::Cint = 0
    offset::Py_ssize_t = 0
    flags::Cint = 0
    doc::Cstring = C_NULL
end

@kwdef struct PyNumberMethods
    add::Ptr{Cvoid} = C_NULL # (o,o)->o
    subtract::Ptr{Cvoid} = C_NULL # (o,o)->o
    multiply::Ptr{Cvoid} = C_NULL # (o,o)->o
    remainder::Ptr{Cvoid} = C_NULL # (o,o)->o
    divmod::Ptr{Cvoid} = C_NULL # (o,o)->o
    power::Ptr{Cvoid} = C_NULL # (o,o,o)->o
    negative::Ptr{Cvoid} = C_NULL # (o)->o
    positive::Ptr{Cvoid} = C_NULL # (o)->o
    absolute::Ptr{Cvoid} = C_NULL # (o)->o
    bool::Ptr{Cvoid} = C_NULL # (o)->Cint
    invert::Ptr{Cvoid} = C_NULL # (o)->o
    lshift::Ptr{Cvoid} = C_NULL # (o,o)->o
    rshift::Ptr{Cvoid} = C_NULL # (o,o)->o
    and::Ptr{Cvoid} = C_NULL # (o,o)->o
    xor::Ptr{Cvoid} = C_NULL # (o,o)->o
    or::Ptr{Cvoid} = C_NULL # (o,o)->o
    int::Ptr{Cvoid} = C_NULL # (o)->o
    _reserved::Ptr{Cvoid} = C_NULL
    float::Ptr{Cvoid} = C_NULL # (o)->o
    inplace_add::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_subtract::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_multiply::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_remainder::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_power::Ptr{Cvoid} = C_NULL # (o,o,o)->o
    inplace_lshift::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_rshift::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_and::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_xor::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_or::Ptr{Cvoid} = C_NULL # (o,o)->o
    floordivide::Ptr{Cvoid} = C_NULL # (o,o)->o
    truedivide::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_floordivide::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_truedivide::Ptr{Cvoid} = C_NULL # (o,o)->o
    index::Ptr{Cvoid} = C_NULL # (o)->o
    matrixmultiply::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_matrixmultiply::Ptr{Cvoid} = C_NULL # (o,o)->o
end

@kwdef struct PySequenceMethods
    length::Ptr{Cvoid} = C_NULL # (o)->Py_ssize_t
    concat::Ptr{Cvoid} = C_NULL # (o,o)->o
    repeat::Ptr{Cvoid} = C_NULL # (o,Py_ssize_t)->o
    item::Ptr{Cvoid} = C_NULL # (o,Py_ssize_t)->o
    _was_item::Ptr{Cvoid} = C_NULL
    ass_item::Ptr{Cvoid} = C_NULL # (o,Py_ssize_t,o)->Cint
    _was_ass_slice::Ptr{Cvoid} = C_NULL
    contains::Ptr{Cvoid} = C_NULL # (o,o)->Cint
    inplace_concat::Ptr{Cvoid} = C_NULL # (o,o)->o
    inplace_repeat::Ptr{Cvoid} = C_NULL # (o,Py_ssize_t)->o
end

@kwdef struct PyMappingMethods
    length::Ptr{Cvoid} = C_NULL # (o)->Py_ssize_t
    subscript::Ptr{Cvoid} = C_NULL # (o,o)->o
    ass_subscript::Ptr{Cvoid} = C_NULL # (o,o,o)->Cint
end

@kwdef struct PyBufferProcs
    get::Ptr{Cvoid} = C_NULL # (o, Ptr{Py_buffer}, Cint) -> Cint
    release::Ptr{Cvoid} = C_NULL # (o, Ptr{Py_buffer}) -> Cvoid
end

@kwdef struct Py_buffer
    buf::Ptr{Cvoid} = C_NULL
    obj::Ptr{Cvoid} = C_NULL
    len::Py_ssize_t = 0
    itemsize::Py_ssize_t = 0
    readonly::Cint = 0
    ndim::Cint = 0
    format::Cstring = C_NULL
    shape::Ptr{Py_ssize_t} = C_NULL
    strides::Ptr{Py_ssize_t} = C_NULL
    suboffsets::Ptr{Py_ssize_t} = C_NULL
    internal::Ptr{Cvoid} = C_NULL
end

@kwdef struct PyMemoryViewObject
    ob_base::PyVarObject = PyVarObject()
    mbuf::PyPtr = PyNULL
    hash::Py_hash_t = 0
    flags::Cint = 0
    exports::Py_ssize_t = 0
    view::Py_buffer = Py_buffer()
    weakreflist::PyPtr = PyNULL
end

@kwdef struct PyTypeObject
    ob_base::PyVarObject = PyVarObject()
    name::Cstring = C_NULL

    basicsize::Py_ssize_t = 0
    itemsize::Py_ssize_t = 0

    dealloc::Ptr{Cvoid} = C_NULL
    vectorcall_offset::Py_ssize_t = 0
    getattr::Ptr{Cvoid} = C_NULL
    setattr::Ptr{Cvoid} = C_NULL
    as_async::Ptr{Cvoid} = C_NULL
    repr::Ptr{Cvoid} = C_NULL

    as_number::Ptr{PyNumberMethods} = C_NULL
    as_sequence::Ptr{PySequenceMethods} = C_NULL
    as_mapping::Ptr{PyMappingMethods} = C_NULL

    hash::Ptr{Cvoid} = C_NULL
    call::Ptr{Cvoid} = C_NULL
    str::Ptr{Cvoid} = C_NULL
    getattro::Ptr{Cvoid} = C_NULL
    setattro::Ptr{Cvoid} = C_NULL

    as_buffer::Ptr{PyBufferProcs} = C_NULL

    flags::Culong = 0

    doc::Cstring = C_NULL

    traverse::Ptr{Cvoid} = C_NULL

    clear::Ptr{Cvoid} = C_NULL

    richcompare::Ptr{Cvoid} = C_NULL

    weaklistoffset::Py_ssize_t = 0

    iter::Ptr{Cvoid} = C_NULL
    iternext::Ptr{Cvoid} = C_NULL

    methods::Ptr{PyMethodDef} = C_NULL
    members::Ptr{PyMemberDef} = C_NULL
    getset::Ptr{PyGetSetDef} = C_NULL
    base::PyPtr = C_NULL
    dict::PyPtr = C_NULL
    descr_get::Ptr{Cvoid} = C_NULL
    descr_set::Ptr{Cvoid} = C_NULL
    dictoffset::Py_ssize_t = 0
    init::Ptr{Cvoid} = C_NULL
    alloc::Ptr{Cvoid} = C_NULL
    new::Ptr{Cvoid} = C_NULL
    free::Ptr{Cvoid} = C_NULL
    is_gc::Ptr{Cvoid} = C_NULL
    bases::PyPtr = C_NULL
    mro::PyPtr = C_NULL
    cache::PyPtr = C_NULL
    subclasses::PyPtr = C_NULL
    weaklist::PyPtr = C_NULL
    del::Ptr{Cvoid} = C_NULL

    version_tag::Cuint = 0

    finalize::Ptr{Cvoid} = C_NULL
    vectorcall::Ptr{Cvoid} = C_NULL

end

const PyTypePtr = Ptr{PyTypeObject}

@kwdef struct PySimpleObject{T}
    ob_base::PyObject = PyObject()
    value::T
end

@kwdef struct PyJuliaValueObject
    ob_base::PyObject = PyObject()
    value::Int = 0
    weaklist::PyPtr = C_NULL
end


text:
"""
    CountTransformer()

Convert a collection of raw documents to matrix representing a bag-of-words structure from
word counts. Essentially, a bag-of-words approach to representing documents in a matrix is
comprised of a count of every word in the document corpus/collection for every document.
This is a simple but often quite powerful way of representing documents as vectors. The
resulting representation is a matrix with rows representing every document in the corpus
and columns representing every word in the corpus. The value for each cell is the raw count
of a particular word in a particular document.

Similarly to the `TfidfTransformer`, the vocabulary considered can be restricted
to words occuring in a maximum or minimum portion of documents.
The parameters `max_doc_freq` and `min_doc_freq` restrict the vocabulary
that the transformer will consider. `max_doc_freq` indicates that terms in only
up to the specified percentage of documents will be considered. For example, if
`max_doc_freq` is set to 0.9, terms that are in more than 90% of documents
will be removed. Similarly, the `min_doc_freq` parameter restricts terms in the
other direction. A value of 0.01 means that only terms that are at least in 1% of
documents will be included.
"""
mutable struct CountTransformer <: AbstractTextTransformer
    max_doc_freq::Float64
    min_doc_freq::Float64
end

function CountTransformer(; max_doc_freq::Float64 = 1.0, min_doc_freq::Float64 = 0.0)
    transformer = CountTransformer(max_doc_freq, min_doc_freq)
    message = MMI.clean!(transformer)
    isempty(message) || @warn message
    return transformer
end

struct CountTransformerResult
    vocab::Vector{String}
end

function _fit(transformer::CountTransformer, verbosity::Int, X::Corpus)
    # process corpus vocab
    update_lexicon!(X)

    # calculate min and max doc freq limits
    if transformer.max_doc_freq < 1 || transformer.min_doc_freq > 0
        # we need to build out the DTM
        dtm_matrix = build_dtm(X)
        n = size(dtm_matrix.dtm, 2) # docs are columns
        high = round(Int, transformer.max_doc_freq * n)
        low = round(Int, transformer.min_doc_freq * n)
        _, vocab = limit_features(dtm_matrix, high, low)
    else
        vocab = sort(collect(keys(lexicon(X))))
    end

    # prepare result
    fitresult = CountTransformerResult(vocab)
    cache = nothing

    return fitresult, cache, NamedTuple()
end

function _transform(::CountTransformer,
                    result::CountTransformerResult,
                    v::Corpus)
    dtm_matrix = build_dtm(v, result.vocab)

    # here we return the `adjoint` of our sparse matrix to conform to
    # the `n x p` dimensions throughout MLJ
    return adjoint(dtm_matrix.dtm)
end

# for returning user-friendly form of the learned parameters:
function MMI.fitted_params(::CountTransformer, fitresult::CountTransformerResult)
    vocab = fitresult.vocab
    return (vocab = vocab,)
end

## META DATA

MMI.metadata_pkg(CountTransformer,
             name="$PKG",
             uuid="7876af07-990d-54b4-ab0e-23690620f79a",
             url="https://github.com/JuliaAI/MLJText.jl",
             is_pure_julia=true,
             license="MIT",
             is_wrapper=false
)

MMI.metadata_model(CountTransformer,
               input_scitype = Union{
                   AbstractVector{<:AbstractVector{STB.Textual}},
                   AbstractVector{<:STB.Multiset{<:ScientificNGram}},
                   AbstractVector{<:STB.Multiset{STB.Textual}}
                   },
               output_scitype = AbstractMatrix{STB.Continuous},
               docstring = "Build Bag-of-Words matrix from word counts for corpus of documents",
               path = "MLJText.CountTransformer"
               )


text:
abstract type SoaveAlphaModel <: AlphaModel end

struct SoaveAlphaParam <: EoSParam
    acentricfactor::SingleParam{Float64}
end

@newmodelsimple SoaveAlpha SoaveAlphaModel SoaveAlphaParam

export SoaveAlpha
function SoaveAlpha(components::Vector{String}; userlocations::Vector{String}=String[], verbose::Bool=false)
    params = getparams(components, ["properties/critical.csv"]; userlocations=userlocations, verbose=verbose)
    acentricfactor = SingleParam(params["w"],"acentric factor")
    packagedparams = SoaveAlphaParam(acentricfactor)
    model = SoaveAlpha(packagedparams, verbose=verbose)
    return model
end

function α_function(model::CubicModel,V,T,z,alpha_model::SoaveAlphaModel)
    Tc = model.params.Tc.values
    ω  = alpha_model.params.acentricfactor.values
    α = zeros(typeof(T),length(Tc))
    for i in @comps
        ωi = ω[i]
        Tr = T/Tc[i]
        m = evalpoly(ωi,(0.480,1.547,-0.176))
        α[i] = (1+m*(1-√(Tr)))^2
    end
    return α
end


text:
using Plots
include("Target.jl")

samp = 1000
n = 15         # Number of student profiles. Must be ≤ m here.
m = 20         # Number of schools.
cap = 20      # For discrete form (unused).

CADA_disutil, STB_disutil, strat_disutil = target_doer(n, m, samp)
# CADA_disutil, STB_disutil, strat_disutil = target_doer_discrete(m, cap, samp)

CADA_improvement = STB_disutil .- CADA_disutil
println(minimum(CADA_improvement))

# a, b = minimum([minimum(o) for o in [CADA_disutil, STB_disutil, strat_disutil]]),
#        maximum([maximum(o) for o in [CADA_disutil, STB_disutil, strat_disutil]])

q = plot([strat_disutil, [0, 5]],
         [STB_disutil, [0, 5]],
        # [CADA_disutil, [a, b]],
         seriestype=[:scatter :line],
         color=[:olivedrab :gray],
         markersize=vcat(sqrt.(max.(0.2 .+ CADA_improvement, 0.2)), 0) .* 5,
         markershape=:circle,
         msw=0,
         ma=[.5 0],
         ls=[:auto :dash],
         title="Choice-augmented deferred acceptance: "*
               "\n$n profiles, $m schools, $samp samples",
         titlefontsize=11,
         xlabel="disutility when strategizing",
         ylabel="disutility under STB",
         legend=false,
         size=(600,600),
         xlims=(-0.05,3.1), ylims=(-0.05,3.1))

annotate!([(3., 0.25, Plots.text("Marker size: improvement"*
                                 "\nbetween CADA and DA-STB.", 8, :right))])

display(q)

# savefig(q, string("examples/target/plot.pdf"))
# savefig(q, string("examples/target/plot.png"))

max_stars_repo_name: maxkapur/DeferredAcceptance

max_issues_repo_name: maxkapur/DeferredAcceptance

max_forks_repo_name: maxkapur/DeferredAcceptance


text:
function (x, y, z, μ)
    begin
        (SymbolicUtils.Code.create_array)(Array, nothing, Val{2}(), Val{(3, 3)}(), (+)((+)(1, (*)((*)(-3//2, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5), (+)((*)(-1//1, x), (*)(-1//1, μ)), (+)((*)(2, x), (*)(2, μ))), (*)((+)(1, (*)(-1, μ)))), (*)(-1//1, μ, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 3)), (*)(-1//1, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 3), (+)(1, (*)(-1, μ)))), (+)((*)(3//4, μ, (^)((+)(-2, (*)(2, x), (*)(2, μ)), 2), (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5)))), (+)((*)((*)(3//2, y, μ, (+)(-2, (*)(2, x), (*)(2, μ))), (*)((^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5))), (*)((*)(-3//1, y, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5), (+)((*)(-1//1, x), (*)(-1//1, μ))), (*)((+)(1, (*)(-1, μ))))), (+)((*)((*)(3//2, z, μ, (+)(-2, (*)(2, x), (*)(2, μ))), (*)((^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5))), (*)((*)(-3//1, z, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5), (+)((*)(-1//1, x), (*)(-1//1, μ))), (*)((+)(1, (*)(-1, μ))))), (+)((*)((*)(3//2, y, μ, (+)(-2, (*)(2, x), (*)(2, μ))), (*)((^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5))), (*)((*)(-3//1, y, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5), (+)((*)(-1//1, x), (*)(-1//1, μ))), (*)((+)(1, (*)(-1, μ))))), (+)((+)(1, (*)(-1//1, μ, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 3)), (*)(-1//1, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 3), (+)(1, (*)(-1, μ))), (*)(3//1, μ, (^)(y, 2), (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5))), (+)((*)(3//1, (^)(y, 2), (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5), (+)(1, (*)(-1, μ))))), (+)((*)((*)(3//1, y, z, μ), (*)((^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5))), (*)((*)(3//1, y, z, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5)), (*)((+)(1, (*)(-1, μ))))), (+)((*)((*)(3//2, z, μ, (+)(-2, (*)(2, x), (*)(2, μ))), (*)((^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5))), (*)((*)(-3//1, z, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5), (+)((*)(-1//1, x), (*)(-1//1, μ))), (*)((+)(1, (*)(-1, μ))))), (+)((*)((*)(3//1, y, z, μ), (*)((^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5))), (*)((*)(3//1, y, z, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5)), (*)((+)(1, (*)(-1, μ))))), (+)((*)(-1//1, μ, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 3)), (*)(-1//1, (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 3), (+)(1, (*)(-1, μ))), (*)(3//1, μ, (^)(z, 2), (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(-1, x, μ), 2)))), 5)), (*)(3//1, (^)(z, 2), (^)((inv)((sqrt)((+)((^)(y, 2), (^)(z, 2), (^)((+)(x, μ), 2)))), 5), (+)(1, (*)(-1, μ)))))
    end
end


text:
using Iterators, FileIO, Colors
using Visualize, GeometryTypes, GtkReactive, ModernGL

using Visualize.GLRasterization
using Visualize.GLRasterization: swapbuffers!, destroy!, GtkWindow, GtkParent, OpenGLVersion, GLCanvas, make_context_current
using Visualize: VertexN, Light, Shading, vert_mesh, frag_mesh, Visible, NativeWindow
using Visualize: Resolution, View, ProjectionView, EyePosition, Projection, Name
using Visualize: VertexN, Light, MeshUniforms, Shading, vert_mesh, frag_mesh
using Visualize: Model, Color, ShadingFunction, Debugging, Canvas, add!
using FieldTraits: Partial, default, on

parent = Gtk.Window("Test", 800, 600, true, true)
box = Gtk.Box(:v)
tb = textbox(String)
sl = GtkReactive.slider(linspace(0.0, 20.0, 100))
mesh_color = map(sl) do val
    RGBA{Float32}(val, 0,0,1)
end
push!(box, tb)
push!(box, sl)

push!(parent, box)
window = GLRasterization.GtkWindow(OpenGLVersion => v"3.3.0", GtkParent => box)
Gtk.setproperty!(box, :expand, window[NativeWindow], true)

Gtk.showall(parent)
# for event in Visualize.NativeWindowEvents
#     add!(window, event)
# end
# add!(window, Mouse.Drag)
add!(window, Mouse.Buttons)
add!(window, Mouse.Position)
add!(window, Mouse.Drag)

cam = PerspectiveCamera(
    TranslationSpeed => 1f0,
    LookAt => Vec3f0(0),
    EyePosition => Vec3f0(6, 6, 8),
    Rotation => Vec3f0(0),
    Area => window[Area],
    RotationSpeed => 0.1f0
)

add!(cam, Translation, window,
    Mouse.right, Set(Keyboard.Button[])
)
add!(cam, Rotation, window,
    Mouse.left, Set(Keyboard.Button[])
)
add!(cam, Projection, View)
add!(cam, EyePosition, LookAt)

make_context_current(window[NativeWindow])
on(cam, ProjectionView) do pv
    Gtk.queue_render(window[NativeWindow])
end

catmesh = normalmesh(load(Pkg.dir("GLVisualize", "assets", "cat.obj")))
catmesh = Base.view(
    reinterpret(Visualize.VertexN, catmesh.parent), catmesh.indexes[1]
)
vbo = VertexArray(catmesh);

args = MeshUniforms(
    ShadingFunction => (V, N, L, color, shading, light) -> return L
)

canvas = window[Canvas];
for field in FieldTraits.Fields(eltype(canvas))
    if haskey(cam, field)
        FieldTraits.link!(field, cam => canvas)
    end
end
light = Light(
    Vec3f0(10),
    Vec3f0(0.0),
    Vec3f0(0.9),
    1.0f0,
    Vec3f0(0.2),
    1.0f0
)
shading = Shading(
    Vec3f0(0.0),
    Vec3f0(0.3),
    8.0f0
)
uniforms = (canvas, UniformBuffer(light), UniformBuffer(shading), UniformBuffer(args));

draw_cat = GLRasterizer(
    vbo,
    uniforms,
    vert_mesh, Visualize.frag_mesh
)

function gtk_render(gl_area, gdk_context)
    global draw_cat, uniforms, args, vbo, window
    glEnable(GL_DEPTH_TEST)
    glDepthMask(GL_TRUE)
    glDepthFunc(GL_LEQUAL)
    glDisable(GL_CULL_FACE)
    GLAbstraction.enabletransparency()
    glClearColor(1,1,1,1)
    glViewport(0, 0, widths(window[Area])...)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    draw_cat(vbo, uniforms)
    glFlush()
    return false
end

Gtk.signal_connect(gtk_render, window[NativeWindow], "render")
cam[View] = eye(Mat4f0)
# signal_connect(parent, :destroy) do widget
#     Gtk.gtk_quit()
# end
# Gtk.gtk_main()


text:
import Baysor as B

include("../test/runtests.jl")

B.run_cli(["--help"]);
B.run_cli(["run", "--help"]);

max_stars_repo_name: repushko/Baysor

max_issues_repo_name: repushko/Baysor

max_forks_repo_name: repushko/Baysor


text:
struct KLocalIdentity{T,H} <: AbsLinearOp{T}
    hilb::H
end

KLocalIdentity(T::Type, hilb::AbstractHilbert) =
    KLocalIdentity{T,typeof(hilb)}(hilb)

KLocalIdentity(hilb) = KLocalIdentity(ComplexF64, hilb)

QuantumOpticsBase.basis(op::KLocalIdentity) = op.hilb

Base.copy(op::KLocalIdentity{T,H}) where {T,H} = KLocalIdentity{T,H}(basis(op))
duplicate(op::KLocalIdentity) = copy(op)

conn_type(top::Type{KLocalIdentity{T,H}}) where {T,H} =
    OpConnectionIdentity{Vector{Int}, Vector{T}}