text:
const CPC = Ptr{Cvoid}
const CPCType = Cstring

mutable struct PC{T}
    ptr::Ptr{Cvoid}
    comm::MPI.Comm
end

Base.cconvert(::Type{CPC}, obj::PC) = obj.ptr
Base.unsafe_convert(::Type{Ptr{CPC}}, obj::PC) =
    convert(Ptr{CPC}, pointer_from_objref(obj))

scalartype(::PC{T}) where {T} = T

@for_libpetsc begin

    function PC{$PetscScalar}(comm::MPI.Comm)
        pc = PC{$PetscScalar}(C_NULL, comm)
        @chk ccall((:PCCreate, $libpetsc), PetscErrorCode, (MPI.MPI_Comm, Ptr{CPC}), comm, pc)
        finalizer(destroy, pc)
        return pc
    end

    function PC(ksp::KSP{$PetscScalar})
        pc = PC{$PetscScalar}(C_NULL, ksp.comm)
        @chk ccall((:KSPGetPC, $libpetsc), PetscErrorCode, (CKSP, Ptr{CPC}), ksp, pc)
        incref(pc) # need to manually increment the reference counter
        finalizer(destroy, pc)
        return pc
    end

    function destroy(pc::PC{$PetscScalar})
        finalized($PetscScalar) ||
        @chk ccall((:PCDestroy, $libpetsc), PetscErrorCode, (Ptr{CPC},), pc)
        return nothing
    end

    function settype!(pc::PC{$PetscScalar}, pctype::String)
        @chk ccall((:PCSetType, $libpetsc), PetscErrorCode, (CPC, Cstring), pc, pctype)
        return nothing
    end

    function setpc!(ksp::KSP{$PetscScalar}, pc::PC{$PetscScalar})
        @chk ccall((:KSPSetPC, $libpetsc), PetscErrorCode, (CKSP, CPC), ksp, pc)
        return nothing
    end

    function gettype(pc::PC{$PetscScalar})
        t_r = Ref{CPCType}()
        @chk ccall((:PCGetType, $libpetsc), PetscErrorCode, (CPC, Ptr{CPCType}),  pc, t_r)
        return unsafe_string(t_r[])
    end

    function view(pc::PC{$PetscScalar}, viewer::Viewer{$PetscScalar}=ViewerStdout{$PetscScalar}(pc.comm))
        @chk ccall((:PCView, $libpetsc), PetscErrorCode,
                    (CPC, CPetscViewer),
                pc, viewer);
        return nothing
    end

end

Base.show(io::IO, pc::PC) = _show(io, pc)


text:
# Exercise 1

using LinearAlgebra
using StaticArrays
using BenchmarkTools

N = 3
A = rand(N, N)
x = rand(N)

@btime $A * $x  # the $ in front of variable names is sometimes important
@btime inv($A)

# Benchmark

A_s = @SMatrix rand(N,N)
x_s =  @SVector rand(N)

@btime  $A_s * $x_s
@btime inv($A_s);

# very fast matrix multiplication, use $ and denote as static vectors
@btime $A_s * $x_s
@show supertypes(typeof(A_s))
@show supertypes(typeof(A));

# Exercise 2

Σ = [0.4  0.3;
     0.3  0.45]
G = I
R = 0.5 * Σ

gain(Σ, G, R) = Σ * G' * inv(G * Σ * G' + R)
@btime gain($Σ, $G, $R)

# Benchmark

Σ_s = @SMatrix [0.4  0.3; 0.3  0.45]
R_s = 0.5 * Σ_s

@show typeof(R) #static array, too

@btime gain($Σ_s, $G, $R_s);

# Exercise 3

using Polynomials

p = Polynomial([2, -5, 2], :x)  # :x just gives a symbol for display

@show p
@show typeof(p)
p′ = derivative(p)   # gives the derivative of p, another polynomial
@show p(0.1), p′(0.1)  # call like a function
@show roots(p);   # find roots such that p(x) = 0

# plot p and p'

r = range(-2.0, 2.0, length = 20)

p_r = p.(r)
p′_r = p′.(r)

plot(r[1:end-1],p′_r[1:end-1],label="Dp(x)")
plot!(r,p_r,label="p(x)")

# Exercise 4

function newtonsmethod(p::Polynomial, x_0; tolerance = 1E-7, maxiter = 100)

    p′ = derivative(p)

    #initialise loop
    iter = 1
    normdiff = Inf
    x_old = x_0

    while normdiff > tolerance && iter < maxiter

        x_new = x_old - p(x_old)/ p′(x_old)
        normdiff = norm(x_new - x_old)

        iter += 1 #continuation
        x_old = x_new
    end
    return (root = x_old, normdiff = normdiff, iter = iter )
end

# Compute roots

p = Polynomial([2, -5, 2], :x)  # :x just gives a symbol for display

@show newtonsmethod(p, 5);   # find roots such that p(x) = 0
@show roots(p)
@btime newtonsmethod(p, 5);
@btime roots(p);

# Exercise 5
function trapezoidal(f::AbstractArray{Float64,1}, x::AbstractArray{Float64,1})
    sol = similar(x)
    del = diff(x)
    for i in 2:length(x)
        sol[i] = (f_x[i]+f_x[i-1])/2*del[i-1]
    end
    return sum(sol)
end

x = range(0.0,1.0,length=9)
f(x) = x^2
f_x = f.(x)

int = trapezoidal(f_x,x)

function trapezoidal2(f::AbstractArray{Float64}, x::AbstractRange{Float64})
    sol = similar(x)
    del = step(x)
    for i in 2:length(x)
        sol[i] = (f_x[i]+ f_x[i-1])/2*del
    end
    return sum(sol)
end

x = range(0.0,1.0,length=1100)
f(x) = x^2
f_x = f.(x)

integral = trapezoidal2(f_x,x)

f(x) = x^3
x̄ = 1.0
x̲ = 0.0
N = 1100;

function trapezoidal3(f, x̲::Real , x̄::Real , N::Int64)
    x = range(x̲, x̄, length = N)
    f_x = f.(x)

    #implementation the same as trapezodal2
    sol = similar(x)
    del = step(x)
    for i in 2:length(x)
        sol[i] = (f_x[i]+ f_x[i-1])/2*del
    end
    return sum(sol)
end

integral = trapezoidal3(f ,x̲ , x̄ , N)

# Exercise 6

using ForwardDiff

function f(a, b; N::Int64 = 50)
    r = range(a, b, length=N) # one
return mean(r)
end

Df(x) = ForwardDiff.derivative(y -> f(0.0, y), x)

@show f(0.0, 3.0)
@show f(0.0, 3.1)

Df(3.0)

function f(a, b; N::Int64 = 50)
    r = range(a, b, length=N) # one
return mean(r)
end

ext: jl

max_stars_repo_name: shanemcmiken/quantecon-notebooks-julia

max_issues_repo_name: shanemcmiken/quantecon-notebooks-julia

max_forks_repo_name: shanemcmiken/quantecon-notebooks-julia


text:
# Test corr.jl
#
# Many test cases are migrated from test/01.jl in the old version
# The reference results are generated from R.
#

using Stats
using Base.Test

# random data for testing

x = [-2.133252557240862    -.7445937365828654;
	   .1775816414485478   -.5834801838041446;
	  -.6264517920318317   -.68444205333293;
	  -.8809042583216906    .9071671734302398;
	   .09251017186697393 -1.0404476733379926;
	  -.9271887119115569   -.620728578941385;
	  3.355819743178915    -.8325051361909978;
	  -.2834039258495755   -.22394811874731657;
	   .5354280026977677    .7481337671592626;
	   .39182285417742585   .3085762550821047]

x1 = x[:, 1]
x2 = x[:, 2]

# autocov & autocorr

@test_approx_eq autocov([1:5]) [2.0, 0.8, -0.2, -0.8, -0.8]
@test_approx_eq autocor([1, 2, 3, 4, 5]) [1.0, 0.4, -0.1, -0.4, -0.4]

racovx1 =  [1.839214242630635709475,
           -0.406784553146903871124,
            0.421772254824993531042,
            0.035874943792884653182,
           -0.255679775928512320604,
            0.231154400105831353551,
           -0.787016960267425180753,
            0.039909287349160660341,
           -0.110149697877911914579,
           -0.088687020167434751916]

@test_approx_eq autocov(x1) racovx1
@test_approx_eq autocov(x) [autocov(x1) autocov(x2)]

racorx1 = [0.999999999999999888978,
          -0.221173011668873431557,
           0.229321981664153962122,
           0.019505581764945757045,
          -0.139015765538446717242,
           0.125681062460244019618,
          -0.427909344123907742219,
           0.021699096507690283225,
          -0.059889541590524189574,
          -0.048220059475281865091]

@test_approx_eq autocor(x1) racorx1
@test_approx_eq autocor(x) [autocor(x1) autocor(x2)]

# crosscov & crosscor

rcov0 = [0.320000000000000006661,
        -0.319999999999999951150,
         0.080000000000000029421,
        -0.479999999999999982236,
         0.000000000000000000000,
         0.479999999999999982236,
        -0.080000000000000029421,
         0.319999999999999951150,
        -0.320000000000000006661]

@test_approx_eq crosscov([1, 2, 3, 4, 5], [1, -1, 1, -1, 1]) rcov0
@test_approx_eq crosscov([1:5], [1:5]) [-0.8, -0.8, -0.2, 0.8, 2.0, 0.8, -0.2, -0.8, -0.8]

c11 = crosscov(x1, x1)
c12 = crosscov(x1, x2)
c21 = crosscov(x2, x1)
c22 = crosscov(x2, x2)

@test_approx_eq crosscov(x,  x1) [c11 c21]
@test_approx_eq crosscov(x1, x)  [c11 c12]
@test_approx_eq crosscov(x,  x)  cat(3, [c11 c21], [c12 c22])

rcor0 = [0.230940107675850,
        -0.230940107675850,
         0.057735026918963,
        -0.346410161513775,
         0.000000000000000,
         0.346410161513775,
        -0.057735026918963,
         0.230940107675850,
        -0.230940107675850]

@test_approx_eq crosscor([1, 2, 3, 4, 5], [1, -1, 1, -1, 1]) rcor0
@test_approx_eq crosscor([1:5], [1:5]) [-0.4, -0.4, -0.1, 0.4, 1.0, 0.4, -0.1, -0.4, -0.4]

c11 = crosscor(x1, x1)
c12 = crosscor(x1, x2)
c21 = crosscor(x2, x1)
c22 = crosscor(x2, x2)

@test_approx_eq crosscor(x,  x1) [c11 c21]
@test_approx_eq crosscor(x1, x)  [c11 c12]
@test_approx_eq crosscor(x,  x)  cat(3, [c11 c21], [c12 c22])

## pacf

rpacfr =  [-0.218158122381419,
            0.195015316828711,
            0.144315804606139,
           -0.199791229449779]

@test_approx_eq pacf(x[:,1], 1:4) rpacfr

rpacfy = [-0.221173011668873,
           0.189683314308021,
           0.111857020733719,
          -0.175020669835420]

@test_approx_eq pacf(x[:,1], 1:4, method=:yulewalker) rpacfy


text:
using MyExample
using Test

@test my_f(1,2) == 4

@testset "MyExample.jl" begin
    # Write your tests here.
    @test my_f(1,2) == 4
    @test my_f(2,1) == 5
end


text:
#=
This file is auto-generated. Do not edit.
=#
"""
    mutable struct AVRTypeII <: AVR
        K0::Float64
        T1::Float64
        T2::Float64
        T3::Float64
        T4::Float64
        Te::Float64
        Tr::Float64
        Va_lim::NamedTuple{(:min, :max), Tuple{Float64, Float64}}
        Ae::Float64
        Be::Float64
        V_ref::Float64
        ext::Dict{String, Any}
        states::Vector{Symbol}
        n_states::Int
        states_types::Vector{StateTypes.StateType}
        internal::InfrastructureSystemsInternal
    end

Parameters of an Automatic Voltage Regulator Type II -  Typical static exciter model

# Arguments
- `K0::Float64`: Regulator Gain, validation range: `(0, nothing)`
- `T1::Float64`: First Pole in s, validation range: `(0, nothing)`
- `T2::Float64`: First zero in s, validation range: `(0, nothing)`
- `T3::Float64`: First Pole in s, validation range: `(0, nothing)`
- `T4::Float64`: First zero in s, validation range: `(0, nothing)`
- `Te::Float64`: Field Circuit Time Constant in s, validation range: `(0, nothing)`
- `Tr::Float64`: Voltage Measurement Time Constant in s, validation range: `(0, nothing)`
- `Va_lim::NamedTuple{(:min, :max), Tuple{Float64, Float64}}`: Limits for pi controler `(Va_min, Va_max)`
- `Ae::Float64`: 1st ceiling coefficient, validation range: `(0, nothing)`
- `Be::Float64`: 2nd ceiling coefficient, validation range: `(0, nothing)`
- `V_ref::Float64`: Reference Voltage Set-point, validation range: `(0, nothing)`
- `ext::Dict{String, Any}`
- `states::Vector{Symbol}`: The states are:
	Vf: Voltage field,
	Vr1: First Lead-Lag state,
	Vr2: Second lead-lag state,
	Vm: Measured voltage
- `n_states::Int`: AVR Type II has 4 states
- `states_types::Vector{StateTypes.StateType}`: AVR Type II has 4 differential states
- `internal::InfrastructureSystemsInternal`: power system internal reference, do not modify
"""
mutable struct AVRTypeII <: AVR
    "Regulator Gain"
    K0::Float64
    "First Pole in s"
    T1::Float64
    "First zero in s"
    T2::Float64
    "First Pole in s"
    T3::Float64
    "First zero in s"
    T4::Float64
    "Field Circuit Time Constant in s"
    Te::Float64
    "Voltage Measurement Time Constant in s"
    Tr::Float64
    "Limits for pi controler `(Va_min, Va_max)`"
    Va_lim::NamedTuple{(:min, :max), Tuple{Float64, Float64}}
    "1st ceiling coefficient"
    Ae::Float64
    "2nd ceiling coefficient"
    Be::Float64
    "Reference Voltage Set-point"
    V_ref::Float64
    ext::Dict{String, Any}
    "The states are:
	Vf: Voltage field,
	Vr1: First Lead-Lag state,
	Vr2: Second lead-lag state,
	Vm: Measured voltage"
    states::Vector{Symbol}
    "AVR Type II has 4 states"
    n_states::Int
    "AVR Type II has 4 differential states"
    states_types::Vector{StateTypes.StateType}
    "power system internal reference, do not modify"
    internal::InfrastructureSystemsInternal
end

function AVRTypeII(K0, T1, T2, T3, T4, Te, Tr, Va_lim, Ae, Be, V_ref=1.0, ext=Dict{String, Any}(), )
    AVRTypeII(K0, T1, T2, T3, T4, Te, Tr, Va_lim, Ae, Be, V_ref, ext, [:Vf, :Vr1, :Vr2, :Vm], 4, [StateTypes.Differential, StateTypes.Differential, StateTypes.Differential, StateTypes.Differential], InfrastructureSystemsInternal(), )
end

function AVRTypeII(; K0, T1, T2, T3, T4, Te, Tr, Va_lim, Ae, Be, V_ref=1.0, ext=Dict{String, Any}(), states=[:Vf, :Vr1, :Vr2, :Vm], n_states=4, states_types=[StateTypes.Differential, StateTypes.Differential, StateTypes.Differential, StateTypes.Differential], internal=InfrastructureSystemsInternal(), )
    AVRTypeII(K0, T1, T2, T3, T4, Te, Tr, Va_lim, Ae, Be, V_ref, ext, states, n_states, states_types, internal, )
end

# Constructor for demo purposes; non-functional.
function AVRTypeII(::Nothing)
    AVRTypeII(;
        K0=0,
        T1=0,
        T2=0,
        T3=0,
        T4=0,
        Te=0,
        Tr=0,
        Va_lim=(min=0.0, max=0.0),
        Ae=0,
        Be=0,
        V_ref=0,
        ext=Dict{String, Any}(),
    )
end

"""Get [`AVRTypeII`](@ref) `K0`."""
get_K0(value::AVRTypeII) = value.K0
"""Get [`AVRTypeII`](@ref) `T1`."""
get_T1(value::AVRTypeII) = value.T1
"""Get [`AVRTypeII`](@ref) `T2`."""
get_T2(value::AVRTypeII) = value.T2
"""Get [`AVRTypeII`](@ref) `T3`."""
get_T3(value::AVRTypeII) = value.T3
"""Get [`AVRTypeII`](@ref) `T4`."""
get_T4(value::AVRTypeII) = value.T4
"""Get [`AVRTypeII`](@ref) `Te`."""
get_Te(value::AVRTypeII) = value.Te
"""Get [`AVRTypeII`](@ref) `Tr`."""
get_Tr(value::AVRTypeII) = value.Tr
"""Get [`AVRTypeII`](@ref) `Va_lim`."""
get_Va_lim(value::AVRTypeII) = value.Va_lim
"""Get [`AVRTypeII`](@ref) `Ae`."""
get_Ae(value::AVRTypeII) = value.Ae
"""Get [`AVRTypeII`](@ref) `Be`."""
get_Be(value::AVRTypeII) = value.Be
"""Get [`AVRTypeII`](@ref) `V_ref`."""
get_V_ref(value::AVRTypeII) = value.V_ref
"""Get [`AVRTypeII`](@ref) `ext`."""
get_ext(value::AVRTypeII) = value.ext
"""Get [`AVRTypeII`](@ref) `states`."""
get_states(value::AVRTypeII) = value.states
"""Get [`AVRTypeII`](@ref) `n_states`."""
get_n_states(value::AVRTypeII) = value.n_states
"""Get [`AVRTypeII`](@ref) `states_types`."""
get_states_types(value::AVRTypeII) = value.states_types
"""Get [`AVRTypeII`](@ref) `internal`."""
get_internal(value::AVRTypeII) = value.internal

"""Set [`AVRTypeII`](@ref) `K0`."""
set_K0!(value::AVRTypeII, val) = value.K0 = val
"""Set [`AVRTypeII`](@ref) `T1`."""
set_T1!(value::AVRTypeII, val) = value.T1 = val
"""Set [`AVRTypeII`](@ref) `T2`."""
set_T2!(value::AVRTypeII, val) = value.T2 = val
"""Set [`AVRTypeII`](@ref) `T3`."""
set_T3!(value::AVRTypeII, val) = value.T3 = val
"""Set [`AVRTypeII`](@ref) `T4`."""
set_T4!(value::AVRTypeII, val) = value.T4 = val
"""Set [`AVRTypeII`](@ref) `Te`."""
set_Te!(value::AVRTypeII, val) = value.Te = val
"""Set [`AVRTypeII`](@ref) `Tr`."""
set_Tr!(value::AVRTypeII, val) = value.Tr = val
"""Set [`AVRTypeII`](@ref) `Va_lim`."""
set_Va_lim!(value::AVRTypeII, val) = value.Va_lim = val
"""Set [`AVRTypeII`](@ref) `Ae`."""
set_Ae!(value::AVRTypeII, val) = value.Ae = val
"""Set [`AVRTypeII`](@ref) `Be`."""
set_Be!(value::AVRTypeII, val) = value.Be = val
"""Set [`AVRTypeII`](@ref) `V_ref`."""
set_V_ref!(value::AVRTypeII, val) = value.V_ref = val
"""Set [`AVRTypeII`](@ref) `ext`."""
set_ext!(value::AVRTypeII, val) = value.ext = val
"""Set [`AVRTypeII`](@ref) `states_types`."""
set_states_types!(value::AVRTypeII, val) = value.states_types = val


text:
# *****************************************************************************
# Written by Ritchie Lee, ritchie.lee@sv.cmu.edu
# *****************************************************************************
# Copyright ã ``2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.  The Reinforcement Learning Encounter Simulator (RLES)
# platform is licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. You
# may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable
# law or agreed to in writing, software distributed under the License is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
# _____________________________________________________________________________
# Reinforcement Learning Encounter Simulator (RLES) includes the following
# third party software. The SISLES.jl package is licensed under the MIT Expat
# License: Copyright (c) 2014: Youngjun Kim.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED
# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# *****************************************************************************

#Implementation of the functions in grammar

using DataFrames

typealias RealVec Vector{Float64}
typealias BoolVec Vector{Bool}

function eq(v1::BoolVec, v2::BoolVec)
    r = similar(v1)
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] == v2[i]
    end
    r
end
function eq(v1::RealVec, v2::RealVec)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] == v2[i]
    end
    r
end
function eq(v1::RealVec, b::Real)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] == b
    end
    r
end
function lt(v1::RealVec, v2::RealVec)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] < v2[i]
    end
    r
end
function lt(v1::RealVec, b::Real)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] < b
    end
    r
end
function lte(v1::RealVec, v2::RealVec)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] <= v2[i]
    end
    r
end

function lte(v1::RealVec, b::Real)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] <= b
    end
    r
end

function gt(v1::RealVec, v2::RealVec)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] > v2[i]
    end
    r
end

function gt(v1::RealVec, b::Real)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] > b
    end
    r
end

function gte(v1::RealVec, v2::RealVec)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] >= v2[i]
    end
    r
end

function gte(v1::RealVec, b::Real)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] >= b
    end
    r
end

function feq{T}(D::DataFrame, col_id::Int64, V::Vector{T}, val_id::Int64)
    v1 = get_ref(D, col_id)
    b = get_val(V, col_id, val_id)
    eq(v1, b)
end
function flt{T}(D::DataFrame, col_id::Int64, V::Vector{T}, val_id::Int64)
    v1 = get_ref(D, col_id)
    b = get_val(V, col_id, val_id)
    lt(v1, b)
end
function flte{T}(D::DataFrame, col_id::Int64, V::Vector{T}, val_id::Int64)
    v1 = get_ref(D, col_id)
    b = get_val(V, col_id, val_id)
    lte(v1, b)
end
function fgt{T}(D::DataFrame, col_id::Int64, V::Vector{T}, val_id::Int64)
    v1 = get_ref(D, col_id)
    b = get_val(V, col_id, val_id)
    gt(v1, b)
end
function fgte{T}(D::DataFrame, col_id::Int64, V::Vector{T}, val_id::Int64)
    v1 = get_ref(D, col_id)
    b = get_val(V, col_id, val_id)
    gte(v1, b)
end

eventually(v::BoolVec) = any(v)
globally(v::BoolVec) = all(v)

function implies(v1::BoolVec, v2::BoolVec)
    r = similar(v1)
    @simd for i = 1:length(v1)
        @inbounds r[i] = v2[i] || !v1[i]
    end
    all(r)
end

function sign_(v1::RealVec, v2::RealVec)
    r = fill(false, length(v1))
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] * v2[i] >= 0.0
    end
    r
end

or(x1::Bool, x2::Bool) = x1 || x2
function or(v1::BoolVec, v2::BoolVec)
    r = similar(v1)
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] || v2[i]
    end
    r
end

and(x1::Bool, x2::Bool) = x1 && x2
function and(v1::BoolVec, v2::BoolVec)
    r = similar(v1)
    @simd for i = 1:length(v1)
        @inbounds r[i] = v1[i] && v2[i]
    end
    r
end

not(x) = !x
function not(v::BoolVec)
    r = similar(v)
    @simd for i = 1:length(v)
        @inbounds r[i] = !v[i]
    end
    r
end

#get
get_ref(D::DataFrame, id::Int64) = D[id]
get_val{T}(V::Vector{T}, col_id::Int64, val_id::Int64) = V[col_id][val_id]

max_stars_repo_name: sisl/ExprSearch

max_issues_repo_name: sisl/ExprSearch


text: @time let count = 0; for p in treefoldingprimes() p > 1000000 && break; count += 1 end; count end

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
# Model supporting only SecondOrderCone as non-LP cone.
MOIU.@model(ModelForMock, (MOI.ZeroOne, MOI.Integer),
            (MOI.EqualTo, MOI.GreaterThan, MOI.LessThan, MOI.Interval),
            (MOI.Zeros, MOI.Nonnegatives, MOI.Nonpositives, MOI.SecondOrderCone),
            (),
            (),
            (MOI.ScalarAffineFunction, MOI.ScalarQuadraticFunction),
            (MOI.VectorOfVariables,),
            (MOI.VectorAffineFunction,))


text:
print_all(Lexers.MatlabLexer, "matlab")

tokentest(
    Lexers.MatlabLexer,
    "% A single line comment.",
    COMMENT_SINGLE => "% A single line comment.",
)

tokentest(
    Lexers.MatlabLexer,
    "%{\n...\n...\n%}",
    COMMENT_MULTILINE => "%{\n...\n...\n%}",
)

tokentest(
    Lexers.MatlabLexer,
    "x = 1;",
    NAME => "x",
    TEXT => " ",
    PUNCTUATION => "=",
    TEXT => " ",
    NUMBER_INTEGER => "1",
    PUNCTUATION => ";",
)

tokentest(
    Lexers.MatlabLexer,
    "function result = func(x, y)",
    KEYWORD => "function",
    WHITESPACE => " ",
    TEXT => "result ",
    PUNCTUATION => "=",
    WHITESPACE => " ",
    NAME_FUNCTION => "func",
    PUNCTUATION => "(",
    TEXT => "x, y",
    PUNCTUATION => ")",
)

tokentest(
    Lexers.MatlabLexer,
    "!ping julialang.org",
    STRING_OTHER => "!ping julialang.org",
)

tokentest(
    Lexers.MatlabLexer,
    "[X, Y] = func(1.0, 2.3e-9, 3j);",
    PUNCTUATION => "[",
    NAME => "X",
    PUNCTUATION => ",",
    TEXT => " ",
    NAME => "Y",
    PUNCTUATION => "]",
    TEXT => " ",
    PUNCTUATION => "=",
    TEXT => " ",
    NAME_FUNCTION => "func",
    PUNCTUATION => "(",
    NUMBER_FLOAT => "1.0",
    PUNCTUATION => ",",
    TEXT => " ",
    NUMBER_FLOAT => "2.3e-9",
    PUNCTUATION => ",",
    TEXT => " ",
    NUMBER_INTEGER => "3",
    NAME => "j",
    PUNCTUATION => ");",
)

tokentest(
    Lexers.MatlabLexer,
    "if x == y",
    KEYWORD => "if",
    TEXT => " ",
    NAME => "x",
    TEXT => " ",
    OPERATOR => "==",
    TEXT => " ",
    NAME => "y",
)

tokentest(
    Lexers.MatlabLexer,
    "'abc ... xyz'",
    STRING => "'abc ... xyz'",
)

tokentest(
    Lexers.MatlabLexer,
    "A(i) = i^2",
    NAME_FUNCTION => "A",
    PUNCTUATION => "(",
    NAME => "i",
    PUNCTUATION => ")",
    TEXT => " ",
    PUNCTUATION => "=",
    TEXT => " ",
    NAME => "i",
    OPERATOR => "^",
    NUMBER_INTEGER => "2",
)

tokentest(
    Lexers.MatlabLexer,
    "x_1 < y_2",
    NAME => "x_1",
    TEXT => " ",
    OPERATOR => "<",
    TEXT => " ",
    NAME => "y_2",
)


text:
#****************************************************************************
#                     Molecular Dynamics Potentials (MDP)
#                            CESMIX-MIT Project
#
#  Contributing authors: Ngoc-Cuong Nguyen (cuongng@mit.edu, exapde@gmail.com)
#****************************************************************************

__precompile__()

using Revise, Libdl

global integrationlib

function loadintegration(mdppath::String)
    libexist = 0
    if Sys.isapple()
        libpath = mdppath * "src/Julia/Integration/cpuIntegration.dylib";
    elseif Sys.isunix()
        libpath = mdppath * "src/Julia/Integration/cpuIntegration.so";
    elseif Sys.windows()
        libpath = mdppath * "src/Julia/Integration/cpuIntegration.so";
    end
    if isfile(libpath)
        libexist = 1;
    end
    if libexist==0
        cdir = pwd();
        cd(mdppath * "src/Julia/Integration")
        cstr = `g++ -std=c++11 -Wall -Wextra -pedantic -c -fPIC cpuIntegration.cpp -o cpuintegration.o`
        run(cstr)
        if Sys.isapple()
            cstr = `g++ -shared cpuintegration.o -o cpuIntegration.dylib`
        else
            cstr = `g++ -shared cpuintegration.o -o cpuIntegration.so`
        end
        run(cstr)
        cd(cdir)
    end
    global integrationlib = Libdl.dlopen(libpath)
end

function closeintegration()
    Libdl.dlclose(integrationlib)
end

function SetGlobalBox(dom::Domain)
    ccall(Libdl.dlsym(integrationlib, :cpuSetGlobalBox), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Cint),
    dom.h, dom.h_inv, dom.boxlo_bound, dom.boxhi_bound, dom.boxhi, dom.boxlo, dom.boxtilt, dom.triclinic)
    return dom
end

function SetLocalOrthBox(dom::Domain)
    ccall(Libdl.dlsym(integrationlib, :cpuSetLocalOrthBox), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Cint),
    dom.subhi, dom.sublo, dom.boxhi, dom.boxlo, dom.subhi_lamda, dom.sublo_lamda, dom.dimension)
    return dom
end

function ShiftedSubbox(dom::Domain)
    epsilon = zeros(3)
    for i=1:3
        epsilon[i] = 1e-6*(dom.boxhi[i]-dom.boxlo[i]);
    end
    ccall(Libdl.dlsym(integrationlib, :cpuShiftedSubbox), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Cint),
    dom.ssublo, dom.ssubhi, dom.boxlo, dom.boxhi, dom.boxlo_lamda, dom.boxhi_lamda,
    dom.sublo, dom.subhi, dom.sublo_lamda, dom.subhi_lamda, epsilon, dom.pbc, dom.triclinic)
    return dom
end

function BoundingSubbox(dom::Domain)
    ccall(Libdl.dlsym(integrationlib, :cpuBoundingSubbox), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Cint),
    dom.bsublo, dom.bsubhi, dom.sublo, dom.subhi, dom.sublo_lamda, dom.subhi_lamda,
    dom.boxlo, dom.h, dom.triclinic)
    return dom
end

function SetupLattice(lat::Lattice, unitstyle::Int32, dim::Int32)
    basis = zeros(12*3)

    nbasis = ccall(Libdl.dlsym(integrationlib, :cpuLattice), Cint, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    basis, lat.primitive, lat.rotaterow, lat.primitinv, lat.rotatecol, lat.origin,
    lat.spacing, lat.a1, lat.a2, lat.a3, lat.scale, lat.orientx, lat.orienty, lat.orientz,
    lat.style, unitstyle, lat.spaceflag, dim)

    lat.nbasis = nbasis
    lat.basis = reshape(basis, (3,12))
    return lat
end

function LatticeBoundingBox(lat::Lattice, dom::Domain)
    ccall(Libdl.dlsym(integrationlib, :cpuLatticeBoundingBox), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Cdouble),
    lat.sublo, lat.subhi, dom.bsublo, dom.bsubhi, lat.primitive, lat.rotaterow, lat.primitinv,
    lat.rotatecol, lat.origin, lat.spacing, lat.scale)
    return lat
end

function AtomLattice(x::Vector{Float64}, t::Vector{Int32}, lat::Lattice, nlocal::Int32, dim::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuAtomLattice), Cvoid, (Ptr{Cdouble}, Ptr{Cint},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
    Cdouble, Ptr{Cint}, Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint), x, t,
    lat.atombasis, lat.primitive, lat.rotaterow, lat.origin, lat.spacing, lat.scale,
    lat.atomtype, lat.nbasis, nlocal, lat.ilo, lat.ihi, lat.jlo, lat.jhi, lat.klo, lat.khi, dim)
    return x, t
end

function SetAtomType(x::Vector{Float64}, fraction::Float64, t::Vector{Int32}, seed::Vector{Int32},
    save::Vector{Int32}, seed0::Int32, newtype::Int32, dim::Int32, nlocal::Int32)
    count = ccall(Libdl.dlsym(integrationlib, :cpuSetAtomType), Cint, (Ptr{Cdouble},
    Cdouble, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, fraction, t, seed, save, seed0, newtype, dim, nlocal)
    return t, seed, save, count
end

function VelocityCreate(x::Vector{Float64}, v::Vector{Float64}, mass::Vector{Float64},
    second::Vector{Float64}, seed::Vector{Int32}, save::Vector{Int32}, map::Vector{Int32},
    type::Vector{Int32}, seed0::Int32, sum_flag::Int32, dist_flag::Int32, loop_flag::Int32,
    dim::Int32, mpiRank::Int32,  nlocal::Int32, natoms::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuVelocityCreate), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint,
    Cint, Cint, Cint, Cint, Cint), x, v, mass, second, seed, save, map, type, seed0, sum_flag,
    dist_flag, loop_flag, dim, mpiRank, nlocal, natoms)
    return x, v, second, seed, save
end

function ComputeMass(amass::Vector{Float64}, mass::Vector{Float64}, type::Vector{Int32},
    ilist::Vector{Int32}, inum::Int32)
    masstotal = ccall(Libdl.dlsym(integrationlib, :cpuComputeMass), Cdouble, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint), amass, mass, type, ilist, inum)
    return masstotal, amass
end

function ComputeVCM(vcm::Vector{Float64}, v::Vector{Float64}, mass::Vector{Float64},
    masstotal::Float64, ilist::Vector{Int32}, type::Vector{Int32}, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuComputeVCM), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint}, Cint, Cint),
    vcm, v, mass, masstotal, ilist, type, dim, inum)
    return vcm
end

function VelocityZeroMomentum(v::Vector{Float64}, vcm::Vector{Float64}, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuVelocityZeroMomentum), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Cint, Cint), v, vcm, dim, inum)
    return v, vcm
end

function ComputeTempScalar(v::Vector{Float64}, mass::Vector{Float64}, tfactor::Float64,
    type::Vector{Int32}, ilist::Vector{Int32}, dim::Int32, inum::Int32)
    temp = ccall(Libdl.dlsym(integrationlib, :cpuComputeTempScalar), Cdouble, (Ptr{Cdouble},
    Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint}, Cint, Cint),
    v, mass, tfactor, type, ilist, dim, inum)
    return temp
end

function ComputeKEAtom(ke::Vector{Float64}, mass::Vector{Float64}, v::Vector{Float64},
    mvv2e::Float64, type::Vector{Int32}, ilist::Vector{Int32}, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuComputeKEAtom), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint}, Cint, Cint),
    ke, mass, v, mvv2e, type, ilist, dim, inum)
end

function InitialIntegrate(x, v, f, mass::Vector{Float64}, dtarray::Vector{Float64}, tarray::Vector{Float64}, eta_mass::Vector{Float64},
    eta::Vector{Float64}, eta_dot::Vector{Float64}, eta_dotdot::Vector{Float64}, vlimitsq::Float64,
    type::Vector{Int32}, ilist::Vector{Int32}, eta_mass_flag::Int32, biasflag::Int32,
    mtchain::Int32, nc_tchain::Int32, mode::Int32, dim::Int32, inum::Int32)

    ccall(Libdl.dlsym(integrationlib, :cpuInitialIntegrate), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint, Cint, Cint, Cint),
    x, v, f, mass, dtarray, tarray, eta_mass, eta, eta_dot, eta_dotdot, vlimitsq,
    type, ilist, eta_mass_flag, biasflag, mtchain, nc_tchain, mode, dim, inum)
end

function FinalIntegrate(x, v, f, mass::Vector{Float64}, dtarray::Vector{Float64}, tarray::Vector{Float64}, eta_mass::Vector{Float64},
    eta::Vector{Float64}, eta_dot::Vector{Float64}, eta_dotdot::Vector{Float64}, vlimitsq::Float64,
    type::Vector{Int32}, ilist::Vector{Int32}, eta_mass_flag::Int32, biasflag::Int32,
    mtchain::Int32, nc_tchain::Int32, mode::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFinalIntegrate), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint, Cint, Cint, Cint),
    x, v, f, mass, dtarray, tarray, eta_mass, eta, eta_dot, eta_dotdot, vlimitsq,
    type, ilist, eta_mass_flag, biasflag, mtchain, nc_tchain, mode, dim, inum)
end

function VelocityRescalingThermostat(v, mass::Vector{Float64}, dtarray::Vector{Float64},
    tarray::Vector{Float64}, second::Vector{Float64}, energy::Float64, type::Vector{Int32}, ilist::Vector{Int32},
    seed::Vector{Int32}, save::Vector{Int32}, biasflag::Int32, mode::Int32, dim::Int32, inum::Int32)
    energy = ccall(Libdl.dlsym(integrationlib, :cpuVelocityRescalingThermostat), Cdouble, (Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint},
    Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    v, mass, dtarray, tarray, second, energy, type, ilist, seed, save, biasflag, mode, dim, inum)
    return energy
end

function SetVelocityInitialIntegrate(v, mass::Vector{Float64}, tfactor::Float64,
    type::Vector{Int32}, ilist::Vector{Int32}, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuSetVelocityInitialIntegrate), Cdouble, (Ptr{Cdouble},
    Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint}, Cint, Cint),
    v, mass, tfactor, type, ilist, dim, inum)
end

function SetVelocityInitialIntegrate(x, v, f, mass::Vector{Float64}, fparam::Vector{Float64},
    dtf::Float64, dtv::Float64, type::Vector{Int32}, ilist::Vector{Int32}, iparam::Vector{Int32}, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuSetVelocityInitialIntegrate), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Cdouble, Cdouble, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Cint, Cint),
    x, v, f, mass, fparam, dtf, dtv, type, ilist, iparam, dim, inum)
end

function SetVelocityFinalIntegrate(x, v, f, mass::Vector{Float64}, dtf::Float64,
    type::Vector{Int32}, ilist::Vector{Int32}, iparam::Vector{Int32}, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuSetVelocityFinalIntegrate), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Cdouble, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Cint, Cint),
    x, v, f, mass, dtf, type, ilist, iparam, dim, inum)
end

function FixWallReflect(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixWallReflect), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

function FixSetForce(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixSetForce), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

function FixLineForce(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixLineForce), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

function FixPlaneForce(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixPlaneForce), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

# function FixAddForce(x, v, f,
#     eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
#     ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
#     ccall(Libdl.dlsym(integrationlib, :cpuFixAddForce), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
#     Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
#     x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
# end

# function FixDragForce(x, v, f,
#     eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, box::Vector{Float64},
#     iparam::Vector{Int32}, ilist::Vector{Int32}, pbc::Vector{Int32}, triclinic::Int32,
#     eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
#     ccall(Libdl.dlsym(integrationlib, :cpuFixDragForce), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
#     Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
#     x, v, f, eatom, vatom, fparam, box, iparam, ilist, pbc, triclinic, eflag_atom, vflag_atom, dim, inum)
# end

function FixWallHarmonic(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixWallHarmonic), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

function FixWallLJ93(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixWallLJ93), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

function FixWallLJ126(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixWallLJ126), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

function FixWallLJ1043(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixWallLJ1043), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

function FixWallMorse(x, v, f,
    eatom::Vector{Float64}, vatom::Vector{Float64}, fparam::Vector{Float64}, iparam::Vector{Int32},
    ilist::Vector{Int32}, eflag_atom::Int32, vflag_atom::Int32, dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuFixWallMorse), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint}, Ptr{Cint}, Cint, Cint, Cint, Cint),
    x, v, f, eatom, vatom, fparam, iparam, ilist, eflag_atom, vflag_atom, dim, inum)
end

function ApplyPBC(x, v, image::Vector{Int32},
    boxhi::Vector{Float64}, boxlo::Vector{Float64}, hi_lambda::Vector{Float64},
    lo_lambda::Vector{Float64}, h::Vector{Float64}, h_inv::Vector{Float64},
    h_rate::Vector{Float64}, pbc::Vector{Int32}, vdeform::Int32, triclinic::Int32,
    dim::Int32, inum::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuPBC), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cint},
    Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cint}, Cint, Cint, Cint, Cint), x, v, image, boxhi, boxlo, hi_lambda, lo_lambda, h, h_inv,
    h_rate, pbc, vdeform, triclinic, dim, inum)
end

function ArrayDistSquareSum(y, x1, x2, m::Int32, n::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuArrayDistSquareSum), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Cint, Cint), y, x1, x2, m, n)
end

function ArrayPlusAtColumnIndex(A, B, colind::Vector{Int32},
    m::Int32, n::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuArrayPlusAtColumnIndex), Cvoid, (Ptr{Cdouble}, Ptr{Cdouble},
    Ptr{Cdouble}, Cint, Cint), A, B, colind, m, n)
end

function ArraySumEveryColumn(A, B, m::Int32, n::Int32)
    ccall(Libdl.dlsym(integrationlib, :cpuArraySumEveryColumn), Cvoid, (Ptr{Cdouble},
    Ptr{Cdouble}, Cint, Cint), A, B, m, n)
end

max_stars_repo_name: cesmix-mit/MDP

max_issues_repo_name: cesmix-mit/MDP

max_forks_repo_name: cesmix-mit/MDP


text:
module DTWDTfunctions
export test, computeErrorFunction, accumulateErrorFunction, backtrackDistanceFunction, computeDTWerror

"""
 USAGE: err = computeErrorFunction( u1, u0, nSample, lag )

 INPUT:

   u1      = trace that we want to warp; size = (nsamp,1)

   u0      = reference trace to compare with: size = (nsamp,1)

   nSample = numer of points to compare in the traces

   lag     = maximum lag in sample number to search

   norm    = 'L2' or 'L1' (default is 'L2')

 OUTPUT:

    err = the 2D error function; size = (nsamp,2*lag+1)

 The error function is equation 1 in Hale, 2013.

 You could umcomment the L1 norm and comment the L2 norm if you want on Line 29

 Original by Di Yang
 Last modified by Dylan Mikesell (25 Feb. 2015)
"""
function computeErrorFunction(u1::Union{Array{Float32,1},Array{Float64,1}}, u0::Union{Array{Float32,1},Array{Float64,1}}, nSample::Int, lag::Int; norm::String="L2")

    if lag >= nSample
        error("computeErrorFunction:lagProblem ","lag must be smaller than nSample");
    end

    #using JLD2
    #@load "../exampledata/sineShiftData.jld2"
    #nSample = length(u0)
    #lag = 80
    #norm = "L2"

    # Allocate error function variable
    err = zeros(Float64, nSample, 2 * lag + 1 );

    #--------------------------------------------------------------------------
    # initial error calculation
    for ll = -lag:lag # loop over lags

        thisLag = ll + lag + 1;

        for ii = 1:nSample # loop over samples

            if ( ii + ll >= 1 && ii + ll <= nSample ) # skip corners for now, we will come back to these

                diff = u1[ii] - u0[ii + ll]; # sample difference

                if norm == "L2"
                        err[ii, thisLag] = diff^2; # difference squared error
                elseif norm == "L1"
                        err[ii, thisLag] = abs(diff); # absolute value errors
                else
                    error("norm type is not defined.")
                end

            end

        end

    end

    #--------------------------------------------------------------------------
    # Now fix corners with constant extrapolation
    for ll = -lag:lag # loop over lags

        thisLag = ll + lag + 1;

        for ii = 1:nSample # loop over samples

            if ( ii + ll < 1 ) # lower left corner (negative lag, early time)

                err[ii, thisLag] = err[-ll + 1, thisLag];

            elseif ( ii + ll > nSample ) # upper right corner (positive lag, late time)

                err[ii, thisLag] = err[nSample - ll, thisLag];

            end

        end

    end

    return err
end

"""

 USAGE: d = accumulation_diw_mod( dir, err, nSample, lag, b )

 INPUT:

   dir = accumulation direction ( dir > 0 = forward in time, dir <= 0 = backward in time)

   err = the 2D error function; size = (nsamp,2*lag+1)

   nSample = numer of points to compare in the traces

   lag = maximum lag in sample number to search

   b = strain limit (integer value >= 1)

 OUTPUT:

    d = the 2D distance function; size = (nsamp,2*lag+1)

 The function is equation 6 in Hale, 2013.

 Original by Di Yang Last modified by Dylan Mikesell (25 Feb. 2015)
"""
function accumulateErrorFunction(dir::Int, err::Array{Float64,2}, nSample::Int, lag::Int, b::Int)

    #nSample = length(u0)
    #lag = 80
    #dir = -1

    nLag = (2 * lag ) + 1; # number of lags from [ -lag : +lag ]

    # allocate distance matrix
    d = zeros(Float64, nSample, nLag);

    #--------------------------------------------------------------------------
    # Setup indices based on forward or backward accumulation direction
    #--------------------------------------------------------------------------
    if dir > 0            # FORWARD
        iBegin = 1;       # start index
        iEnd   = nSample; # end index
        iInc   = 1;       # increment
    else                  # BACKWARD
        iBegin = nSample; # start index
        iEnd   = 1;       # stop index
        iInc   = -1;      # increment
    end
    #--------------------------------------------------------------------------
    # Loop through all times ii in forward or backward direction

    for ii = iBegin:iInc:iEnd

        # min/max to account for the edges/boundaries
        ji = max(1, min(nSample, ii - iInc ));     # i-1 index
        jb = max(1, min(nSample, ii - iInc * b )); # i-b index

        # loop through all lags l
        for ll = 1:nLag

            # -----------------------------------------------------------------
            # check limits on lag indices
            lMinus1 = ll - 1; # lag at l-1

            if lMinus1 < 1  # check lag index is greater than 1
                lMinus1 = 1; # make lag = first lag
            end

            lPlus1 = ll + 1; # lag at l+1

            if lPlus1 > nLag # check lag index less than max lag
    #             lPlus1 = nLag - 1; # D.Y. version
                lPlus1 = nLag; # D.M. version
            end
            # -----------------------------------------------------------------

            # get distance at lags (ll-1, ll, ll+1)
            distLminus1 = d[jb, lMinus1]; # minus:  d( i-b, j-1 )
            distL       = d[ji, ll];      # actual: d( i-1, j   )
            distLplus1  = d[jb, lPlus1];  # plus:   d( i-b, j+1 )

            if ji != jb # equation 10 in Hale (2013)
                for kb = ji:-iInc:jb+iInc # sum errors over i-1:i-b+1
                    distLminus1 = distLminus1 + err[kb, lMinus1];
                    distLplus1  = distLplus1  + err[kb, lPlus1];
                end
            end

            # equation 6 (if b=1) or 10 (if b>1) in Hale (2013) after treating boundaries
            d[ii, ll] = err[ii, ll] + min(distLminus1, distL, distLplus1);
        end
    end
    return d
end

"""

 USAGE: stbar = backtrackDistanceFunction( dir, d, err, lmin, b )

 INPUT:

   dir   = side to start minimization ( dir > 0 = front, dir <= 0 =  back)

   d     = the 2D distance function; size = (nsamp,2*lag+1)

   err   = the 2D error function; size = (nsamp,2*lag+1)

   lmin  = minimum lag to search over

   b     = strain limit (integer value >= 1)

 OUTPUT:

   stbar = vector of integer shifts subject to |u(i)-u(i-1)| <= 1/b

 The function is equation 2 in Hale, 2013.

 Original by Di Yang Last modified by Dylan Mikesell (19 Dec. 2014)

"""
function backtrackDistanceFunction(dir::Int, d::Array{Float64,2}, err::Array{Float64,2}, lmin::Int, b::Int)

    #d = dist
    #dir = -1
    #lmin = -maxLag
    #b = 1

    nSample = size(d,1); # number of samples
    nLag    = size(d,2); # number of lags
    stbar   = zeros(Int64, nSample); # allocate

    #--------------------------------------------------------------------------
    # Setup indices based on forward or backward accumulation direction
    #--------------------------------------------------------------------------
    if dir > 0            # FORWARD
        iBegin = 1;       # start index
        iEnd   = nSample; # end index
        iInc   = 1;       # increment
    else                  # BACKWARD
        iBegin = nSample; # start index
        iEnd   = 1;       # stop index
        iInc   = -1;      # increment
    end
    #--------------------------------------------------------------------------
    # start from the end (front or back)
    ll0 = argmin(d[iBegin,:]); # find minimum accumulated distance at front or back depending on 'dir'
    stbar[iBegin] = ll0 + lmin - 1; # absolute value of integer shift
    #--------------------------------------------------------------------------
    # move through all time samples in forward or backward direction
    ii = iBegin;

    while ii != iEnd
        if ii == iBegin
            ll = ll0;
        else
            ll = ll_next
        end

        # min/max for edges/boundaries
        ji = max( 1, min(nSample, ii + iInc) );
        jb = max( 1, min(nSample, ii + iInc * b) );

        # -----------------------------------------------------------------
        # check limits on lag indices

        lMinus1 = ll - 1; # lag at l-1

        if lMinus1 < 1 # check lag index is greater than 1
            lMinus1 = 1; # make lag = first lag
        end

        lPlus1 = ll + 1; # lag at l+1

        if lPlus1 > nLag # check lag index less than max lag
            lPlus1 = nLag; # D.M. and D.Y. version
        end
        # -----------------------------------------------------------------
        # get distance at lags (ll-1, ll, ll+1)
        distLminus1 = d[jb, lMinus1]; # minus:  d( i-b, j-1 )
        distL       = d[ji, ll];      # actual: d( i-1, j   )
        distLplus1  = d[jb, lPlus1];  # plus:   d( i-b, j+1 )

        if ji != jb # equation 10 in Hale (2013)
            for kb = ji:iInc:jb-iInc # sum errors over i-1:i-b+1
                distLminus1 = distLminus1 + err[kb, lMinus1];
                distLplus1  = distLplus1  + err[kb, lPlus1];
            end
        end

        dl = min(distLminus1, distL, distLplus1); # update minimum distance to previous sample

        if ( dl != distL ) # then ll != ll and we check forward and backward
            if ( dl == distLminus1 )
                global ll_next = lMinus1;
            else # ( dl == lPlus1 )
                global ll_next = lPlus1;
            end
        else
            ll_next = ll
        end

        # assume ii = ii - 1
        ii += iInc; # previous time sample

        stbar[ii] = ll_next + lmin - 1; # absolute integer of lag
        # now move to correct time index, if smoothing difference over many
        # time samples using 'b'

        if ( ll_next == lMinus1 || ll_next == lPlus1 ) # check edges to see about b values
            if ( ji != jb ) # if b>1 then need to move more steps
                for kb = ji:iInc:jb - iInc
                    ii = ii + iInc; # move from i-1:i-b-1
                    stbar[ii] = ll_next + lmin - 1; # constant lag over that time
                end
            end
        end
    end

    return stbar

    #------------------------#
    # while loop is tricky with Julia
    # we modified ll to ll_next
    # this is the original source from dylanmikesell
    #------------------------#
    # ii = iBegin;
    # while (ii ~= iEnd)
    #
    #     % min/max for edges/boundaries
    #     ji = max( 1, min( [ nSample, ii + iInc ] ) );
    #     jb = max( 1, min( [ nSample, ii + iInc * b ] ) );
    #
    #     % -----------------------------------------------------------------
    #     % check limits on lag indices
    #     lMinus1 = ll - 1; % lag at l-1
    #
    #     if lMinus1 < 1 % check lag index is greater than 1
    #         lMinus1 = 1; % make lag = first lag
    #     end
    #
    #     lPlus1 = ll + 1; % lag at l+1
    #
    #     if lPlus1 > nLag % check lag index less than max lag
    #         lPlus1 = nLag; % D.M. and D.Y. version
    #     end
    #     % -----------------------------------------------------------------
    #
    #     % get distance at lags (ll-1, ll, ll+1)
    #     distLminus1 = d( jb, lMinus1 ); % minus:  d( i-b, j-1 )
    #     distL       = d( ji, ll );      % actual: d( i-1, j   )
    #     distLplus1  = d( jb, lPlus1 );  % plus:   d( i-b, j+1 )
    #
    #     if (ji ~= jb) % equation 10 in Hale (2013)
    #         for kb = ji : iInc : jb - iInc % sum errors over i-1:i-b+1
    #             distLminus1 = distLminus1 + err( kb, lMinus1 );
    #             distLplus1  = distLplus1  + err( kb, lPlus1  );
    #         end
    #     end
    #
    #     dl = min( [ distLminus1, distL, distLplus1 ] ); % update minimum distance to previous sample
    #
    #     if ( dl ~= distL ) % then ll ~= ll and we check forward and backward
    #         if ( dl == distLminus1 )
    #             ll = lMinus1;
    #         else % ( dl == lPlus1 )
    #             ll = lPlus1;
    #         end
    #     end
    #
    #     % assume ii = ii - 1
    #     ii = ii + iInc; % previous time sample
    #
    #     stbar(ii) = ll + lmin - 1; % absolute integer of lag
    #
    #     % now move to correct time index, if smoothing difference over many
    #     % time samples using 'b'
    #     if ( ll == lMinus1 || ll == lPlus1 ) % check edges to see about b values
    #         if ( ji ~= jb ) % if b>1 then need to move more steps
    #             for kb = ji : iInc : jb - iInc
    #                 ii = ii + iInc; % move from i-1:i-b-1
    #                 stbar(ii) = ll + lmin - 1; % constant lag over that time
    #             end
    #         end
    #     end
    # end

end

"""

 Compute the accumulated error along the warping path for Dynamic
 Time Warping.

 USAGE: function error = computeDTWerror( Aerr, u, lag0 )

 INPUT:

   Aerr = error MATRIX (equation 13 in Hale, 2013)

   u    = warping function (samples) VECTOR

   lag0 = value of maximum lag (samples) SCALAR

 Written by Dylan Mikesell Last modified: 25 February 2015
"""
function computeDTWerror(Aerr::Array{Float64,2}, u::Array{Int64,1}, lag0::Int)

    npts = length(u);

    if size(Aerr,1) != npts
        #println("Funny things with dimensions of error matrix: check inputs.");
        #Aerr = transpose(Aerr);
        error("Funny things with dimensions of error matrix: check inputs.")
    end

    error = 0; # initialize

    # accumulate error
    for ii = 1:npts
        idx = lag0 + 1 + u[ii]; # index of lag
        error += Aerr[ii,idx]; # sum error
    end

    return error

end

end


text:
# Queueing problems
m = 2;  n = 40 ; lmd = 1.0
g = ones(n); g /=sum(g)
U = zeros(m, n)
for i in (1:n)
   U[2,i] = 28 - i
end

@test  all(risolve(U,g,1,
                  initialIterations = 10,
                  aTolSetChoiceProbToZero = 10e-6,
                  aTolerance4Stopping = 0.0,
                  maxIterations = 9999)[1:2] .≈ ([0.2901315939203102, 0.7098684060796899],8.880930086724845))

# Matejka and McKay 2015, RBT
UtilTable = [0 1 0 1;
    0 0 1 1;
    1/2 1/2 1/2 1/2]
λ = 0.4
ρs = -1:0.1:1
results = [risolve(UtilTable, [1+ρ; 1-ρ; 1-ρ; 1+ρ]./4, λ)[1][1] for ρ in ρs]

correct_results = [ 0.5
 0.5000000000000001
 0.5
 0.5
 0.5
 0.5
 0.5
 0.49803143236800007
 0.47259634434957937
 0.4481775023391477
 0.4248079737420439
 0.4025132814392701
 0.38131040477540723
 0.3612070466744384
 0.34220131237025564
 0.32428179482751757
 0.3074280331092877
 0.2916113993696781
 0.27679620629020485
 0.2629410102570515
 0.2500000009320786 ]
@test all((results .+10) .≈ (correct_results .+ 10))


text:
module ReactionNetworkImporters

using DataStructures, DiffEqBiological, SparseArrays

abstract type NetworkFileFormat end

# exported data types
struct RSSANetwork <: NetworkFileFormat end
struct BNGNetwork <: NetworkFileFormat end
struct MatrixNetwork <: NetworkFileFormat end

struct ParsedReactionNetwork
    "DiffEqBiological Network"
    rn

    "Initial Conditions"
    u₀

    "Parameters"
    p

    "Parameter Expressions"
    paramexprs

    "Dict from short sym in rn.syms to full sym for species name"
    symstonames

    "Dict from lumped species name (symbol) to group of species ids"
    groupstoids

end
ParsedReactionNetwork(rn, u₀; p=nothing, paramexprs=nothing, symstonames=nothing, groupstoids=nothing) =
                        ParsedReactionNetwork(rn, u₀, p, paramexprs, symstonames, groupstoids)

export RSSANetwork, BNGNetwork, MatrixNetwork, ParsedReactionNetwork

# parsers
include("parsing_routines_rssafiles.jl")
include("parsing_routines_bngnetworkfiles.jl")
include("parsing_routines_matrixnetworks.jl")

export loadrxnetwork

end # module


text:
using VulkanExperiments
using Test

@testset "VulkanExperiments.jl" begin
    # Write your tests here.
end


text:
lines = readlines("input.txt")
re = r"(\w+)"

function main()
    uniq = 0
    for line = lines
        input, output = split(line, '|')
        signals = [m.match for m = eachmatch(re, output)]
        for signal = signals
            if length(signal) == 2 # one
                uniq += 1
            elseif length(signal) == 3 # seven
                uniq += 1
            elseif length(signal) == 4 # four
                uniq += 1
            elseif length(signal) == 7 # eight
                uniq += 1
            end
        end
    end
    println(uniq)
end

main()


text:
"""
Provides logging functionality.
"""
module Loggers

using Millboard, Dates, MiniLogging
using Genie

import Base.log
export log

"""
Map Genie log levels to MiniLogging levels
"""
const LOG_LEVEL_MAPPING = Dict(
  :debug    => MiniLogging.DEBUG,
  :info     => MiniLogging.INFO,
  :warn     => MiniLogging.WARN,
  :error    => MiniLogging.ERROR,
  :err      => MiniLogging.ERROR,
  :critical => MiniLogging.CRITICAL
)

"""
    log(message, level = "info"; showst::Bool = true) :: Nothing
    log(message::Any, level::Any = "info"; showst::Bool = false) :: Nothing
    log(message::String, level::Symbol) :: Nothing

Logs `message` to all configured logs (STDOUT, FILE, etc) by delegating to `Lumberjack`.
Supported values for `level` are "info", "warn", "debug", "err" / "error", "critical".
If `level` is `error` or `critical` it will also dump the stacktrace onto STDOUT.

# Examples
```julia
```
"""
function log(message::Union{String,Symbol,Number,Exception}, level::Union{String,Symbol} = :debug; showst = false) :: Nothing
  message = string(" ", message)
  level = string(level)

  try
    if isempty(get_logger().handlers)
      if Genie.config.log_to_file
        basic_config(LOG_LEVEL_MAPPING[Genie.config.log_level], log_path()) # file logger
        push!(get_logger().handlers, MiniLogging.Handler(stderr, "%Y-%m-%d %H:%M:%S")) # console logger
      else
        basic_config(LOG_LEVEL_MAPPING[Genie.config.log_level], date_format = "%Y-%m-%d %H:%M:%S")
      end
    end
  catch ex
    basic_config(LOG_LEVEL_MAPPING[Genie.config.log_level], date_format = "%Y-%m-%d %H:%M:%S")
  end

  loggo = get_logger()

  if level == "debug"
    MiniLogging.@debug(loggo, message)
  elseif level == "info"
    MiniLogging.@info(loggo, message)
  elseif level == "warn"
    MiniLogging.@warn(loggo, message)
  elseif level == "error" || level == "err"
    MiniLogging.@error(loggo, message)
  elseif level == "critical"
    MiniLogging.@critical(loggo, message)
  else
    MiniLogging.@debug(loggo, message)
  end

  if (level == "error") && showst
    println()
    stacktrace()
  end

  nothing
end

"""
    truncate_logged_output(output::String) :: String

Truncates (shortens) output based on `output_length` settings and appends "..." -- to be used for limiting the output length when logging.

# Examples
```julia
julia> Genie.config.output_length
100

julia> Genie.config.output_length = 10
10

julia> Loggers.truncate_logged_output("abc " ^ 10)
"abc abc ab..."
```
"""
function truncate_logged_output(output::String) :: String
  length(output) > Genie.config.output_length && output[1:Genie.config.output_length] * "..."
end

"""
    setup_loggers()

Sets up default app loggers (STDOUT and per env file loggers) defferring to the logging module.
Automatically invoked.
"""
function setup_loggers()

end

function log_path()
  "$(joinpath(Genie.LOG_PATH, Genie.config.app_env)).log"
end
function log_path!()
  initlogfile()
  log_path()
end

"""
    macro location()

Provides a macro that injects the FILE and the LINE where the logger was invoked.
"""
macro location()
  :(log(" in $(@__FILE__):$(@__LINE__)", :err))
end

function initlogfile()
	lp = log_path()
	Base.@info "Logging to file at $(abspath(lp)) \n"
  dirname(lp) |> mkpath
	touch(lp)
end

"""
    empty_log_queue() :: Vector{Tuple{String,Symbol}}

The Genie log queue is used to push log messages in the early phases of framework bootstrap,
when the logger itself is not available. Once the logger is ready, the queue is emptied and the
messages are logged.
Automatically invoked.
"""
function empty_log_queue() :: Nothing
  for log_message in Genie.GENIE_LOG_QUEUE
    log(log_message...)
  end

  empty!(Genie.GENIE_LOG_QUEUE)

  nothing
end

function inner_logger()
  get_logger()
end

end


text:
using Mamba

## Data
seeds = Dict{Symbol, Any}(
  :r => [10, 23, 23, 26, 17, 5, 53, 55, 32, 46, 10, 8, 10, 8, 23, 0, 3, 22, 15,
         32, 3],
  :n => [39, 62, 81, 51, 39, 6, 74, 72, 51, 79, 13, 16, 30, 28, 45, 4, 12, 41,
         30, 51, 7],
  :x1 => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  :x2 => [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
)
seeds[:N] = length(seeds[:r])

## Model Specification
model = Model(

  r = Stochastic(1,
    (alpha0, alpha1, x1, alpha2, x2, alpha12, b, n, N) ->
      UnivariateDistribution[
        begin
          p = invlogit(alpha0 + alpha1 * x1[i] + alpha2 * x2[i] +
                       alpha12 * x1[i] * x2[i] + b[i])
          Binomial(n[i], p)
        end
        for i in 1:N
      ],
    false
  ),

  b = Stochastic(1,
    s2 -> Normal(0, sqrt(s2)),
    false
  ),

  alpha0 = Stochastic(
    () -> Normal(0, 1000)
  ),

  alpha1 = Stochastic(
    () -> Normal(0, 1000)
  ),

  alpha2 = Stochastic(
    () -> Normal(0, 1000)
  ),

  alpha12 = Stochastic(
    () -> Normal(0, 1000)
  ),

  s2 = Stochastic(
    () -> InverseGamma(0.001, 0.001)
  )

)

## Initial Values
inits = [
  Dict(:r => seeds[:r], :alpha0 => 0, :alpha1 => 0, :alpha2 => 0,
       :alpha12 => 0, :s2 => 0.01, :b => zeros(seeds[:N])),
  Dict(:r => seeds[:r], :alpha0 => 0, :alpha1 => 0, :alpha2 => 0,
       :alpha12 => 0, :s2 => 1, :b => zeros(seeds[:N]))
]

## Sampling Scheme
scheme = [AMM([:alpha0, :alpha1, :alpha2, :alpha12], 0.01 * eye(4)),
          AMWG(:b, 0.01),
          AMWG(:s2, 0.1)]
setsamplers!(model, scheme)

## MCMC Simulations
sim = mcmc(model, seeds, inits, 12500, burnin=2500, thin=2, chains=2)
describe(sim)


text:
using HypothesisTests, Distributions, Base.Test

# One sample test
n = 1000
srand(1984948)

x = rand(Normal(), n)
t = OneSampleADTest(x, Normal())
@test_approx_eq_eps t.A² 0.2013 0.1^4
@test_approx_eq_eps pvalue(t) 0.8811 0.1^4

x = rand(DoubleExponential(), n)
t = OneSampleADTest(x, Normal())
@test_approx_eq_eps t.A² 10.7439 0.1^4
@test_approx_eq_eps pvalue(t) 0.0 0.1^4

x = rand(Cauchy(), n)
t = OneSampleADTest(x, Normal())
@test pvalue(t) < 1e-100

x = rand(LogNormal(), n)
t = OneSampleADTest(x, Normal())
@test pvalue(t) < 1e-100

# k-sample test
samples = Any[
    [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0],
    [39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8],
    [34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0],
    [34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]
]

t = KSampleADTest(samples...)
@test_approx_eq_eps t.A²k 8.3926 0.1^4
@test_approx_eq_eps t.σ 1.2038 0.1^4
@test_approx_eq_eps pvalue(t) 0.0020 0.1^4

t = KSampleADTest(samples..., modified = false)
@test_approx_eq_eps t.A²k 8.3559 0.1^4
@test_approx_eq_eps t.σ 1.2038 0.1^4
@test_approx_eq_eps pvalue(t) 0.0021 0.1^4

srand(31412455)
samples = Any[rand(Normal(), 50), rand(Normal(0.5), 30)]
t = KSampleADTest(samples...)
@test pvalue(t) < 0.05

samples = Any[rand(Normal(), 50), rand(Normal(), 30), rand(Normal(), 20)]
t = KSampleADTest(samples...)
@test pvalue(t) > 0.05

@test pvalue(OneSampleADTest(vcat(rand(Normal(),500), rand(Beta(2,2),500)), Beta(2,2))) == 0


text:
function for_with_break()
    arr = []
    for i = 0:3
        if i == 2
            has_break = true
            break
        end
        push!(arr, i)
    end
    @assert(arr == [0, 1])
end

function for_with_continue()
    arr = []
    for i = 0:3
        if i == 2
            continue
        end
        push!(arr, i)
    end
    @assert(arr == [0, 1, 3])
end

function for_with_else()
    arr = []
    has_break = false
    for i = 0:3
        push!(arr, i)
    end
    if has_break != true
        push!(arr, 4)
    end
    @assert(arr == [0, 1, 2, 3, 4])
end

function while_with_break()
    arr = []
    i = 0
    while true
        if i == 2
            has_break = true
            break
        end
        push!(arr, i)
        i += 1
    end
    @assert(arr == [0, 1])
end

function while_with_continue()
    arr = []
    i = 0
    while i < 5
        i += 1
        if i == 2
            continue
        end
        push!(arr, i)
    end
    @assert(arr == [1, 3, 4, 5])
end

function loop_range_test()
    arr1 = []
    for i = 1:9
        push!(arr1, i)
    end
    arr2 = []
    num = 1:11
    for i in num
        push!(arr2, i)
    end
    @assert(arr1 == [1, 2, 3, 4, 5, 6, 7, 8, 9])
    @assert(arr2 == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
end

function loop_element_test()
    arr = [1, 2]
    res_1 = []
    for e in arr
        e[2]
        push!(res_1, e)
    end
    @assert(res_1 == [1, 2])
    arr_c = [2, 3, 4]
    res_2 = []
    for e in arr
        push!(res_2, arr_c[e+1])
    end
    @assert(res_2 == [3, 4])
end

function for_cycle_vars()
    seq = [1, 2, 3, 4, 5]
    seq_copy = collect(seq)
    for i = 0:length(seq)-2
        @assert(seq[i+1] == seq_copy[i+1])
    end
    complex_list = [([1, 2], 3, 4)]
    for ((a1, a2), b, c) in complex_list
        @assert(a1 == 1)
        @assert(a2 == 2)
        @assert(b == 3)
        @assert(c == 4)
        arr = []
        a = 1
        for j = 0:1
            push!(arr, a)
            a += 1
        end
        @assert(arr[1] == 1)
        @assert(arr[2] == 2)
    end
    @assert(seq[1] == 1)
    @assert(seq[3] == 3)
    @assert(seq[end] == 5)
    x = 1
    @assert(seq[x+1] == 2)
end

function reversed_array()
    x = [1, 2, 3]
    x = x[end:-1:begin]
    @assert(x == [3, 2, 1])
end

function list_of_lists()
    x = [[1, 2], [3, 4, 5, 6], [3, 4, 5, 6]]
    @assert(x[2][3] == 5)
    @assert(x[3][4] == 6)
end

function inplace_ops()
    a = [1, 1]
    b = a
    b = append!(b, [3, 3])
    @assert(a == [1, 1, 3, 3])
    @assert(b == [1, 1, 3, 3])
end

function list_ops()
    a = Vector()
    push!(a, "test")
    @assert(a == ["test"])
    empty!(a)
    @assert(a == [])
    @assert(length(a) == 0)
    push!(a, "test1")
    push!(a, "test2")
    deleteat!(a, findfirst(isequal("test1"), a))
    @assert(a == ["test2"])
    @assert(length(a) == 1)
    empty!(a)
    push!(a, "test")
    b = copy(a)
    @assert(b == a)
    empty!(a)
    push!(a, "test2")
    push!(a, "test2")
    deleteat!(a, findfirst(isequal("test2"), a))
    @assert(count(isequal("test2"), a) == 1)
    empty!(a)
    push!(a, "test1")
    append!(a, b)
    @assert(a == ["test1", "test"])
    empty!(a)
    elems = ["1", "2", "3"]
    new_elems = []
    for e in elems
        push!(new_elems, repeat(e, 2))
    end
    @assert(new_elems == ["11", "22", "33"])
end

if abspath(PROGRAM_FILE) == @__FILE__
    for_with_break()
    for_with_continue()
    while_with_break()
    while_with_continue()
    loop_range_test()
    for_cycle_vars()
    reversed_array()
    list_of_lists()
    inplace_ops()
    list_ops()
end


text:
function thiele4(pt₁, pt₂, pt₃, pt₄, x)
    result = thiele4(pt₁[1], pt₂[1], pt₃[1], pt₄[1],
                     pt₁[2:end], pt₂[2:end], pt₃[2:end], pt₄[2:end], x)
    # check for degenerate case
    if !allfinite(result)
        if x <= pt₃[1]
            result = thiele3(pt₁, pt₂, pt₃, x)
        else
            result = thiele3(pt₂, pt₃, pt₄, x)
        end
    end
    return result
end

function thiele4(pt₁x, pt₂x, pt₃x, pt₄x, pt₁y, pt₂y, pt₃y, pt₄y, x)
    t1 = @. pt₁y - pt₂y
    t2 = @. pt₂y - pt₃y
    t2 = @. inv(t2)
    t1 = @. inv(t1)
    t2 = @. (pt₂x - pt₃x) * t2
    t1 = @. (pt₁x - pt₂x) * t1
    t3 = @. -t2 + t1
    t4 = @. pt₃y - pt₄y
    t4 = @. inv(t4)
    t4 = @. -(pt₃x - pt₄x) * t4 + t2
    t4 = @. inv(t4)
    t3 = @. inv(t3)
    t3 = @. (pt₁x - pt₃x) * t3
    t4 = @. -(pt₂x - pt₄x) * t4 + pt₂y - pt₃y + t3
    t4 = @. inv(t4)
    t2 = @. -(pt₁x - pt₄x) * t4 + t1 - t2
    t2 = @. inv(t2)
    t2 = @. (pt₃x - x) * t2 - pt₁y + pt₂y + t3
    t2 = @. inv(t2)
    t1 = @. -(pt₂x - x) * t2 + t1
    t1 = @. inv(t1)
    return @. (-(pt₁x - x) * t1 + pt₁y)
end


text:
using Test
using TightBindingLattice

using LinearAlgebra

@testset "basic" begin

    @testset "round" begin
        for Ti in [Int, Int8, Int16, Int32, Int64]
            @test round(Ti,  1//2, RoundDown) == 0
            @test round(Ti, -1//2, RoundDown) == -1
            @test round(Ti,  1//2, RoundUp) == 1
            @test round(Ti, -1//2, RoundUp) == 0
            @test round(Ti,  1//2, RoundToZero) == 0
            @test round(Ti, -1//2, RoundToZero) == 0

            @test round(Ti,  1//1, RoundDown) == 1
            @test round(Ti, -1//1, RoundDown) == -1
            @test round(Ti,  1//1, RoundUp) == 1
            @test round(Ti, -1//1, RoundUp) == -1
            @test round(Ti,  1//1, RoundToZero) == 1
            @test round(Ti, -1//1, RoundToZero) == -1

            inf = 1 // 0
            @test_throws DivideError round(Ti,  inf, RoundDown)
            @test_throws DivideError round(Ti, -inf, RoundDown)
            @test_throws DivideError round(Ti,  inf, RoundUp)
            @test_throws DivideError round(Ti, -inf, RoundUp)
            @test_throws DivideError round(Ti,  inf, RoundToZero)
            @test_throws DivideError round(Ti, -inf, RoundToZero)
        end

        for Tf in [Float16, Float32, Float64]
            @test round(Tf,  1//2, RoundDown) == 0.0
            @test round(Tf, -1//2, RoundDown) == -1.0
            @test round(Tf,  1//2, RoundUp) == 1.0
            @test round(Tf, -1//2, RoundUp) == 0.0
            @test round(Tf,  1//2, RoundToZero) == 0.0
            @test round(Tf, -1//2, RoundToZero) == 0.0

            @test round(Tf,  1//1, RoundDown) == 1.0
            @test round(Tf, -1//1, RoundDown) == -1.0
            @test round(Tf,  1//1, RoundUp) == 1.0
            @test round(Tf, -1//1, RoundUp) == -1.0
            @test round(Tf,  1//1, RoundToZero) == 1.0
            @test round(Tf, -1//1, RoundToZero) == -1.0

            inf = 1 // 0
            @test round(Tf,  inf, RoundDown) == Inf
            @test round(Tf, -inf, RoundDown) == -Inf
            @test round(Tf,  inf, RoundUp) == Inf
            @test round(Tf, -inf, RoundUp) == -Inf
            @test round(Tf,  inf, RoundToZero) == Inf
            @test round(Tf, -inf, RoundToZero) == -Inf
        end
    end

    @testset "gcd" begin
        using TightBindingLattice: extended_gcd
        let x = 3, y = 0
            r, (a,b) = extended_gcd(x,y)
            @test r == 3
            @test a*x + b*y == r
        end
        let x = 0, y = -3
            r, (a,b) = extended_gcd(x,y)
            @test r == 3
            @test a*x + b*y == r
        end

        for sx in [-1,1], sy in [-1,1]
            let x = 3*sx, y = 4*sy
                r, (a,b) = extended_gcd(x,y)
                @test r == 1
                @test a*x + b*y == r
            end
            let x = 6*sx, y = 9*sy
                r, (a,b) = extended_gcd(x,y)
                @test r == 3
                @test a*x + b*y == r
            end
        end
    end

    @testset "ExactLinearAlgebra" begin
        mat = Int[1 2 3;
                  4 5 2;
                  7 8 10]

        @testset "cofactor" begin
            results = Dict(
                (1,1) => [5 2; 8 10],
                (1,2) => [4 2; 7 10],
                (1,3) => [4 5; 7 8],
                (2,1) => [2 3; 8 10],
                (2,2) => [1 3; 7 10],
                (2,3) => [1 2; 7 8],
                (3,1) => [2 3; 5 2],
                (3,2) => [1 3; 4 2],
                (3,3) => [1 2; 4 5]
            )

            for i in 1:3, j in 1:3
                out = ones(Int, (2,2))
                ExactLinearAlgebra.get_cofactor_matrix_unsafe!(out, mat, i, j)
                @test out == results[i,j]
            end
        end

        @testset "determinant" begin
            tol = Base.rtoldefault(Float64)
            @test_throws ArgumentError ExactLinearAlgebra.determinant([1 2 3; 4 5 6])
            @test_throws ArgumentError ExactLinearAlgebra.determinant(ones(Int, 0,0))
            @test ExactLinearAlgebra.determinant(7*ones(Int, 1, 1)) == 7

            @test ExactLinearAlgebra.determinant(float.(mat)) == det(mat)
            @test abs(det(mat) - ExactLinearAlgebra.determinant(mat)) < tol
            for n in [5, 6, 7, 8]
                a = rand(-3:3, (n, n))
                det1 = det(a)
                det2 = ExactLinearAlgebra.determinant(a)
                @test abs(det1 - det2) < Base.rtoldefault(Float64)
            end
        end # testset determinant

        @testset "inverse" begin
            tol = Base.rtoldefault(Float64)
            @test_throws ArgumentError ExactLinearAlgebra.inverse([1 2 3; 4 5 6])
            @test_throws ArgumentError ExactLinearAlgebra.inverse(ones(Int, 0, 0))
            @test ExactLinearAlgebra.inverse(7*ones(Int, 1, 1)) == ones(Int, 1, 1)//7

            @test maximum(abs.(inv(mat) - ExactLinearAlgebra.inverse(float.(mat)))) < tol
            @test maximum(abs.(inv(mat) - ExactLinearAlgebra.inverse(mat))) < tol
            for n in [5, 6, 7, 8]
                a = rand(-3:3, (n, n)) + 30*I
                inv1 = inv(a)
                inv2 = ExactLinearAlgebra.inverse(a)
                @test maximum(abs.(inv1 - inv2)) < tol
            end

        end
    end # testset ExactLinearAlgebra

end


text:
export resptofc

"""
    resptofc(R::Union{PZResp, PZResp64}))

Attempt to guess critical frequency of seismic instrument response R.
Assumes broadband sensors behave roughly like geophones (i.e., as harmonic
oscillators with a single lower corner frequency) at low frequencies.

See also: `fctoresp`, `PZResp`
"""

function resptofc(R::Union{PZResp, PZResp64})
  T = typeof(R.a0)
  P = R.p
  i = argmin(abs.([real(P[j])-imag(P[j]) for j = 1:length(P)]))
  return T(rationalize(abs(P[i]) / 2pi, tol=eps(Float32)))
end


text:
# ---
# title: 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
# id: problem1546
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Dynamic Programming
# link: <https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/description/>
# hidden: true
# ---
#
# Given an array `nums` and an integer `target`.
#
# Return the maximum number of **non-empty**   **non-overlapping** subarrays
# such that the sum of values in each subarray is equal to `target`.
#
#
#
# **Example 1:**
#
#
#
#     Input: nums = [1,1,1,1,1], target = 2
#     Output: 2
#     Explanation: There are 2 non-overlapping subarrays [ **1,1** ,1, **1,1** ] with sum equals to target(2).
#
#
# **Example 2:**
#
#
#
#     Input: nums = [-1,3,5,1,4,2,-9], target = 6
#     Output: 2
#     Explanation: There are 3 subarrays with sum equal to 6.
#     ([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.
#
# **Example 3:**
#
#
#
#     Input: nums = [-2,6,6,3,5,4,1,2,8], target = 10
#     Output: 3
#
#
# **Example 4:**
#
#
#
#     Input: nums = [0,0,0], target = 0
#     Output: 3
#
#
#
#
# **Constraints:**
#
#   * `1 <= nums.length <= 10^5`
#   * `-10^4 <= nums[i] <= 10^4`
#   * `0 <= target <= 10^6`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
using Dates

struct AmericanExercise <: EarlyExercise
  dates::Vector{Date}
end

struct BermudanExercise <: EarlyExercise
  dates::Vector{Date}
end

struct EuropeanExercise <: Exercise
  dates::Vector{Date}
end

EuropeanExercise(d::Date) = EuropeanExercise([d])
AmericanExercise(d1::Date, d2::Date) = AmericanExercise(Date[d1, d2])

struct RebatedExercise{E <: Exercise, C <: BusinessCalendar, B <: BusinessDayConvention} <: Exercise
  exercise::E
  rebate::Float64
  rebateSettlementDays::Int
  rebatePaymentCalendar::C
  rebatePaymentConvention::B

  RebatedExercise{E, C, B}(exercise::E,
                          rebate::Float64 = 0.0,
                          rebateSettlementDays::Int = 0,
                          rebatePaymentCalendar::C = NullCalendar(),
                          rebatePaymentConvention::B = Following()) where {E, C, B} =
                new{E, C, B}(exercise, rebate, rebateSettlementDays, rebatePaymentCalendar, rebatePaymentConvention)
end


text:
### A Pluto.jl notebook ###
# v0.12.16

using Markdown
using InteractiveUtils

# ╔═╡ 2dd190ae-3888-11eb-2e68-090f885617d6
using DataStructures

# ╔═╡ 47c147e6-3888-11eb-1574-cd2d6aea7b1c
file = open(f->read(f, String), "day_9.txt")

# ╔═╡ 019df412-388a-11eb-17c1-2bfe6376975b
#first match get command, second get value of comand
regex = r"(\d+)\n"

# ╔═╡ f875f352-3952-11eb-3d4a-979e6ccb162f
to_int(x) = parse(Int64,x)

# ╔═╡ 913adf24-3955-11eb-2cf3-5bbfeee310db
input =[ to_int(x.captures[1]) for x in eachmatch(regex,file)]

# ╔═╡ 93a45364-3a20-11eb-0b1c-7b2f51070e0b
tam_buffer = 25

# ╔═╡ c1fc1900-3a1d-11eb-3ec4-fd5962e66c3c
function question1()
	memory = CircularBuffer{Int}(tam_buffer)
	append!(memory,input[1:tam_buffer])

	for (index,i) in enumerate(input[tam_buffer+1:end])

		has_sum = any([(j+k==i)&&(j!=k) for j in memory, k in memory])
		awnser = 40
		if(has_sum)
			push!(memory,i)
		else
			return (index+tam_buffer,i)
		end
	end

end

# ╔═╡ e8f52ace-3a1f-11eb-1933-157ecc0d42c0
index_awns1, awns1 = question1()

# ╔═╡ aab19fbe-3956-11eb-0e2e-4d1994109154
md"# Question 2"

# ╔═╡ bb4c9200-3a20-11eb-3ef3-374ba3a31658
before_awns1 = input[1: index_awns1-1]

# ╔═╡ efa380ea-3a20-11eb-3c8e-8d04111be3e0
function _question2(size_set,awns1)

	memory = CircularBuffer{Int}(size_set)
	append!(memory,input[1:size_set-1])

	for (index,i) in enumerate(input[size_set: end])
		push!(memory,i)

		if(sum(memory) == awns1)
			return  minimum(memory) + maximum(memory)
		end
	end
	return nothing
end

# ╔═╡ 6ba067a8-3a21-11eb-1a57-29ab5ea8efd3
_question2(4,awns1)

# ╔═╡ 86b6bf60-3a21-11eb-0cae-1f6b2222e1b6
function question2()
	for n in 2:size(input)[1]

		result =_question2(n,awns1)
		if(result != nothing)
			return result
		end
	end
end

# ╔═╡ 9490fb04-3a22-11eb-2c11-9fd604a6a319
question2()

# ╔═╡ 130b05ce-3a23-11eb-17bb-218a402f4383

# ╔═╡ Cell order:
# ╠═2dd190ae-3888-11eb-2e68-090f885617d6
# ╠═47c147e6-3888-11eb-1574-cd2d6aea7b1c
# ╠═019df412-388a-11eb-17c1-2bfe6376975b
# ╠═f875f352-3952-11eb-3d4a-979e6ccb162f
# ╠═913adf24-3955-11eb-2cf3-5bbfeee310db
# ╠═93a45364-3a20-11eb-0b1c-7b2f51070e0b
# ╠═c1fc1900-3a1d-11eb-3ec4-fd5962e66c3c
# ╠═e8f52ace-3a1f-11eb-1933-157ecc0d42c0
# ╠═aab19fbe-3956-11eb-0e2e-4d1994109154
# ╠═bb4c9200-3a20-11eb-3ef3-374ba3a31658
# ╠═efa380ea-3a20-11eb-3c8e-8d04111be3e0
# ╠═6ba067a8-3a21-11eb-1a57-29ab5ea8efd3
# ╠═86b6bf60-3a21-11eb-0cae-1f6b2222e1b6
# ╠═9490fb04-3a22-11eb-2c11-9fd604a6a319
# ╠═130b05ce-3a23-11eb-17bb-218a402f4383


text:
module Libxcb

import Xorg_libxcb_jll: libxcb, libxcb_xkb
import Xorg_xcb_util_jll: libxcb_util

using CEnum

const Ctm = Base.Libc.TmStruct
const Ctime_t = UInt
const Cclock_t = UInt

include("xcb_common.jl")
include("xcb_api.jl")

export Ctm, Ctime_t, Cclock_t

# export everything
foreach(names(@__MODULE__, all=true)) do s
   if startswith(string(s), r"(?:X|XCB|xcb)") && !startswith(string(s), "XCB_CONN_") # XCB_CONN_* are replaced by an appropriate enum type (see connection.jl)
       @eval export $s
   end
end

end # module


text:
using RAKE
# Explicitly import some of the internal functions which aren't exported
import RAKE: flatten, split_at_stopwords, find_all_possible_keyphrases
using Base.Test

@testset "RAKE" begin
    @testset "remove_redundant_whitespace" begin
        @test remove_redundant_whitespace(" a") == "a"
        @test remove_redundant_whitespace(" a  b") == "a b"
        @test remove_redundant_whitespace("Bob  the builder") == "Bob the builder"
    end

    @testset "flatten" begin
        @test flatten([["a", "rabbit"],["a", "frog"]]) == ["a", "rabbit", "a", "frog"]
        @test flatten([["a"], ["rabbit"],["a", "frog"]]) == ["a", "rabbit", "a", "frog"]
    end

    @testset "split_at_stopwords" begin
        substringify(str_vec) = SubString{String}.(str_vec)
        @test split_at_stopwords([SubString{String}("Bob the builder")], ["the"]) == substringify.([["Bob"], ["builder"]])
        @test split_at_stopwords(["Bob the builder"], ["the"]) == substringify.([["Bob"], ["builder"]])

        @test (split_at_stopwords(["Bobby Bobbington the brilliantly bold builder and Bill"], ["the", "and"]) == [
            SubString{String}.(["Bobby","Bobbington"]),
            SubString{String}.(["brilliantly","bold","builder"]),
            SubString{String}.(["Bill"])
        ])

        begin
            sentences = ["In mathematics a matrix is a rectangular array of numbers arranged in rows and columns"]
            stopwords = ["in", "a", "is", "of", "in", "and"]
            phrases = substringify.([["mathematics"], ["matrix"], ["rectangular", "array"], ["numbers", "arranged"], ["rows"], ["columns"]])
            @test split_at_stopwords(sentences, stopwords) == phrases
        end
    end

    @testset "Find all possible keyphrases" begin
        @test find_all_possible_keyphrases([["shops"]], 2) == ["shops"]
        @test find_all_possible_keyphrases([["I", "once", "walked"]], 5) ==  ["I", "once", "walked", "I once", "once walked", "I once walked"]

        begin
            phrases = [["deep", "convolutional", "neural", "networks"]]
            one_grams = ["deep", "convolutional", "neural", "networks"]
            two_grams = ["deep convolutional", "convolutional neural", "neural networks"]
            three_grams = ["deep convolutional neural", "convolutional neural networks"]
            four_grams = ["deep convolutional neural networks"]

            @test find_all_possible_keyphrases(phrases, 1) == one_grams
            @test find_all_possible_keyphrases(phrases, 2) == vcat(one_grams, two_grams)
            @test find_all_possible_keyphrases(phrases, 3) == vcat(one_grams, two_grams, three_grams)
            @test find_all_possible_keyphrases(phrases, 4) == vcat(one_grams, two_grams, three_grams, four_grams)
        end
    end
end

max_stars_repo_name: EtymoIO/RAKE


text:
include("t_rho.jl")

include("n_rho.jl")

include("b_rho.jl")