text:
"""
    local_clustering_coefficient(g, v)

Computes the [local clustering coefficient](https://en.wikipedia.org/wiki/Clustering_coefficient) for node `v`.
"""
function local_clustering_coefficient(g::SimpleGraph, v::Integer)
    ntriang, alltriang = local_clustering(g, v)

    return alltriang == 0 ? 0. : ntriang / alltriang
end

"""
    local_clustering(g, v)

Returns a tuple `(a,b)`, where `a` is the number of triangles in the neighborhood of
`v` and `b` is the maximum number of possible triangles.
It is related to the local clustering coefficient  by `r=a/b`.
"""
function local_clustering(g::SimpleGraph, v::Integer)
    k = degree(g, v)
    k <= 1 && return (0, 0)
    neighs = neighbors(g, v)
    c = 0
    for i=1:length(neighs)
        for j=1:length(neighs)
            i == j && continue
            if has_edge(g, neighs[i], neighs[j])
                c += 1
            end
        end
    end
    return is_directed(g) ? (c , k*(k-1)) : (div(c,2) , div(k*(k-1),2))
end

"""
    triangles(g, v)

Returns the number of triangles in the neighborhood for node `v`.
"""
triangles(g::SimpleGraph, v::Integer) = local_clustering(g, v)[1]

"""
    local_clustering_coefficient(g, vlist = vertices(g))

Returns a vector containing  the [local clustering coefficients](https://en.wikipedia.org/wiki/Clustering_coefficient) for vertices `vlist`.
"""
local_clustering_coefficient(g::SimpleGraph, vlist = vertices(g)) = Float64[local_clustering_coefficient(g, v) for v in vlist]

"""
    local_clustering(g, vlist = vertices(g))

Returns two vectors, respectively containing  the first and second result of `local_clustering_coefficients(g, v)`
for each `v` in `vlist`.
"""
function local_clustering(g::SimpleGraph, vlist = vertices(g))
    ntriang = zeros(Int, length(vlist))
    nalltriang = zeros(Int, length(vlist))
    i = 0
    for v in vlist
        i+=1
        ntriang[i], nalltriang[i] = local_clustering(g, v)
    end
    return ntriang, nalltriang
end

"""
    triangles(g, vlist = vertices(g))

Returns a vector containing the number of triangles for vertices `vlist`.
"""
triangles(g::SimpleGraph, vlist = vertices(g)) = local_clustering(g, vlist)[1]

"""
    global_clustering_coefficient(g)

Computes the [global clustering coefficient](https://en.wikipedia.org/wiki/Clustering_coefficient).
"""
function global_clustering_coefficient(g::SimpleGraph)
    c = 0
    ntriangles = 0
    for v in 1:nv(g)
        neighs = neighbors(g, v)
        for i=1:length(neighs)
            for j=1:length(neighs)
                i == j && continue
                if has_edge(g, neighs[i], neighs[j])
                    c += 1
                end
            end
        end
        k = degree(g, v)
        ntriangles += k*(k-1)
    end
    ntriangles == 0 && return 1.
    return c / ntriangles
end


text:
using Flipping
##
Directory_path = "/home/beatriz/mainen.flipping.5ht@gmail.com/Flipping/";
Exp_type = "Photometry";
Exp_name = "GCaMP_close_pokes"
training_days = Date(2017,5,15):Day(1):Date(2017,5,26)
issues_days = Date(2016,12,31):Day(1):Date(2017,1,1)
bad_days = vcat(training_days, issues_days)
Camera_path = "/Users/dariosarra/Google Drive/Flipping/run_task_photo/DatcreGCaMPAutomaticBarr/Cam/"
Behavior_path = "/Users/dariosarra/Google Drive/Flipping/run_task_photo/raw_data"
Mice_suffix = "DG";
DataIndex = ProcessPhotometry.create_photometry_DataIndex(Directory_path, Exp_type,Exp_name, Mice_suffix;bad_days = bad_days)
names(DataIndex)
dformat = Dates.DateFormat("yyyymmdd")
mask = DataIndex[:Day].<=Date("20190717",dformat)
# mask = DataIndex[:MouseID].== "DG2"
DataIndex = DataIndex[mask,:]
# names(DataIndex)
##
pokes, cam_dict = save_bhv_photo(DataIndex)

ext: jl


text:
module AbbrvKW

import StatsBase.countmap
export @AbbrvKW

function findAbbrv(symLong::Vector{Symbol})
    if length(symLong) == 0
        return symLong
    end

    out = Dict()
    for sym in symLong
        out[sym] = Vector{Symbol}()
    end

    symAbbr = deepcopy(symLong)
    symStr = convert.(String, symLong)
    kwCount = length(symLong)

    # Max length of string representation of keywords
    maxLen = maximum(length.(symStr))

    # Identify all abbreviations
    for len in 1:maxLen
        for i in 1:kwCount
            s = symStr[i]
            if length(s) >= len
                s = s[1:len]
                push!(symLong, symLong[i])
                push!(symAbbr, convert(Symbol, s))
                push!(symStr , s)
            end
        end
    end
    symStr = nothing # no longer needed

    # Identify unique abbreviations
    abbrCount = 0
    for (sym, count) in countmap(symAbbr)
        if count == 1
            i = find(symAbbr .== sym)
            @assert length(i) == 1
            i = i[1]
            if symLong[i] != symAbbr[i]
                push!(out[symLong[i]], symAbbr[i])
                abbrCount += 1
            end
        end
    end

    for (key, val) in out
        sort!(out[key])
    end

    return (out, abbrCount)
end

"""
Allow to use abbreviated keyword names in function calls.

This macro allows to shorten function calls by means of abbreviated
keyword names, while using full descriptive keyword names in the
function definition.

Example:
```
@AbbrvKW function Foo(;Keyword::Int=1, verboseLevel::Union{Void,Int}=nothing)
    println("Keyword: ", Keyword)
    if verboseLevel != nothing
        println("New verbosity level: ", verboseLevel)
    end
end

Foo(verb=1, K=3)
```
"""
macro AbbrvKW(func)
    @assert func.head == :function "Not a function"

    if length(func.args[1].args) <= 1
        # Empty parameter list
        return esc(func)
    end

    if typeof(func.args[1]) == Expr  &&
        func.args[1].head == :where
        param = func.args[1].args[1].args[2]
    else
        param = func.args[1].args[2]
    end

    if (typeof(param) != Expr)  ||
        (param.head != :parameters)
        # No keywords given
        return esc(func)
    end

    sym = Vector{Symbol}() # Symbol, long version
    typ = Dict()           # Data type
    splat = Symbol()
    splatFound = false
    for k in param.args
        @assert typeof(k) == Expr "Expr expected"
        @assert k.head in (:kw, :(...)) "Expected :kw or :..., got $(k.head)"

        #dump(k)
        if k.head == :kw
            @assert typeof(k.args[1]) in (Expr, Symbol) "Expected Expr or Symbol"

            if typeof(k.args[1]) == Symbol
                push!(sym, k.args[1])
                typ[sym[end]] = :Any
            elseif typeof(k.args[1]) == Expr
                @assert k.args[1].head == :(::) "Expected :(::), got $(k.args[1].head)"
                push!(sym, k.args[1].args[1])
                typ[sym[end]] = k.args[1].args[2]
            end
        elseif k.head == :(...)
            splat = k.args[1]
            splatFound = true
        end
    end

    # Find abbreviations
    (abbr, count) = findAbbrv(sym)
    if count == 0
        # No abbreviations found
        return esc(func)
    end

    # Add a splat variable if not present
    if !splatFound
        splat = :_abbrvkw_
        a = :($splat...)
        a = a.args[1]
        push!(param.args, a)
        a = nothing
    end

    # Build output Expr
    expr = Expr(:block)
    push!(expr.args, :(local _ii_ = 1))
    push!(expr.args, Expr(:while, :(_ii_ <= length($splat)), Expr(:block)))

    for (sym, tup) in abbr
        length(tup) > 0 || continue
        tup = tuple(tup...)
        push!(expr.args[end].args[end].args,
              :(
                if $(splat)[_ii_][1] in $tup
                typeassert($(splat)[_ii_][2], $(typ[sym]))
                $(sym) = $(splat)[_ii_][2]
                deleteat!($splat, _ii_)
                continue
                end
                ))
    end
    push!(expr.args[end].args[end].args, :(_ii_ += 1))
    push!(expr.args, :(_ii_ = nothing))

    if !splatFound
        push!(expr.args, :(if length($splat) !=0 ;
                           error("Unrecognized keyword abbreviation(s): " * string($splat))
                           end))
        push!(expr.args, :($splat = nothing))
    end

    @assert length(func.args) == 2 "Function Expr has " * string(length(func.args)) * " args"
    @assert func.args[2].head == :block "Function block is not a block, but " * string(func.args[2].head)

    prepend!(func.args[2].args, [expr])
    #@show func
    return esc(func)
end

end # module


text:
# output relay on
# KOE
export psp_setrelayon

const RELAY_ON = [0x4b, 0x4F, 0x45, 0x0d]

"""
    psp_setrelayon(io)

Set output relay on.
"""
function psp_setrelayon(io_psp::IO)
  write(io_psp, RELAY_ON)
  return nothing
end


text:
using LazySets.Arrays: _vector_type

function post(alg::ORBIT{N, VT, AM}, ivp::IVP{<:AbstractContinuousSystem}, tspan;
              Δt0::TimeInterval=zeroI, kwargs...) where {N, VT, AM}

    @unpack δ, approx_model = alg

    if haskey(kwargs, :NSTEPS)
        NSTEPS = kwargs[:NSTEPS]
        T = NSTEPS * δ
    else
        # get time horizon from the time span imposing that it is of the form (0, T)
        T = _get_T(tspan, check_zero=true, check_positive=true)
        NSTEPS = ceil(Int, T / δ)
    end

    U = inputset(ivp)

    # normalize system to canonical form
    ivp_norm = _normalize(ivp)

    # preallocate output flowpipe
    ST = Singleton{N, VT}
    F = Vector{ReachSet{N, ST}}(undef, NSTEPS+1)

    return _post!(U, alg, F, ivp_norm, NSTEPS, Δt0; kwargs...)
end

function _post!(U::AbstractInput, alg::ORBIT, F, ivp, NSTEPS, Δt0; kwargs...)
    U = next_set(U, 1)  # unpack inputs to dispatch on the set type
    _post!(U, alg, F, ivp, NSTEPS, Δt0; kwargs...)
end

# method for deterministic inputs
function _post!(U::Union{Nothing, AbstractSingleton}, alg::ORBIT, F, ivp,
                NSTEPS, Δt0; kwargs...)
    @unpack δ, approx_model = alg

    # homogenize the initial-value problem
    if haskey(kwargs, :homogenize) && kwargs[:homogenize] == true
        ivp = homogenize(ivp)
    end

    # discretize system
    ivp_discr = discretize(ivp, δ, approx_model)
    Φ = state_matrix(ivp_discr)
    Ω0 = initial_state(ivp_discr)

    X = stateset(ivp_discr)
    V = inputset(ivp_discr)

    _orbit!(F, Φ, Ω0, V, NSTEPS+1, δ, X, Δt0)

    return Flowpipe(F)
end

# method for nondeterministic inputs
function _post!(U::LazySet, alg::ORBIT{N, VT}, F, ivp, NSTEPS, Δt0;
               kwargs...) where {N, VT}
    X = stateset(ivp)
    !isa(X, Universe) && error("this algorithm does not " *
        "support state constraints (also called invariants)")

    @unpack δ, approx_model = alg
    !isa(approx_model, NoBloating) && error("this algorithm does not support " *
        "continuous-time analysis")

    A = state_matrix(ivp)
    n = size(A, 1)
    X0 = initial_state(ivp)
    U = next_set(inputset(ivp), 1)

    # discretized matrix
    Φ = _exp(A, δ, approx_model.exp)

    # time interval
    Δt = (zero(N) .. zero(N)) + Δt0

    # start with x0
    x = element(X0)
    @inbounds F[1] = ReachSet(Singleton(x), Δt)
    Δt += δ

    # iterate
    @inbounds for k in 2:NSTEPS+1
        # obtain random input signal and discretize it
        u = sample(U)
        Mu = _Φ₁_u(A, δ, approx_model.exp, approx_model.inv, u, Φ)

        # compute next state
        y = VT(undef, n)
        mul!(y, Φ, x)
        y .+= Mu

        F[k] = ReachSet(Singleton(y), Δt)
        x = y
        Δt += δ
    end

    return Flowpipe(F)
end

# Given a matrix Φ and vectors Ω0 and V, compute the sequence:
#
# Ω0
# Φ*Ω0 + V
# Φ^2*Ω0 + Φ*V + V
# ....
# Φ^(NSTEPS)*Ω0 + Φ^(NSTEPS-1)*V + ... + Φ*V + V
function _orbit!(F, Φ::AbstractMatrix{N}, Ω0, V, NSTEPS, δ, X::Universe, Δt0) where {N}
    # preallocate output sequence
    n = size(Φ, 1)
    VT = _vector_type(typeof(Φ))
    out = Vector{VT}(undef, NSTEPS)
    @inbounds for i in 1:NSTEPS
        out[i] = VT(undef, n)
    end

    # compute output sequence
    _orbit!(out, Φ, Ω0, V, NSTEPS)

    # fill reach-set sequence for each time instance 0, δ, 2δ, ...
    Δt = (zero(N) .. zero(N)) + Δt0
    for k in 1:NSTEPS
        xk = Singleton(out[k])
        F[k] = ReachSet(xk, Δt)
        Δt += δ
    end
    return out
end

# case with zero homogeneous solution Ω0 = 0
function _orbit!(out, Φ::AbstractMatrix{N}, Ω0::ZeroSet, V::Singleton, NSTEPS) where {N}
    v = element(V)
    out[1] = zeros(N, n)
    copy!(out[2], v)
    @inbounds for i in 2:NSTEPS-1
        mul!(out[i+1], Φ, out[i])
        out[i+1] .+= v
    end
    return out
end

# case without input V = 0
function _orbit!(out, Φ::AbstractMatrix{N}, Ω0::Singleton, V::Union{ZeroSet, Nothing}, NSTEPS) where {N}
    x = element(Ω0)
    copy!(out[1], x)
    @inbounds for i in 1:NSTEPS-1
        mul!(out[i+1], Φ, out[i])
    end
    return out
end

# general case
function _orbit!(out, Φ::AbstractMatrix{N}, Ω0::Singleton, V::Singleton, NSTEPS) where {N}
    v = element(V)
    x = element(Ω0)
    copy!(out[1], x)
    @inbounds for i in 1:NSTEPS-1
        mul!(out[i+1], Φ, out[i])
        out[i+1] .+= v
    end
    return out
end

function load_krylov_ORBIT()
return quote

    # case Ω0 = 0 and vector V
    function _orbit_krylov!(A::AbstractMatrix, V::AbstractVector, NSTEPS;
                            hermitian=false, m=min(30, size(A, 1)), tol=1e-7)

        T = eltype(A)
        Ks = KrylovSubspace{T, real(T)}(length(V), m)
        arnoldi!(Ks, A, V; m=m, ishermitian=hermitian, tol=tol)

        out = Vector{typeof(V)}(undef, NSTEPS)
        @inbounds for i in 1:NSTEPS
            out[i] = similar(V)
        end
        out[1] = copy(V)

        @inbounds for i in 1:NSTEPS-1
            expv!(out[i+1], i*1.0, Ks)
            out[i+1] += out[i]
        end
        return out
    end

    # TODO : general case for vectors Ω0 and V
    # ...

end end  # quote / load_krylov_ORBIT()


text:
mutable struct Scope
    parent::Union{Scope,Nothing}
    expr::EXPR
    names::Dict{String,Binding}
    modules::Union{Nothing,Dict{String,Any}}
    ismodule::Bool
end
Scope(expr) = Scope(nothing, expr, Dict{String,Binding}(), nothing, typof(expr) === CSTParser.ModuleH || typof(expr) === CSTParser.BareModule)
function Base.show(io::IO, s::Scope)
    printstyled(io, typof(s.expr))
    printstyled(io, " ", join(keys(s.names), ","), color = :yellow)
    s.modules isa Dict && printstyled(io, " ", join(keys(s.modules), ","), color = :blue)
    println(io)
end

function introduces_scope(x::EXPR, state)
    if typof(x) === CSTParser.BinaryOpCall
        if kindof(x.args[2]) === CSTParser.Tokens.EQ && CSTParser.is_func_call(x.args[1])
            return true
        elseif kindof(x.args[2]) === CSTParser.Tokens.EQ && typof(x.args[1]) === CSTParser.Curly
            return true
        elseif kindof(x.args[2]) === CSTParser.Tokens.ANON_FUNC
            return true
        else
            return false
        end
    elseif typof(x) === CSTParser.WhereOpCall
        # unless in func def signature
        return !_in_func_def(x)
    elseif typof(x) === CSTParser.FunctionDef ||
            typof(x) === CSTParser.Macro ||
            typof(x) === CSTParser.For ||
            typof(x) === CSTParser.While ||
            typof(x) === CSTParser.Let ||
            typof(x) === CSTParser.Generator || # and Flatten?
            typof(x) === CSTParser.Try ||
            typof(x) === CSTParser.Do ||
            typof(x) === CSTParser.ModuleH ||
            typof(x) === CSTParser.BareModule ||
            typof(x) === CSTParser.Abstract ||
            typof(x) === CSTParser.Primitive ||
            typof(x) === CSTParser.Mutable ||
            typof(x) === CSTParser.Struct
        return true
    end
    return false
end

hasscope(x::EXPR) = hasmeta(x) && hasscope(x.meta)
scopeof(x) = nothing
scopeof(x::EXPR) = scopeof(x.meta)
CSTParser.parentof(s::Scope) = s.parent

function setscope!(x::EXPR, s)
    if !hasmeta(x)
        x.meta = Meta()
    end
    x.meta.scope = s
end

function scopes(x::EXPR, state)
    clear_scope(x)
    if scopeof(x) === nothing && introduces_scope(x, state)
        setscope!(x, Scope(x))
    end
    s0 = state.scope
    if typof(x) === FileH
        setscope!(x, state.scope)
    elseif scopeof(x) isa Scope
        if CSTParser.defines_function(x) || CSTParser.defines_macro(x)
            state.delayed = true # Allow delayed resolution
        end
        scopeof(x) != s0 && setparent!(scopeof(x), s0)
        state.scope = scopeof(x)
        if typof(x) === ModuleH # Add default modules to a new module
            state.scope.modules = Dict{String,Any}()
            state.scope.modules["Base"] = getsymbolserver(state.server)["Base"]
            state.scope.modules["Core"] = getsymbolserver(state.server)["Core"]
        elseif typof(x) === BareModule
            state.scope.modules = Dict{String,Any}()
            state.scope.modules["Core"] = getsymbolserver(state.server)["Core"]
        end
        if (typof(x) === CSTParser.ModuleH || typof(x) === CSTParser.BareModule) && bindingof(x) !== nothing # Add reference to out of scope binding (i.e. itself)
            # state.scope.names[bindingof(x).name] = bindingof(x)
            add_binding(x, state)
        elseif typof(x) === CSTParser.Flatten && typof(x.args[1]) === CSTParser.Generator && x.args[1].args isa Vector{EXPR} && length(x.args[1].args) > 0 && typof(x.args[1].args[1]) === CSTParser.Generator
            setscope!(x.args[1].args[1], nothing)
        end
    end
    return s0
end


text:
"""
	struct ExtractDict
		dict::Dict{Symbol,Any}
	end

extracts all items in `dict` and return them as a `Mill.ProductNode`.
If a key is missing in extracted dict, `nothing` is passed to the child extractors.

# Examples

```jldoctest
julia> e = ExtractDict(Dict(:a=>ExtractScalar(Float32, 2, 3), :b=>ExtractCategorical(1:5)))
Dict
  ├── a: Float32
  └── b: Categorical d = 6

julia> res1 = e(Dict("a"=>1, "b"=>1))
ProductNode with 1 obs
  ├── a: ArrayNode(1×1 Array with Float32 elements) with 1 obs
  └── b: ArrayNode(6×1 MaybeHotMatrix with Bool elements) with 1 obs

julia> res1[:a].data
1×1 Array{Float32,2}:
 -3.0

julia> res1[:b].data
6×1 Mill.MaybeHotMatrix{Int64,Array{Int64,1},Int64,Bool}:
 1
 0
 0
 0
 0
 0

julia> res2 = e(Dict("a"=>0))
ProductNode with 1 obs
  ├── a: ArrayNode(1×1 Array with Float32 elements) with 1 obs
  └── b: ArrayNode(6×1 MaybeHotMatrix with Missing elements) with 1 obs

julia> res2[:a].data
1×1 Array{Float32,2}:
 -6.0

julia> res2[:b].data
6×1 Mill.MaybeHotMatrix{Missing,Array{Missing,1},Int64,Missing}:
 missing
 missing
 missing
 missing
 missing
 missing
```
"""
struct ExtractDict{S} <: AbstractExtractor
	dict::S
	function ExtractDict(d::S) where {S<:Dict}
		new{typeof(d)}(d)
	end
end

function Base.getindex(m::ExtractDict, s::Symbol)
	!isnothing(m.dict) && haskey(m.dict, s) && return m.dict[s]
	nothing
end

Base.keys(e::ExtractDict) = keys(e.dict)

replacebyspaces(pad) = map(s -> (s[1], " "^length(s[2])), pad)
(s::ExtractDict)(v::V) where {V<:Nothing} = s(Dict{String,Any}())
(s::ExtractDict)(v)  = s(nothing)

function (s::ExtractDict{S})(v::Dict) where {S<:Dict}
	o = [Symbol(k) => f(get(v,String(k),nothing)) for (k,f) in s.dict]
	ProductNode((; o...))
end

function (s::ExtractDict{S})(ee::ExtractEmpty) where {S<:Dict}
	o = [Symbol(k) => f(ee) for (k,f) in s.dict]
	ProductNode((; o...))
end

extractbatch(extractor, samples) = reduce(catobs, map(s-> extractor(s), samples))

Base.hash(e::ExtractDict, h::UInt) = hash(e.dict, h)
Base.:(==)(e1::ExtractDict, e2::ExtractDict) = e1.dict == e2.dict


text:
function get_crossvalid_parameters(fm::FeatureMap,  kernelname::AbstractString,output_type::AbstractString,options, dataname::AbstractString)
  savename = string(get_model_name(fm,kernelname,output_type,options),"-",dataname,"-crossvalid")
  default_path = "../data/"
  lambdabest =1.0;
  klparambest =1.0;
  #repeat =1 means we should repeat all calculations even if there is a saved output already
  try
    lambdabest, klparambest = load("$(default_path)$(savename).jld","lambdabest", "klparambest");
    println("found ", "$(default_path)$(savename).jld with lambdabest ",lambdabest, " and kernelparam ", klparambest)
  catch loaderror
    println(loaderror)
    println("No best lambdabest for $(fm.name)$(kernelname)")
  end
  return lambdabest, klparambest
end

function get_feature_L1(fm::FeatureMap,output_type::AbstractString)
  savename = string(fm.name,"-",output_type ,"-featureL1");
  default_path = "../data/"
  #repeat =1 means we should repeat all calculations even if there is a saved output already
  features = [];
  try
    features = load("$(default_path)$(savename).jld","features");
    println("found  features for $(default_path)$(savename).jld")
  catch loaderror
    println(loaderror)
    println("No $(default_path)$(savename).jld")
  end
  return features
end

function get_model_name(fm::FeatureMap,  kernelname::AbstractString,output_type::AbstractString, options)
    s=size(options.aux);
    name =string(fm.name,kernelname,"-",output_type)
    if(length(s)>1 || isempty(options.aux) )
        name = string(name,"-f");
    end
   return name
end


text:
# MD5 hash tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/md5-test.c
for (text, hash) in [
    (
        "",
        "d41d8cd98f00b204e9800998ecf8427e"
    ),(
        "a",
        "0cc175b9c0f1b6a831c399e269772661"
    ),(
        "abc",
        "900150983cd24fb0d6963f7d28e17f72"
    ),(
        "message digest",
        "f96b697d7cb7938d525a2f31aaf161d0"
    ),(
        "abcdefghijklmnopqrstuvwxyz",
        "c3fcd3d76192e4007dfb496cca67e13b"
    ),(
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef" *
        "ghijklmnopqrstuvwxyz0123456789",
        "d174ab98d277d9f5a5611c2c9f419d9f"
    ),(
        "12345678901234567890123456789012" *
        "34567890123456789012345678901234" *
        "5678901234567890",
        "57edf4a22be3c955ac49da2e2107b67a"
    )
]
    @test digest("md5", text) == hex2bytes(hash)
end

# SHA1 hash tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/sha1-test.c
for (text, hash) in [
    (
        "",
        "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    ),(
        "a",
        "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8",
    ),(
        "abc",
        "a9993e364706816aba3e25717850c26c9cd0d89d",
    ),(
        "abcdefghijklmnopqrstuvwxyz",
        "32d10c7b8cf96570ca04ce37f2a19d84240d3a89",
    ),(
        "message digest",
        "c12252ceda8be8994d5fa0290a47231c1d16aae3",
    ),(
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn" *
        "opqrstuvwxyz0123456789",
        "761c457bf73b14d27e9e9265c46f4b4dda11f940",
    ),(
        "1234567890123456789012345678901234567890" *
        "1234567890123456789012345678901234567890",
        "50abf5706a150990a08b2c5ea40fa0e585554732",
    ),(
        "38",
        "5b384ce32d8cdef02bc3a139d4cac0a22bb029e8"
    )
]
    @test hexdigest("sha1", text) == hash
end

# SHA256 hash tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/sha256-test.c
for (text,hash) in [
    (
        "abc",
        "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
    ),(
        "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
        "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
    ),(
        "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno" *
        "ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
        "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"
    ),(
        "",
        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    ),(
        "a",
        "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"
    ),(
        "38",
        "aea92132c4cbeb263e6ac2bf6c183b5d81737f179f21efdc5863739672f0f470"
    ),(
        "message digest",
        "f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650"
    ),(
        "abcdefghijklmnopqrstuvwxyz",
        "71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73"
    ),(
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
        "db4bfcbd4da0cd85a60c3c37d3fbd8805c77f15fc6b1fdfe614ee0a7c8fdb4c0"
    ),(
        "1234567890123456789012345678901234567890123456789012345678901234" *
        "5678901234567890",
        "f371bc4a311f2b009eef952dd83ca80e2b60026c8e935592d0f9c308453c813e"
    )
]
    h = Hasher("sha256")
    update!(h, text)
    @test hexdigest!(h) == hash
end

# Test that digest!() actually resets the HashState
h = Hasher("SHA1")
update!(h,"")
@test hexdigest!(h) == "da39a3ee5e6b4b0d3255bfef95601890afd80709"
update!(h,"The quick brown fox jumps over the lazy dog")
@test hexdigest!(h) == "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
h = Hasher("SHA256")
update!(h,"The quick brown fox jumps over the lazy dog")
@test hexdigest!(h) == "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"

# Test invalid parameters
@test_throws ArgumentError Hasher("this is not a hash name")

# Test show methods
println("Testing hash show methods:")
println(get_hash_types()["SHA256"])
println(Hasher("SHA256"))


text:
# # Enright test

# To see the algorithm in action we may look how a triangulated sphere behaves under periodic incompressable shear flow defined in `velocity` method:

function velocity(t,pos)
    x,y,z = pos

    x = x*0.15 + 0.35
    y = y*0.15 + 0.35
    z = z*0.15 + 0.35

    u = 2*sin(pi*x)^2 * sin(2*pi*y) * sin(2*pi*z) * sin(2/3*pi*t)
    v = - sin(2*pi*x) * sin(pi*y)^2 * sin(2*pi*z) * sin(2/3*pi*t)
    w = - sin(2*pi*x) * sin(2*pi*y) * sin(pi*z)^2 * sin(2/3*pi*t)

    [u,v,w] /0.3 #/0.15
end

# As previosly, let's load the a sphere mesh with two subdivisions from icosahedron:
using ElTopo
include("sphere.jl")
msh = unitsphere(2)

# Knowing the mesh, which corresponds to initial conditions, we can use RK2 method to integrate the velocity field. While at every time step we can stabilize the triangulation and visualize that with the fantastic Makie package:

using GeometryTypes
using AbstractPlotting, GLMakie

x = Node(msh)
y = lift(x->x,x)

scene = Scene(show_axis=false)

wireframe!(scene,y,linewidth = 3f0)
mesh!(scene,y, color = :white, shading = false)

display(scene)

t = 0
Δt = 0.01
N = convert(Int,floor(pi/ Δt))

par = SurfTrack(allow_vertex_movement=true)

record(scene, "enright.gif", 1:N) do i # for i in 1:N
    update_cam!(scene,Vec3f0(4,4,4), Vec3f0(2, 0, 0))

    global v = msh.vertices
    global f = msh.faces

    k1 = [velocity(t,pos) for pos in v]
    v1 = v .+ k1 .* Δt
    k2 = [velocity(t+Δt/2,pos) for pos in v1]

    v2 = v .+ k2 .* Δt

    mshn = HomogenousMesh(v2,f)
    global msh = stabilize(mshn,par)

    push!(x,msh)

    AbstractPlotting.force_update!()

    global t+=Δt
end

# ![](enright.gif)


text:
println("Testing symbol.jl")
println("===============================================")

function _symbol_to_unicode()
    RHEOS.symbol_to_unicode(:ε) == :ϵ
end
@test _symbol_to_unicode()

function _symbol_to_unicode_tuple()
    RHEOS.symbol_to_unicode((ε = [1,2,3], sigma = [3,4,5], time = [0.1, 0.2, 0.3], eta = 2.5, k = 6)) == (ϵ = [1, 2, 3], σ = [3, 4, 5], t = [0.1, 0.2, 0.3], η = 2.5, k = 6)
end
@test _symbol_to_unicode_tuple()

function _symbol_to_unicode_dict()
    ds=Dict(:beta=>0.05, :c_beta=>0.05, :eta=>10.0)
    nt=RHEOS.symbol_to_unicode(ds)
    nt.η==10.0
end
@test _symbol_to_unicode_dict()

function _dictnamedtuple()
    dict(namedtuple(x=1,y=2))[:x]==namedtuple(dict(x=1,y=2)).x
end
@test _dictnamedtuple()

println("===============================================")


text:
module Histograms

using StatsBase

import Base.ndims
import Base.push!, Base.+

nbins(h::AbstractHistogram) = map(x->size(x, 1) - 1, edges(h))
nbins(h::AbstractHistogram, i::Int) = size(edges(h)[i], 1)
edges(h::AbstractHistogram) = h.edges

contents(h::Histogram) = h.weights
integral(h::Histogram) = sum(h.weights)
entries(h::Histogram) = contents(h)

integral{T<:Real, N, E}(h::AbstractHistogram{T, N, E}, ndims=1:N) =
    first(sum(contents(h), ndims))

import Base.mean

function mean{T<:Real, N, E}(h::AbstractHistogram{T, N, E}, ndims=1:N)
    ret = Array(Float64, length(ndims))
    for (ind, ndim) in enumerate(ndims)
        mids = Base.midpoints(edges(h)[ndim])
        tot = 0
        otherdims = collect(1:N)
        deleteat!(otherdims, ndim)

        for (midp, w) in zip(mids, sum(contents(h), otherdims))
            tot += midp * w
        end
        ret[ind] = tot
    end
    return ret / integral(h)
end

type ErrorHistogram{T<:Real, N, E} <: AbstractHistogram{T, N, E}
    edges::E
    weights::Array{T,N}
    weights_sq::Array{T,N}
    closed::Symbol
    function ErrorHistogram(
        edges::NTuple{N,AbstractArray},
        weights::Array{T,N},
        weights_sq::Array{T,N},
        closed::Symbol)
        for edg in edges
            issorted(edg) || error("edges must be sorted: $edg")
        end
        closed == :right || closed == :left || error("closed must :left or :right")
        map(x -> length(x)-1,edges) == size(weights) || error("Histogram edge vectors must be 1 longer than corresponding weight dimensions")
        new(edges, weights, weights_sq, closed)
    end
end

Hist1D = ErrorHistogram{Float64, 1, Tuple{Vector{Float64}, }}
Hist2D = ErrorHistogram{Float64, 2, Tuple{Vector{Float64}, Vector{Float64}} }
Hist3D = ErrorHistogram{Float64, 2, Tuple{Vector{Float64}, Vector{Float64}, Vector{Float64}}}

function ErrorHistogram(edges...)
    T = Float64
    N = length(edges)
    E = typeof(edges)

    return ErrorHistogram{T, N, E}(
        edges,
        zeros(T, map(x->size(x, 1) - 1, edges)...),
        zeros(T, map(x->size(x, 1) - 1, edges)...),
        :left
    )
end

function push!{T, N, E, X <: Real, W <: Real}(
    h::ErrorHistogram{T,N,E},
    xs::NTuple{N,X},
    w::W
    )
    idxs = if h.closed == :right
        map((edge, x) -> searchsortedfirst(edge,x) - 1, h.edges, xs)
    else
        map(searchsortedlast, h.edges, xs)
    end

    try
        h.weights[idxs...] += w
        h.weights_sq[idxs...] += w^2
    catch e
        isa(e,BoundsError) || rethrow(e)
    end
    h
end

function push!{T, E, X <: Real, W <: Real}(
    h::ErrorHistogram{T,1,E}, x::X, w::W
    )
    i = if h.closed == :right
        searchsortedfirst(edges(h)[1], x) - 1
    else
        searchsortedlast(edges(h)[1], x)
    end

    if 1 <= i <= length(h.weights)
        @inbounds h.weights[i] += w
        @inbounds h.weights_sq[i] += w^2
    end
    h
end

nbins(h::ErrorHistogram) = map(x->size(x, 1) - 1, edges(h))
ndims{T, N, E}(h::ErrorHistogram{T, N, E}) = N

errors(h::ErrorHistogram) =  sqrt(h.weights_sq)
errorssq(h::ErrorHistogram) =  h.weights_sq
contents(h::ErrorHistogram) = h.weights
edges(h::ErrorHistogram) = h.edges
entries(h::ErrorHistogram) = sum(contents(h))^2 / sum(errorssq(h))

normalize(h::Histogram) = Histogram(h.edges, h.weights/sum(h.weights))
function normalize{T<:Real, N, E}(h::ErrorHistogram{T, N, E})
    sw = sum(h.weights)
    ErrorHistogram{T, N, E}(h.edges, h.weights/sw, h.weights_sq, h.closed)
end

function +{T1<:Real, T2<:Real, N, E}(h1::ErrorHistogram{T1, N, E}, h2::ErrorHistogram{T2, N, E})
    @assert ndims(h1) == ndims(h2)
    @assert nbins(h1) == nbins(h2)
    @assert h1.closed == h2.closed

    for i=1:ndims(h1)
        @assert all(edges(h1)[i] .== edges(h2)[i])
    end

    return ErrorHistogram{T1, N, E}(
        edges(h1),
        contents(h1) .+ contents(h2),
        h1.weights_sq .+ h2.weights_sq,
        h1.closed
    )
end

integralerror{T<:Real, N, E}(h::ErrorHistogram{T, N, E}, ndims=1:N) =
    first(sqrt(sum(errorssq(h), ndims)))

import Base.mean
function mean(h::Hist1D)
    l = 0.0
    mids = midpoints(h.edges[1][2:end-1])
    for i=2:nbins(h)[1]-1
        l += mids[i-1] * h.weights[i]
    end
    return l / sum(h.weights)
end

import Base.std
function std(h::Hist1D)
    l = 0.0
    mids = midpoints(h.edges[1][2:end-1])
    m = mean(h)
    for i=2:nbins(h)[1]-1
        l += (mids[i-1] - m)^2 * h.weights[i]
    end
    return sqrt(l / sum(h.weights))
end

export nbins, edges, contents, errors, integral
export normalize, entries
export ErrorHistogram, Hist1D, Hist2D, Hist3D
export +
end


text:
using Test
using FixedSizeStrings

let e = FixedSizeString{0}("")
    @test e == ""
    @test length(e) == 0
    @test convert(String, e) === ""
    @test isa(convert(String, e), String)
    @test convert(FixedSizeString{0}, "") == e
end

@test_throws ArgumentError FixedSizeString{3}("ab")

let s = FixedSizeString{3}("xyZ")
    @test s == "xyZ"
    @test isless(s, "yyZ")
    @test isless("xyY", s)
    @test length(s) == sizeof(s) == 3
    @test collect(s) == ['x', 'y', 'Z']
    @test convert(String, s) == "xyZ"
    @test convert(FixedSizeString{3}, "xyZ") == s
    @test isa(convert(FixedSizeString{3}, "xyZ"), FixedSizeString)
end

@test_throws InexactError FixedSizeString{2}("αb")

let b = IOBuffer()
    write(b, "a tEst str1ng")
    seekstart(b)
    @test read(b, FixedSizeString{4}) == "a tE"
    @test read(b, FixedSizeString{2}) == "st"
    b = IOBuffer()
    data = "\0Te\$t\0_"
    write(b, FixedSizeString(data))
    @test String(take!(b)) == data
end


text:
using Documenter
using sampleproject

makedocs(
    sitename="sample project",
    modules=[sampleproject],
    pages=["Home" => "index.md"]
)

deploydocs(
    repo = "github.com/nluetts/sampleproject.git",
)

max_stars_repo_name: nluetts/sampleproject

max_issues_repo_name: nluetts/sampleproject

max_forks_repo_name: nluetts/sampleproject


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

using SHA
using Test

const VERBOSE = false

# Define some data we will run our tests on
lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
so_many_as_array = repeat([0x61], 1000000)
so_many_as_tuple = ntuple((i) -> 0x61, 1000000)
tempdir = mktempdir()
file = joinpath(tempdir, ".sha")
fIO = open(file, "w")
write(fIO, '\0')
close(fIO)
data = Any["", "test", lorem, file, so_many_as_array, so_many_as_tuple]

# Descriptions of the data, the SHA functions we'll run on the data, etc...
data_desc = ["the empty string", "the string \"test\"", "lorem ipsum",
             "0 file", "one million a's Array", "one million a's Tuple"]
sha_types = Dict(sha1 => SHA.SHA1_CTX,
            sha2_224 => SHA.SHA2_224_CTX, sha2_256 => SHA.SHA2_256_CTX, sha2_384 => SHA.SHA2_384_CTX, sha2_512 => SHA.SHA2_512_CTX,
            sha3_224 => SHA.SHA3_224_CTX, sha3_256 => SHA.SHA3_256_CTX, sha3_384 => SHA.SHA3_384_CTX, sha3_512 => SHA.SHA3_512_CTX)
sha_funcs = [sha1,
             sha2_224, sha2_256, sha2_384, sha2_512,
             sha3_224, sha3_256, sha3_384, sha3_512]
ctxs = [SHA1_CTX,
        SHA2_224_CTX, SHA2_256_CTX, SHA2_384_CTX, SHA2_512_CTX,
        SHA3_224_CTX, SHA3_256_CTX, SHA3_384_CTX, SHA3_512_CTX]
shws = ["SHA1 hash state",
        "SHA2 224-bit hash state", "SHA2 256-bit hash state", "SHA2 384-bit hash state", "SHA2 512-bit hash state",
        "SHA3 224-bit hash state", "SHA3 256-bit hash state", "SHA3 384-bit hash state", "SHA3 512-bit hash state"]

answers = Dict(
sha1 => [
"da39a3ee5e6b4b0d3255bfef95601890afd80709",
"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3",
"19afa2a4a37462c7b940a6c4c61363d49c3a35f4",
"5ba93c9db0cff93f52b521d7420e43f6eda2784f",
"34aa973cd4c4daa4f61eeb2bdbad27316534016f",
"34aa973cd4c4daa4f61eeb2bdbad27316534016f"
],
sha2_224 => [
"d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f",
"90a3ed9e32b2aaf4c61c410eb925426119e1a9dc53d4286ade99a809",
"6a0644abcf1e2cecbec2814443dab5f24b7ad8ebb66c75667ab67959",
"fff9292b4201617bdc4d3053fce02734166a683d7d858a7f5f59b073",
"20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67",
"20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67"
],
sha2_256 => [
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
"2c7c3d5f244f1a40069a32224215e0cf9b42485c99d80f357d76f006359c7a18",
"6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d",
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0",
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"
],
sha2_384 => [
"38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b",
"768412320f7b0aa5812fce428dc4706b3cae50e02a64caa16a782249bfe8efc4b7ef1ccb126255d196047dfedf17a0a9",
"63980fd0425cd2c3d8a400ee0f2671ef135db03b947ec1af21b6e28f19c16ca272036469541f4d8e336ac6d1da50580f",
"bec021b4f368e3069134e012c2b4307083d3a9bdd206e24e5f0d86e13d6636655933ec2b413465966817a9c208a11717",
"9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985",
"9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985"
],
sha2_512 => [
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
"ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff",
"f41d92bc9fc1157a0d1387e67f3d0893b70f7039d3d46d8115b5079d45ad601159398c79c281681e2da09bf7d9f8c23b41d1a0a3c5b528a7f2735933a4353194",
"b8244d028981d693af7b456af8efa4cad63d282e19ff14942c246e50d9351d22704a802a71c3580b6370de4ceb293c324a8423342557d4e5c38438f0e36910ee",
"e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b",
"e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"
],
sha3_224 => [
"6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7",
"3797bf0afbbfca4a7bbba7602a2b552746876517a7f9b7ce2db0ae7b",
"ea5395370949ad8c7d2ca3e7c045ef3306fe3a3f4740de452ef87a28",
"bdd5167212d2dc69665f5a8875ab87f23d5ce7849132f56371a19096",
"d69335b93325192e516a912e6d19a15cb51c6ed5c15243e7a7fd653c",
"d69335b93325192e516a912e6d19a15cb51c6ed5c15243e7a7fd653c"
],
sha3_256 => [
"a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a",
"36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80",
"8c8142d2ca964ab307ace567ddd5764f17ebb76eb8ff25543ab54c14fe2ab139",
"5d53469f20fef4f8eab52b88044ede69c77a6a68a60728609fc4a65ff531e7d0",
"5c8875ae474a3634ba4fd55ec85bffd661f32aca75c6d699d0cdcb6c115891c1",
"5c8875ae474a3634ba4fd55ec85bffd661f32aca75c6d699d0cdcb6c115891c1",
],
sha3_384 => [
"0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004",
"e516dabb23b6e30026863543282780a3ae0dccf05551cf0295178d7ff0f1b41eecb9db3ff219007c4e097260d58621bd",
"eb9fbba3eb916a4efe384b3125f5d03ceb9c5c1b94431ac30fa86c54408b92701ca5d2628cd7113aa5541177ec3ccd1d",
"127677f8b66725bbcb7c3eae9698351ca41e0eb6d66c784bd28dcdb3b5fb12d0c8e840342db03ad1ae180b92e3504933",
"eee9e24d78c1855337983451df97c8ad9eedf256c6334f8e948d252d5e0e76847aa0774ddb90a842190d2c558b4b8340",
"eee9e24d78c1855337983451df97c8ad9eedf256c6334f8e948d252d5e0e76847aa0774ddb90a842190d2c558b4b8340",
],
sha3_512 => [
"a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26",
"9ece086e9bac491fac5c1d1046ca11d737b92a2b2ebd93f005d7b710110c0a678288166e7fbe796883a4f2e9b3ca9f484f521d0ce464345cc1aec96779149c14",
"3a4318353396a12dfd20442cfce1d8ad4d7e732e85cc56b01b4cf9057a41c8827c0a03c70812e76ace68d776759225c213b4f581aac0dba5dd43b785b1a33fe5",
"7127aab211f82a18d06cf7578ff49d5089017944139aa60d8bee057811a15fb55a53887600a3eceba004de51105139f32506fe5b53e1913bfa6b32e716fe97da",
"3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87",
"3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87",
]
)

function describe_hash(T::Type{S}) where {S <: SHA.SHA_CTX}
    if T <: SHA.SHA1_CTX return "SHA1" end
    if T <: SHA.SHA2_CTX return "SHA2-$(SHA.digestlen(T)*8)" end
    if T <: SHA.SHA3_CTX return "SHA3-$(SHA.digestlen(T)*8)" end
end

VERBOSE && println("Loaded hash types: $(join(sort([describe_hash(t[2]) for t in sha_types]), ", ", " and "))")

# First, test processing the data in one go
nerrors = 0
for idx in 1:length(data)
    global nerrors

    desc = data_desc[idx]
    VERBOSE && print("Testing on $desc$(join(["." for z in 1:(34-length(desc))]))")
    nerrors_old = nerrors
    for sha_idx in 1:length(sha_funcs)
        sha_func = sha_funcs[sha_idx]

        if idx == 4
            open(data[idx]) do f
                hash = bytes2hex(sha_func(f))
            end
        else
            hash = bytes2hex(sha_func(data[idx]))
        end

        if hash != answers[sha_func][idx]
            print("\n")
            @warn(
            """
            For $(describe_hash(sha_types[sha_func])) expected:
                $(answers[sha_func][idx])
            Calculated:
                $(hash)
            """)
            nerrors += 1
        else
            VERBOSE && print(".")
        end
    end
    VERBOSE && println("Done! [$(nerrors - nerrors_old) errors]")
end

# Do another test on the "so many a's" data where we chunk up the data into
# two chunks, (sized appropriately to AVOID overflow from one update to another)
# in order to test multiple update!() calls
VERBOSE && print("Testing on one million a's (chunked properly)")
nerrors_old = nerrors
for sha_idx in 1:length(sha_funcs)
    global nerrors

    ctx = sha_types[sha_funcs[sha_idx]]()
    SHA.update!(ctx, so_many_as_array[1:2*SHA.blocklen(typeof(ctx))])
    SHA.update!(ctx, so_many_as_array[2*SHA.blocklen(typeof(ctx))+1:end])
    hash = bytes2hex(SHA.digest!(ctx))
    if hash != answers[sha_funcs[sha_idx]][end]
        print("\n")
        @warn(
        """
        For $(describe_hash(sha_types[sha_funcs[sha_idx]])) expected:
            $(answers[sha_funcs[sha_idx]][end-1])
        Calculated:
            $(hash)
        """)
        nerrors += 1
    else
        VERBOSE && print(".")
    end
end
VERBOSE && println("Done! [$(nerrors - nerrors_old) errors]")

# Do another test on the "so many a's" data where we chunk up the data into
# three chunks, (sized appropriately to CAUSE overflow from one update to another)
# in order to test multiple update!() calls as well as the overflow codepaths
VERBOSE && print("Testing on one million a's (chunked clumsily)")
nerrors_old = nerrors
for sha_idx in 1:length(sha_funcs)
    global nerrors
    ctx = sha_types[sha_funcs[sha_idx]]()

    # Get indices awkwardly placed for the blocklength of this hash type
    idx0 = round(Int, 0.3*SHA.blocklen(typeof(ctx)))
    idx1 = round(Int, 1.7*SHA.blocklen(typeof(ctx)))
    idx2 = round(Int, 2.6*SHA.blocklen(typeof(ctx)))

    # Feed data in according to our dastardly blocking scheme
    SHA.update!(ctx, so_many_as_array[0      + 1:1*idx0])
    SHA.update!(ctx, so_many_as_array[1*idx0 + 1:2*idx0])
    SHA.update!(ctx, so_many_as_array[2*idx0 + 1:3*idx0])
    SHA.update!(ctx, so_many_as_array[3*idx0 + 1:4*idx0])
    SHA.update!(ctx, so_many_as_array[4*idx0 + 1:idx1])
    SHA.update!(ctx, so_many_as_array[idx1 + 1:idx2])
    SHA.update!(ctx, so_many_as_array[idx2 + 1:end])

    # Ensure the hash is the appropriate one
    hash = bytes2hex(SHA.digest!(ctx))
    if hash != answers[sha_funcs[sha_idx]][end]
        print("\n")
        @warn(
        """
        For $(describe_hash(sha_types[sha_funcs[sha_idx]])) expected:
            $(answers[sha_funcs[sha_idx]][end-1])
        Calculated:
            $(hash)
        """)
        nerrors += 1
    else
        VERBOSE && print(".")
    end
end
VERBOSE && println("Done! [$(nerrors - nerrors_old) errors]")

# test hmac correctness using the examples on [wiki](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code#Examples)
VERBOSE && print("Testing on the hmac functions")
nerrors_old = nerrors
for (key, msg, fun, hash) in (
    (b"", b"", hmac_sha1, "fbdb1d1b18aa6c08324b7d64b71fb76370690e1d"),
    (b"", b"", hmac_sha256, "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"),
    (b"key", b"The quick brown fox jumps over the lazy dog", hmac_sha1, "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"),
    (b"key", b"The quick brown fox jumps over the lazy dog", hmac_sha256, "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"),
)
    global nerrors
    digest1 = bytes2hex(fun(Vector(key), Vector(msg)))
    digest2 = bytes2hex(fun(Vector(key), IOBuffer(Vector(msg))))
    if digest1 != hash || digest2 != hash
        print("\n")
        @warn(
        """
        For $fun($(String(key)), $(String(msg))) expected:
            $hash
        Calculated:
            $digest1
            $digest2
        """)
        nerrors += 1
    else
        VERBOSE && print(".")
    end
end
VERBOSE && println("Done! [$(nerrors - nerrors_old) errors]")

replstr(x) = sprint((io, x) -> show(IOContext(io, :limit => true), MIME("text/plain"), x), x)

for idx in 1:length(ctxs)
    global nerrors
    # Part #1: copy
    VERBOSE && print("Testing copy function @ $(ctxs[idx]) ...")
    try
        copy(ctxs[idx]())
    catch
        print("\n")
        @warn("Some weird copy error happened with $(ctxs[idx])")
        nerrors += 1
    end
    VERBOSE && println("Done! [$(nerrors - nerrors_old) errors]")

    # Part #2: show
    VERBOSE && print("Testing show function @ $(ctxs[idx]) ...")
    if replstr(ctxs[idx]()) != shws[idx]
        print("\n")
        @warn("Some weird show error happened with $(ctxs[idx])")
        nerrors += 1
    end
    VERBOSE && println("Done! [$(nerrors - nerrors_old) errors]")
end

# test error if eltype of input is not UInt8
for f in sha_funcs
    global nerrors
    local data = UInt32[0x23467, 0x324775]
    try
        f(data)
    catch ex
        if ex isa MethodError &&
            ex.f === f &&
            ex.args === (data,)
            continue
        end
        rethrow()
    end
    @warn("Non-UInt8 Arrays should fail")
    nerrors += 1
end

# Clean up the I/O mess
rm(file)
rm(tempdir)

if nerrors == 0
    VERBOSE && println("ALL OK")
else
    println("Failed with $nerrors failures")
end
@test nerrors == 0

max_stars_repo_name: RelationalAI-oss/julia


text:
import BlockArrays: BlockSizes, BlockIndex, globalrange, nblocks, global2blockindex, blockindex2global

#=
[1,1  1,2] | [1,3  1,4  1,5]
--------------------------
[2,1  2,2] | [2,3  2,4  2,5]
[3,1  3,2] | [3,3  3,4  3,5]
----------------------------
[4,1  4,2] | [4,3  4,4  4,5]
[5,1  5,2] | [5,3  5,4  5,5]
[6,1  6,2] | [6,3  6,4  6,5]
=#

block_size = BlockSizes([1,2,3], [2, 3])

@testset "BlockSizes / BlockIndices" begin
@test nblocks(block_size) == (3,2)
@test nblocks(block_size, 1) == 3
@test nblocks(block_size, 2) == 2

@test @inferred(globalrange(block_size, (1,1))) == (1:1, 1:2)
@test @inferred(globalrange(block_size, (1,2))) == (1:1, 3:5)
@test @inferred(globalrange(block_size, (2,1))) == (2:3, 1:2)
@test @inferred(globalrange(block_size, (2,2))) == (2:3, 3:5)

# Test for allocations inside a function to avoid noise due to global
# variable references
wrapped_allocations = (bs, i) -> @allocated(globalrange(bs, i))
@test wrapped_allocations(block_size, (1, 1)) == 0

@test @inferred(global2blockindex(block_size, (3, 1))) == BlockIndex((2,1), (2,1))
@test @inferred(global2blockindex(block_size, (1, 4))) == BlockIndex((1,2), (1,2))
@test @inferred(global2blockindex(block_size, (4, 5))) == BlockIndex((3,2), (1,3))

wrapped_allocations = (bs, i) -> @allocated(global2blockindex(bs, i))
@test wrapped_allocations(block_size, (3, 1)) == 0

@test @inferred(blockindex2global(block_size, BlockIndex((2,1), (2,1)))) == (3, 1)
@test @inferred(blockindex2global(block_size, BlockIndex((1,2), (1,2)))) == (1, 4)
@test @inferred(blockindex2global(block_size, BlockIndex((3,2), (1,3)))) == (4, 5)

wrapped_allocations = (bs, i) -> @allocated(blockindex2global(bs, i))
@test wrapped_allocations(block_size, BlockIndex((2,1), (2,1))) == 0

@test block_size == BlockSizes(1:3, 2:3)

buf = IOBuffer()
print(buf, block_size)
@test String(take!(buf)) == "[1, 2, 3] × [2, 3]"

end


text:
using SharedArrays

abstract type Analysis end

pvalue(an::Analysis) = an.p
nperms(an::Analysis) = an.nperms
spotcheck(an::Analysis) = an.spotcheck

struct MIAnalysis <: Analysis
    lags::UnitRange{Int}
    nperms::Int
    p::Float64
    spotcheck::Int
    MIAnalysis(; lags=0:9, nperms=1000, p=0.05, spotcheck=1000) = new(lags, nperms, p, spotcheck)
end

params(mi::MIAnalysis) = mi.lags

function analyze(rng::AbstractRNG, mi::MIAnalysis,
                 xs::AbstractVector{Int}, ys::AbstractVector{Int},
                 lag::Int)
    significance(rng, MIDist(), mutualinfo!, xs[1:end-lag], ys[(lag+1):end];
                 nperms=nperms(mi), pvalue=pvalue(mi), spotcheck=spotcheck(mi))
end

struct TEAnalysis <: Analysis
    ks::UnitRange{Int}
    nperms::Int
    p::Float64
    spotcheck::Int
    TEAnalysis(; ks=1:9, nperms=1000, p=0.05, spotcheck=1000) = new(ks, nperms, p, spotcheck)
end

params(te::TEAnalysis) = te.ks

function analyze(rng::AbstractRNG, te::TEAnalysis,
                 xs::AbstractVector{Int}, ys::AbstractVector{Int},
                 k::Int)
    significance(rng, TEDist(k), transferentropy!, xs, ys;
                 nperms=nperms(te), pvalue=pvalue(te), spotcheck=spotcheck(te))
end

function analyze(rng::AbstractRNG, an::Analysis, binned::AbstractArray{Int,3})
    m, n, t = size(binned)
    allinfo = Array{Float64,4}[]
    for l in params(an)
        info = SharedArray{Float64,4}((m, n, m, n))
        @sync @distributed for a in 1:m*n
            i = (a - 1) % m + 1
            j = (a - 1) ÷ m + 1
            for u in 1:m, v in 1:n
                @views begin
                    value = analyze(rng, an, binned[i, j, :], binned[u, v, :], l)
                end
                info[i, j, u, v] = issig(value; p=pvalue(an)) ? first(value) : zero(Float64)
            end
        end
        push!(allinfo, Array(info))
    end
    allinfo
end

analyze(an::Analysis, binned::AbstractArray{Int,3}) = analyze(Random.GLOBAL_RNG, an, binned)

function analyze(an::Analysis, data::AbstractArray{Int,3},
                 parameters::Dict, pkey::Symbol, akey::Symbol,
                 videopath::String)
    runtime = (@elapsed allinfo = analyze(an, data))
    for (param, info) in zip(params(an), allinfo)
        data = merge(parameters, Dict(pkey => param))
        path = datadir("info", string(akey), savename(data, "bson"))

        data[akey] = info
        data[:runtime] = runtime
        data[:videopath] = videopath

        @tagsave path data safe=true
    end
end

max_stars_repo_name: ELIFE-ASU/dglmoore

max_issues_repo_name: ELIFE-ASU/dglmoore

max_forks_repo_name: ELIFE-ASU/dglmoore


text:
alpha = 0.85
accuracy = 0.00001
edgelist = "test/fixtures/gaps.adj"

rank = Rank{Float64,Int64}(alpha, accuracy, edgelist)
r = stationary_distribution(rank)
count = length(r)

iexpected = [1, 8, 3, 5, 7, 9]
expected  = [0.245344, 0.245344, 0.208173, 0.176404, 0.087356, 0.037375]
precision = 5

@assert isequal(floor(expected, precision), floor(r[iexpected], precision))


text:
"""
Arrays with fixed size and circular indexing.
"""
module CircularArrays

export CircularArray, CircularVector

"""
    CircularArray{T, N} <: AbstractArray{T, N}

`N`-dimensional array backed by an AbstractArray{T, N} with fixed size and circular indexing.

    array[index] == array[mod1(index, size)]
"""
struct CircularArray{T, N} <: AbstractArray{T, N}
    data::AbstractArray{T, N}
end

"""
    CircularVector{T} <: AbstractVector{T}

One-dimensional array backed by an AbstractArray{T, 1} with fixed size and circular indexing.
Alias for [`CircularArray{T,1}`](@ref).

    array[index] == array[mod1(index, size)]
"""
const CircularVector{T} = CircularArray{T, 1}

@inline clamp_bounds(arr::CircularArray, I::Tuple{Vararg{Int}})::AbstractArray{Int, 1} = map(dim -> mod1(I[dim], size(arr.data, dim)), eachindex(I))

CircularArray(def::T, size) where T = CircularArray(fill(def, size))

@inline Base.getindex(arr::CircularArray, i::Int) = @inbounds getindex(arr.data, mod1(i, size(arr.data, 1)))
@inline Base.setindex!(arr::CircularArray, v, i::Int) = @inbounds setindex!(arr.data, v, mod1(i, size(arr.data, 1)))
@inline Base.getindex(arr::CircularArray, I::Vararg{Int}) = @inbounds getindex(arr.data, clamp_bounds(arr, I)...)
@inline Base.setindex!(arr::CircularArray, v, I::Vararg{Int}) = @inbounds setindex!(arr.data, v, clamp_bounds(arr, I)...)
@inline Base.size(arr::CircularArray) = size(arr.data)

CircularVector(data::AbstractArray{T, 1}) where T = CircularVector{T}(data)
CircularVector(def::T, size::Int) where T = CircularVector{T}(fill(def, size))

Base.IndexStyle(::Type{<:CircularVector}) = IndexLinear()

end


text:
function log_beta(::Type{Beta}, arg0::jdouble, arg1::jdouble)
    return jcall(Beta, "logBeta", jdouble, (jdouble, jdouble), arg0, arg1)
end

function regularized_beta(::Type{Beta}, arg0::jdouble, arg1::jdouble, arg2::jdouble)
    return jcall(Beta, "regularizedBeta", jdouble, (jdouble, jdouble, jdouble), arg0, arg1, arg2)
end

function regularized_beta(::Type{Beta}, arg0::jdouble, arg1::jdouble, arg2::jdouble, arg3::jdouble)
    return jcall(Beta, "regularizedBeta", jdouble, (jdouble, jdouble, jdouble, jdouble), arg0, arg1, arg2, arg3)
end

function regularized_beta(::Type{Beta}, arg0::jdouble, arg1::jdouble, arg2::jdouble, arg3::jdouble, arg4::jint)
    return jcall(Beta, "regularizedBeta", jdouble, (jdouble, jdouble, jdouble, jdouble, jint), arg0, arg1, arg2, arg3, arg4)
end

function regularized_beta(::Type{Beta}, arg0::jdouble, arg1::jdouble, arg2::jdouble, arg3::jint)
    return jcall(Beta, "regularizedBeta", jdouble, (jdouble, jdouble, jdouble, jint), arg0, arg1, arg2, arg3)
end


text:
###################################################################
#  Legend related definitions & functions
###################################################################

config_legend_spec = Dict(
  :orient          => AbstractString,
  :title           => AbstractString,
  :format          => AbstractString,
  :shortTimeLabels => Bool,
  :values          => Vector
)

legend_help = """

- `orient` (`AbstractString`) : The orientation of the legend. One of "left" or "right". This determines how the legend is positioned within the scene. Default value: derived from legend config’s orient ("right" by default).
- `title` (`AbstractString`) : The title for the legend. Default value: derived from the field’s name and transformation function applied e.g, “field_name”, “SUM(field_name)”, “BIN(field_name)”, “YEAR(field_name)”.
- `format` (`AbstractString`) : The formatting pattern for axis labels. This is D3’s number format pattern for quantitative axis and D3’s time format pattern for time axis. Default value: derived from numberFormat config for quantitative axis and from timeFormat config for time axis.
- `shortTimeLabels` (`Bool`) : Whether month and day names should be abbreviated. Default value: derived from legend config’s shortTimeLabels (false by default).
- `values` (`Vector{AbstractString}`) : Explicitly set the visible legend values.
"""

########### helper function for encoding()  ########
"""
Sets legend properties for the `legend` argument within `encoding()` :

```julia
encoding_x(..., legend=legend(orient="left"), ...)
```

$legend_help
"""
legend(;properties...) = _mkdict(config_legend_spec, properties)

########### global level function ########
"""
Sets legend properties

`config_legend(;properties...)`

$legend_help
"""
config_legend(;properties...) = _mkvis((:config, :legend), config_legend_spec, properties)


text:
#  Copyright 2016,2017 Eric S. Tellez <eric.tellez@infotec.mx>
#
#    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.

export compute_distances, select_sss, select_tournament
using Random
"""
Computes the distances of `q` to the set of references `refs` (each index point to an item in `db`)
It returns an array of tuples `(distance, refID)`
"""
function compute_distances(dist::Function, db::AbstractVector{T}, refs::AbstractVector{Int}, q::T) where T
    [(dist(q, db[refs[refID]]), refID) for refID in 1:length(refs)]
end

"""
Computes the distances of `q` to the set of references `refs`
It returns an array of tuples `(distance, refID)`
"""
function compute_distances(dist::Function, refs::AbstractVector{T}, q::T) where T
    [(dist(q, ref), refID) for (refID, ref) in enumerate(refs)]
end

"""
select_tournament selects `numrefs` references from `db` using a tournament criterion; each
individual is selected among `tournamentsize` individuals.

It returns a set of pivots as a list of integers pointing to elements in `db`
"""
function select_tournament(dist::Function, db::AbstractVector{T}, numrefs::Int, tournamentsize::Int) where T
    refs = Vector{Int}()
    perm = 1:length(db) |> collect
    shuffle!(perm)
    push!(refs, perm[end])

    for i=1:(numrefs-1)
        sample = perm[(i-1)*tournamentsize+1:i*tournamentsize]
        distant = 0
        distantRef = 0
        for x in sample
            M = compute_distances(dist, db, refs, db[x])
            d, refID = minimum(M)
            if d > distant
                distant = d
                distantRef = x
            end
        end
        # println(sample, distant, distantRef)
        if distantRef > 0
            push!(refs, distantRef)
        end
    end

    return refs
end

"""
select_sss selects the necessary pivots to fulfill the SSS criterion using :param:alpha.
If :param:shuffle_db is true then the database is shuffled before the selection process; in any case,
the estimation of the maximum distance introduces indeterminism, however it could be too small.
If you need better a better random selection set :param:shuf as true

It returns a set of pivots as a list of integers pointing to elements in :param:db
"""
function select_sss(dist::Function, db::AbstractVector{T}, alpha::Float64; shuf::Bool=true) where T
    @info "select_sss: db=$(typeof(db)), alpha=$(alpha), distance=$(dist), shuf=$(shuf)"
    dmax::Float64 = 0.0
    s = Int(round(sqrt(length(db))/2))
    sample1, sample2 = rand(db, s), rand(db, s)
    dmax = maximum([dist(sample1[i], sample2[i]) for i=1:s])
    # plot(x=X, Geom.histogram(bincount=100))

    @info "the maximum distance estimated as $(dmax), now selecting pivots"
    xdb = Array(1:length(db))
    if shuf
        shuffle!(xdb)
    end
    #pivots::Array{T,1} = Array(T, 1)
    #pivots[1] = xdb[1]
    pivots = Int[xdb[1]]

    for i=2:length(xdb)
        obj = db[xdb[i]]
        if minimum([dist(db[pivID], obj) for pivID in pivots]) / dmax < alpha
            continue
        end

        push!(pivots, i)
    end

    return pivots
end


text:
using SymbolicRegression, SymbolicUtils

X = randn(Float32, 5, 100)
y = 2 * cos.(X[4, :]) + X[1, :] .^ 2 .- 2

options = SymbolicRegression.Options(;
    binary_operators=(+, *, /, -), unary_operators=(cos, exp), npopulations=20
)

hall_of_fame = EquationSearch(X, y; niterations=40, options=options, numprocs=4)

dominating = calculate_pareto_frontier(X, y, hall_of_fame, options)

eqn = node_to_symbolic(dominating[end].tree, options)
println(simplify(eqn * 5 + 3))

println("Complexity\tMSE\tEquation")

for member in dominating
    complexity = compute_complexity(member.tree, options)
    loss = member.loss
    string = string_tree(member.tree, options)

    println("$(complexity)\t$(loss)\t$(string)")
end


text:
# Defines streaming types and operators
abstract WallStreaming <: Streaming
abstract IOLetStreaming <: Streaming
immutable FluidStreaming <: Streaming; end
immutable NullStreaming <: Streaming; end
immutable HalfWayBounceBack <: Streaming; end
const NULLSTREAMER = NullStreaming()

# Do nothing when streaming to null, by default
streaming(::NullStreaming, args...) = nothing

# Overload to make unit-testing a bit easier
streaming(
    streamer::Streaming, quant::LocalQuantities, sim::Simulation,
    from::GridCoords, to::GridCoords, direction::Integer
) = streaming(streamer, quant, indexing(sim.indexing, from), indexing(sim.indexing, to), direction)
# Normal streaming from fluid to fluid
streaming(
    streamer::FluidStreaming, quantities::LocalQuantities, sim::Simulation,
    from::Integer, to::Integer, direction::Integer
) = streaming(streamer, sim, from, to, direction)
function streaming(::FluidStreaming, sim::Simulation, from::Integer, to::Integer, dir::Integer)
    # Replacing multi-dimensional getitem with hand-crafted version gains ~10% overall speed-up.
    # At least in this one case. Note that this one case is called very very often.
    const N = size(sim.next_populations, 1)
    @inbounds sim.next_populations[N * (to - 1) + dir] = sim.populations[N * (from - 1) + dir]
end

# Half-way bounce back streaming
streaming(
    streamer::HalfWayBounceBack, quantities::LocalQuantities, sim::Simulation,
    from::Integer, to::Integer, direction::Integer
) = streaming(streamer, sim, from, direction)
function streaming(::HalfWayBounceBack, sim::Simulation, from::Integer, direction::Integer)
    const invdir = sim.lattice.inversion[direction]
    sim.next_populations[invdir, from] = sim.populations[direction, from]
end


text:
using jlmie
using Plots

n = 3
# angular range
theta = range(0,2π,length=73) # per 5 degrees with length 73
mu = cos.(theta)
pin,taun = jlmie_pt(mu,n)
# show results
# validation can be done by comparing to ITMO Mie Calculator
# https://physics.itmo.ru/en/mie
plt = plot(theta, pin, proj=:polar,
    # xlabel       = "Wavelength (nm)",
    # ylabel       = "Scattering efficiency",
    # legend       = false,
    label        = "pi",
    # xlims        =(-3,3),
    # ylims        =(-3,3),
    # aspect_ratio =0.5,
    # title        ="TITLE",
    # linecolor    =:blue,
    # linewidth    =5,
    # linestyle    =:dot,
    # size         =(400,300),
) # https://qiita.com/I_ppp/items/dca3552affa6a672e4bd
plot!(theta, taun, proj=:polar,label="tau")
display(plt)

# save
if false
    runningfilename = splitext(splitpath(@__FILE__)[end])[1]
    outfilename = ".\\result\\" * runningfilename
    savefig(plt,outfilename)
    println("Graph has been saved in result directory")
end

max_stars_repo_name: Hinamoooon/jlmie

max_issues_repo_name: Hinamoooon/jlmie

max_forks_repo_name: Hinamoooon/jlmie


text:
# MIT License
#
# Copyright (c) 2018 Martin Biel
#
# 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.

# Affine decision function #
# ========================== #
struct AffineDecisionObjectiveBridge{T} <: MOIB.Objective.AbstractBridge
    decision_function::AffineDecisionFunction{T}
end

function MOIB.Objective.bridge_objective(::Type{AffineDecisionObjectiveBridge{T}}, model::MOI.ModelLike,
                                         f::AffineDecisionFunction{T}) where T
    # All decisions have been mapped to the variable part terms
    # at this point.
    F = MOI.ScalarAffineFunction{T}
    # Set the bridged objective
    MOI.set(model, MOI.ObjectiveFunction{F}(), MOI.ScalarAffineFunction(f.variable_part.terms, zero(T)))
    # Save decision function to allow modifications
    return AffineDecisionObjectiveBridge{T}(f)
end

function MOIB.Objective.supports_objective_function(
    ::Type{<:AffineDecisionObjectiveBridge}, ::Type{<:AffineDecisionFunction})
    return true
end
MOIB.added_constrained_variable_types(::Type{<:AffineDecisionObjectiveBridge}) = Tuple{DataType}[]
function MOIB.added_constraint_types(::Type{<:AffineDecisionObjectiveBridge})
    return Tuple{DataType, DataType}[]
end
function MOIB.set_objective_function_type(::Type{AffineDecisionObjectiveBridge{T}}) where T
    return MOI.ScalarAffineFunction{T}
end

function MOI.get(::AffineDecisionObjectiveBridge, ::MOI.NumberOfVariables)
    return 0
end

function MOI.get(::AffineDecisionObjectiveBridge, ::MOI.ListOfVariableIndices)
    return MOI.VariableIndex[]
end

function MOI.delete(::MOI.ModelLike, ::AffineDecisionObjectiveBridge)
    # Nothing to delete
    return nothing
end

function MOI.set(::MOI.ModelLike, ::MOI.ObjectiveSense,
                 ::AffineDecisionObjectiveBridge, ::MOI.OptimizationSense)
    # Nothing to handle if sense changes
    return nothing
end

function MOI.get(model::MOI.ModelLike,
                 attr::MOIB.ObjectiveFunctionValue{F},
                 bridge::AffineDecisionObjectiveBridge{T}) where {T, F <: AffineDecisionFunction{T}}
    f = bridge.decision_function
    G = MOI.ScalarAffineFunction{T}
    obj_val = MOI.get(model, MOIB.ObjectiveFunctionValue{G}(attr.result_index))
    # Calculate and add constant
    return obj_val + f.variable_part.constant
end

function MOI.get(model::MOI.ModelLike, attr::MOI.ObjectiveFunction{F},
                 bridge::AffineDecisionObjectiveBridge{T}) where {T, F <: AffineDecisionFunction{T}}
    return bridge.decision_function
end

function MOI.modify(model::MOI.ModelLike, bridge::AffineDecisionObjectiveBridge{T}, change::MOI.ScalarConstantChange) where T
    f = bridge.decision_function
    # Modify constant of variable part
    f.variable_part.constant = change.new_constant
    return nothing
end

function MOI.modify(model::MOI.ModelLike, bridge::AffineDecisionObjectiveBridge{T}, change::MOI.ScalarCoefficientChange) where T
    f = bridge.decision_function
    # Modify variable part of decision function
    modify_coefficient!(f.variable_part.terms, change.variable, change.new_coefficient)
    # Modify the variable part of the mapped objective as well
    F = MOI.ScalarAffineFunction{T}
    MOI.modify(model, MOI.ObjectiveFunction{F}(), change)
    return nothing
end


text:
"""
ДАНО: Робот - в произвольной клетке ограниченного прямоугольного поля, на котором могут находиться также внутренние прямоугольные перегородки (все перегородки изолированы друг от друга, прямоугольники могут вырождаться в отрезки)
РЕЗУЛЬТАТ: Робот - в исходном положении и в углах поля стоят маркеры
"""
function mark_4(r::Robot)
    steps=0
    arr_of_steps=[] #Массив
    while ((isborder(r,Sud))&&(isborder(r,West)))==false
        push!(arr_of_steps,moves!(r,West)) #Добавление элемента в конец массива
        push!(arr_of_steps,moves!(r,Sud))
        steps=steps+2
    end
    for side in (Nord,Ost,Sud,West)
        moves!(r,side)
        putmarker!(r)
    end
    while (steps>0)==true
        side=isodd(steps) ? Ost : Nord #Тернарный оператор
        for a in 1:arr_of_steps[steps]
            move!(r,side)
        end
        steps=steps-1
    end
end

function moves!(r::Robot,side::HorizonSide)
    num_steps=0
    while isborder(r,side)==false
        move!(r,side)
        num_steps=num_steps+1
    end
    return num_steps
end

max_stars_repo_name: alexgruzberg/mirea-progs

max_issues_repo_name: alexgruzberg/mirea-progs

max_forks_repo_name: alexgruzberg/mirea-progs


text:
# During handling of an execute_request (when execute_msg is !nothing),
# we redirect STDOUT and STDERR into "stream" messages sent to the IPython
# front-end.

# logging in verbose mode goes to original stdio streams.  Use macros
# so that we do not even evaluate the arguments in no-verbose modes
macro vprintln(x...)
    quote
        if verbose::Bool
            println(orig_STDOUT, $(x...))
        end
    end
end
macro verror_show(e, bt)
    quote
        if verbose::Bool
            showerror(orig_STDERR, $e, $bt)
        end
    end
end

function send_stream(s::String, name::String)
    if !isempty(s)
        send_ipython(publish,
                     msg_pub(execute_msg, "stream",
                             ["name" => name, "data" => s]))
    end
end

function watch_stream(rd::IO, name::String)
    try
        while !eof(rd) # blocks until something is available
            d = readbytes(rd, nb_available(rd))
            s = try
                bytestring(d)
            catch
                # FIXME: what should we do here?
                string("<ERROR: invalid UTF8 data ", d, ">")
            end
	    send_stream(s, name)
            sleep(0.1) # a little delay to accumulate output
        end
    catch e
        # the IPython manager may send us a SIGINT if the user
        # chooses to interrupt the kernel; don't crash on this
        if isa(e, InterruptException)
            watch_stream(rd, name)
        else
            rethrow()
        end
    end
end

# IJulia issue #42: there doesn't seem to be a good way to make a task
# that blocks until there is a read request from STDIN ... this makes
# it very hard to properly redirect all reads from STDIN to pyin messages.
# In the meantime, however, we can just hack it so that readline works:
import Base.readline
function readline(io::Base.Pipe)
    if io == STDIN
        if !execute_msg.content["allow_stdin"]
            error("IJulia: this front-end does not implement stdin")
        end
        send_ipython(raw_input,
                     msg_reply(execute_msg, "input_request",
                               ["prompt" => "STDIN> "]))
        while true
            msg = recv_ipython(raw_input)
            if msg.header["msg_type"] == "input_reply"
                return msg.content["value"]
            else
                error("IJulia error: unknown stdin reply")
            end
        end
    else
        invoke(readline, (Base.AsyncStream,), io)
    end
end

function watch_stdio()
    @async watch_stream(read_stdout, "stdout")
    @async watch_stream(read_stderr, "stderr")
end

import Base.flush
function flush(io::Base.Pipe)
    invoke(flush, (super(Base.Pipe),), io)
    # send any available bytes to IPython (don't use readavailable,
    # since we don't want to block).
    if io == STDOUT
        send_stream(takebuf_string(read_stdout.buffer), "stdout")
    elseif io == STDERR
        send_stream(takebuf_string(read_stderr.buffer), "stderr")
    end
end


text:
using CUDArt
import Base: isapprox

function isapprox(x, y;
                  maxeps::Real = max(eps(eltype(x)), eps(eltype(y))),
                  rtol::Real=maxeps^(1/3), atol::Real=maxeps^(1/2))
    size(x) == size(y) || (warn("isapprox: $(size(x))!=$(size(y))"); return false)
    isa(x, CudaArray) && (x = to_host(x))
    isa(y, CudaArray) && (y = to_host(y))
    d = abs(x-y)
    s = abs(x)+abs(y)
    all(d .< (atol + rtol * s))
end

max_stars_repo_name: denizyuret/KUDNN

max_issues_repo_name: denizyuret/KUDNN

max_forks_repo_name: denizyuret/KUDNN


text:
using Test
using TightBindingLattice

@testset "symmorphic" begin
    tsym = TranslationSymmetry([4 0; 0 4])
    psym = project(PointSymmetryDatabase.find("4mm"), [1 0 0; 0 1 0])
    @test_throws ArgumentError TranslationSymmetry([4 0; 0 3]) ⋊ psym
    @test_throws ArgumentError psym ⋊ tsym
    ssym = tsym ⋊ psym

    @test eltype(ssym) == SpaceOperation{Int, Int}
    @test valtype(ssym) == SpaceOperation{Int, Int}
    @test element(ssym, 2) == TranslationOperation([1, 0])  # equality between different types
    let els = elements(ssym)
        @test length(els) == 4 * 4 * group_order(psym)
        @test typeof(first(els)) == SpaceOperation{Int, Int}
    end

    @test element_name(ssym, 2) == "{ [1, 0] | 1 }"
    let els = element_names(ssym)
        @test length(els) == 4 * 4 * group_order(psym)
        @test typeof(first(els)) <: AbstractString
    end

    els = elements(ssym)
    let product = symmetry_product(ssym)
        @test all(
            let
                z1 = product(x, y)
                z2 = x * y
                z3 = SpaceOperation(z2.matrix, tsym.orthocube.wrap(z2.displacement)[2])
                z1 == z3
            end for x in els, y in els
        )
    end
    element_lookup = Dict(x => i for (i, x) in enumerate(elements(ssym)))

    @test group_order(ssym) == group_order(psym) * group_order(tsym)

    let
        mtab = zeros(Int, group_order(ssym), group_order(ssym))
        let product = symmetry_product(ssym)
            for (i, xi) in enumerate(els), (j, xj) in enumerate(els)
                xk = product(xi, xj)
                k = element_lookup[xk]
                mtab[i, j] = k
            end
        end
        G = group(ssym)
        @test G.multiplication_table == mtab
        @test group_multiplication_table(ssym) == mtab
    end

    gen_inds = generator_indices(ssym)
    gen_els = generator_elements(ssym)
    @test length(gen_inds) == length(generator_indices(tsym)) + length(generator_indices(psym))
    @test length(gen_els) == length(generator_indices(tsym)) + length(generator_indices(psym))

    # get_irrep_components(ssym)

    @testset "embedding" begin
        unitcell = make_unitcell([1.0 0.0; 0.0 1.0]; SiteType=String)
        addsite!(unitcell, "A", FractCoord([0, 0], [0.5, 0.0]))
        addsite!(unitcell, "B", FractCoord([0, 0], [0.0, 0.5]))
        lattice = make_lattice(unitcell, [4 0; 0 4])
        tsymbed = embed(lattice, tsym)
        psymbed = embed(lattice, psym)

        ssym = tsym ⋊ psym
        ssym2 = psym ⋉ tsym

        @test ssym == ssym2

        ssymbed1 = embed(lattice, ssym)
        ssymbed2 = tsymbed ⋊ psymbed
        ssymbed3 = psymbed ⋉ tsymbed
        ssymbed4 = SymmorphicSymmetryEmbedding(tsymbed, psymbed)
        @test_throws ArgumentError SymmorphicSymmetryEmbedding(psymbed, tsymbed)
        @test_throws ArgumentError SymmorphicSymmetryEmbedding(make_lattice(unitcell, [4 0; 0 3]), ssym)

        let lattice2 = make_lattice(unitcell, [4 0; 0 3])
            tsymbed2 = translation_symmetry_embedding(lattice2)
            @test_throws ArgumentError tsymbed2 ⋊ psymbed
        end

        @test typeof(ssymbed1) == typeof(ssymbed2)
        @test eltype(ssymbed1) == SitePermutation
        @test eltype(ssymbed2) == SitePermutation
        @test valtype(ssymbed1) == SitePermutation
        @test valtype(ssymbed2) == SitePermutation

        @test ssymbed1 == ssymbed2 == ssymbed3 == ssymbed4

        @test ssymbed1.lattice == lattice
        @test ssymbed1.normal.symmetry == tsymbed.symmetry
        @test ssymbed1.rest.symmetry == psymbed.symmetry

        @test ssymbed2.lattice == lattice
        @test ssymbed2.normal.symmetry == tsymbed.symmetry
        @test ssymbed2.rest.symmetry == psymbed.symmetry

        tsic1 = first(get_irrep_components(tsymbed))
        psic1 = first(get_irrep_components(psymbed))
        SymmorphicIrrepComponent(tsic1, psic1)

        let lattice2 = make_lattice(unitcell, [4 0; 0 3])
            tsymbed2 = translation_symmetry_embedding(lattice2)
            tsic2 = first(get_irrep_components(tsymbed2))
            @test_throws ArgumentError SymmorphicIrrepComponent(tsic2, psic1)
        end

        count = 0
        for tsic in get_irrep_components(tsymbed)
            psymbed_little = little_symmetry(tsic, psymbed)
            for psic in get_irrep_components(psymbed_little)
                count += 1
            end
        end
        @test count == length(collect(get_irrep_components(ssymbed1)))
        @test all(isa(ssic.normal, IrrepComponent{SymmetryEmbedding{TranslationSymmetry}})
                      for ssic in get_irrep_components(ssymbed1))
    end
    @testset "fractional_momentum" begin
        unitcell = make_unitcell([1.0 0.0; 0.0 1.0]; SiteType=String)
        addsite!(unitcell, "A", FractCoord([0, 0], [0.5, 0.0]))
        addsite!(unitcell, "B", FractCoord([0, 0], [0.0, 0.5]))
        lattice = make_lattice(unitcell, [4 0; 0 4])
        tsymbed = embed(lattice, tsym)
        psymbed = embed(lattice, psym)
        ssymbed = tsymbed ⋊ psymbed

        tsym = symmetry(tsymbed)
        psym = symmetry(psymbed)
        ssym = tsym ⋊ psym

        kf = tsym.fractional_momenta
        @test all(
            let tidx = tsic.irrep_index
                kf[tidx] ==
                fractional_momentum(tsym, tidx) ==
                fractional_momentum(ssym, tidx) ==
                fractional_momentum(tsymbed, tidx) ==
                fractional_momentum(ssymbed, tidx)
            end
            for tsic in get_irrep_components(tsymbed)
        )
    end
end


text:
#
# Create functions if a string is passed as summary_statistic
#
function build_summary_statistic(summary_statistic_string::String)

    if summary_statistic_string == "mean"
        return mean_summary_statistic
    elseif summary_statistic_string == "variance"
        return var_summary_statistic
    elseif summary_statistic_string == "max"
        return max_summary_statistic
    elseif summary_statistic_string == "min"
        return min_summary_statistic
    elseif summary_statistic_string == "range"
        return range_summary_statistic
    elseif summary_statistic_string == "median"
        return median_summary_statistic
    elseif summary_statistic_string == "q1"
        return q1_summary_statistic
    elseif summary_statistic_string == "q3"
        return q3_summary_statistic
    elseif summary_statistic_string == "iqr"
        return iqr_summary_statistic
    elseif summary_statistic_string == "keep_all"
        return keep_all_summary_statistic
    else
        error("$(summary_statistic_string) is not a valid summary statistic")
    end

end

function build_summary_statistic(summary_statistic_strings::Vector{String})
    function summary_statistic(data)
        sum_stat_funcs = [build_summary_statistic(sum_stat) for sum_stat in summary_statistic_strings]
        out = [func(data) for func in sum_stat_funcs]
        return vcat(out...)
    end
    return summary_statistic
end

#
# Check a user-defined summary statistic function
#
function build_summary_statistic(summary_statistic_func::Function)
    # Check output shape is right
    test_output = summary_statistic_func(rand(3,100))

    if ndims(test_output) != 1
        error("The summary statistic function provided does not return a 1D array")
    end

    return summary_statistic_func
end

#
# Built-in summary statistics. Data should be in the format returned by
# DifferentialEquations.solve i.e. an array with size (n_trajectories, n_time_points)
#

# Mean of each trajectory
function mean_summary_statistic(data::AbstractArray{Float64,2})
    return mean(data, dims=2)[:]
end

# Variance of each trajectory
function var_summary_statistic(data::AbstractArray{Float64,2})
    return var(data, dims=2)[:]
end

# Max of each trajectory
function max_summary_statistic(data::AbstractArray{Float64,2})
    return maximum(data, dims=2)[:]
end

# Min of each trajectory
function min_summary_statistic(data::AbstractArray{Float64,2})
    return minimum(data, dims=2)[:]
end

# Range of each trajectory
function range_summary_statistic(data::AbstractArray{Float64,2})
    return max_summary_statistic(data) - min_summary_statistic(data)
end

# Median of each trajectory
function median_summary_statistic(data::AbstractArray{Float64,2})
    return median(data, dims=2)[:]
end

# First quartile of each trajectory
function q1_summary_statistic(data::AbstractArray{Float64,2})
    return [quantile(data[i,:], 0.25) for i = 1:size(data,1)]
end

# Third quartile of each trajectory
function q3_summary_statistic(data::AbstractArray{Float64,2})
    return [quantile(data[i,:], 0.75) for i = 1:size(data,1)]
end

# Inter-quartile range of each trajectory
function iqr_summary_statistic(data::AbstractArray{Float64,2})
    return q3_summary_statistic(data) - q1_summary_statistic(data)
end

# Keep all the data from all the trajectoriess (in a single 1d array)
function keep_all_summary_statistic(data::AbstractArray{Float64,2})
    return reshape(data, prod(size(data)))
end


text:
using Test

for submodule in [
                  "FiniteDifferenceGrids",
                  "DomainDecomp",
                  "StateVecs",
                  "TDMA",
                  "PDEs",
                  # "BOMEX",
                  ]

  println("Testing $submodule")
  include(joinpath(submodule*".jl"))
end

max_stars_repo_name: akshaysridhar/CLIMA

max_issues_repo_name: akshaysridhar/CLIMA

max_forks_repo_name: akshaysridhar/CLIMA


text:
include("qstates/mpsstate.jl")
export  MPSState,
		getindex,
		getinds,
		setindex!,
		length,
		size,
		iterate,
		copy,
		isapprox,
		siteForQubit,
		sitesForQubits,
		qubitAtSite,
		qubitsAtSites,
		updateMap!,
		updateLims!,
		getQubit,
		getQubits,
		siteIndex,
		siteInds,
		toExactState,
		normalize!,
		measure!,
		orderQubits!,
		moveQubit!,
		localizeQubitsInOrder!,
		centerAtSite!,
		centerAtQubit!,
		swapSites!,
		oneShot,
		collapse!,
		dag,
		showStructure,
		showData,
		ρ

include("qstates/exactstate.jl")
export  ExactState,
		copy,
		isapprox,
		numQubits,
		toMPSState,
		ρ
include("inter_qstate_qgate/exactstate_qgate.jl")
export apply!

include("qgates/constgate.jl")
export ConstGate


text:
"""
    factorial_iterative(n)

Finds factorial of a number using Iterative method

# Example
```julia
factorial_iterative(5)      # returns 120
factorial_iterative(-1)     # returns error
```
# Reference
- factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial

Contributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)
"""
function factorial_iterative(n::N) where {N<:Integer}
    if n < 0
        throw(
            error(
                "factorial_iterative() only accepts non-negative integral values",
            ),
        )
    end
    if n == 0 || n == 1
        return one(BigInt)
    end
    return n * factorial_iterative(n - 1)
end

"""
    factorial_recursive(n)

Finds factorial of anumber using recursive method

# Example
```julia
factorial_recursive(5)      # returns 120
```
# Reference
- factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial

Contributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)
"""
function factorial_recursive(n::N)::BigInt where {N<:Integer}
    if n < 0
        throw(
            error(
                "factorial_iterative() only accepts non-negative integral values",
            ),
        )
    end
    if n == 0 || n == 1
        return one(BigInt)
        # keep same result type
    else
        factorial = one(BigInt)
        for i in 1:n
            factorial *= i
        end
        return factorial
    end
end

max_stars_repo_name: AugustoCL/Julia

max_issues_repo_name: AugustoCL/Julia

max_forks_repo_name: AugustoCL/Julia


text:
"""
Plots the photonic dispersion of the multilayer structure processed using PyPlot, PlotUtils and LaTeXStrings.
See examples folder for more details.
"""

using PyPlot, PlotUtils, LaTeXStrings
using Printf: @sprintf

function pbgplot(λ::AbstractArray{T1,N1}, θ::AbstractArray{T2,N2}, d::AbstractArray{T3,N3}, Rp::AbstractArray{T1,N4}, Rs::AbstractArray{T1,N4}, kblochp::AbstractArray{T5,N5}, kblochs::AbstractArray{T5,N5}) where {T1<:Number, N1, T2<:Number, N2, T3<:Float64, N3, N4, T5<:ComplexF64, N5}

    nθ = lastindex(θ)

    # periodicity
    Λ = d[1] + d[2]

    # frequency range normalized
    ω = Λ ./ λ

    # kbloch for one angle only
    temp0 = Λ ./ π
    kblochs = kblochs .* temp0
    kblochp = kblochp .* temp0

    # k normalized for angle-frequency dependence
    # logical matrices, used to select points which belong to the forbidden bands
    # maskp = abs.(kblochp) .>= 1.
    # masks = abs.(kblochs) .>= 1.
    maskp = imag.(kblochp) .== 0.
    masks = imag.(kblochs) .== 0.
    κp = deepcopy(kblochp)
    κp[.!maskp] .= 1.
    κp[maskp] .= 0.
    κs = deepcopy(kblochs)
    κs[.!masks] .= 1.
    κs[masks] .= 0.
    # parallel wavevector qz
    qz = sin.(deg2rad.(θ))
    # choose better colormap
    cmp = ColorMap(get_cmap("Blues"))
    cms = ColorMap(get_cmap("Reds"))

    if nθ == 1
        figure()
        title("p/TM-wave")
        subplot(2,2,1),plot(Rp, ω, linestyle="-",color="#386cb0")
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel("Reflectance")
        subplot(2,2,2),plot(real.(kblochp), ω, linestyle="-",color="#66a61e")
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel(L"K^{r}_{Bloch}\Lambda/\pi")
        subplot(2,2,3),plot(Rp, ω,linestyle="-",color="#386cb0")
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel("Reflectance")
        subplot(2,2,4),plot(abs.(imag.(kblochp)), ω,linestyle="-",color="#e41a1c")
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel(L"K^{i}_{Bloch}\Lambda/\pi")
        figure()
        title("s/TE-wave")
        subplot(2,2,1),plot(Rs, ω,linestyle="-",color="#386cb0")
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel("Reflectance")
        subplot(2,2,2),plot(real.(kblochs), ω, linestyle="-",color="#66a61e")
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel(L"K^{r}_{Bloch}\Lambda/\pi")
        subplot(2,2,3),plot(Rs, ω, linestyle="-",color="#386cb0")
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel("Reflectance")
        subplot(2,2,4),plot(abs.(imag.(kblochs)), ω, linestyle="-",color="#e41a1c")
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel(L"K^{i}_{Bloch}\Lambda/\pi")
    else
        figure()
        title("p/TM-wave")
        contourf(qz, ω, κp, 60, cmap = cmp, alpha = 0.7)
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel(L"K_{Bloch}\Lambda/\pi")
        # shading flat
        figure()
        title("s/TE-wave")
        contourf(qz, ω, κs, 60, cmap = cms, alpha = 0.7)
        ylabel(L"\omega\Lambda/(2\pi)")
        xlabel(L"K_{Bloch}\Lambda/\pi")
    end

end # function pbgplot(...)


text:
using Documenter, PolygonOps

makedocs(;
    modules=[PolygonOps],
    format=Documenter.HTML(),
    pages=[
        "Home" => "index.md",
    ],
    repo="https://github.com/JuliaGeometry/PolygonOps.jl/blob/{commit}{path}#L{line}",
    sitename="PolygonOps.jl",
    authors="steve <kd2cca@gmail.com>")

deploydocs(;
    repo="github.com/JuliaGeometry/PolygonOps.jl",
)


text:
try Pkg.clone("https://github.com/zsunberg/Powseeker.jl") end
using POMDPs
using Powseeker

Pkg.add("Reel");            using Reel
Pkg.add("POMDPToolbox");    using POMDPToolbox
Pkg.add("ParticleFilters"); using ParticleFilters
Pkg.add("Plots");           using Plots
Pkg.add("GR");

pomdp = PowseekerPOMDP()
filter = SIRParticleFilter(pomdp, 10_000, rng=MersenneTwister(7))
policy = RandomlyCheckGPS(Topout(pomdp, 0.1), 0.2, MersenneTwister(12))

sim = HistoryRecorder(rng=MersenneTwister(94), max_steps=60, show_progress=true)
hist = simulate(sim, pomdp, policy, filter)

gr()
frames = Frames(MIME("image/png"), fps=2)
for i in 1:length(hist)
    v = view(hist, 1:i)
    plot(pomdp, xlim=(-4000,4000), ylim=(-4000,4000), aspect_ratio=:equal)
    plt = plot!(v)
    push!(frames, plt);
    print(".")
end
println()
write("out.gif", frames);


text:
########################
# Duality
########################

"Supertype of trait types which define a kind of duality."
abstract type DualType end

"Orthogonal dual type."
struct OrthogonalDual <: DualType end

"Return the dictionary dual to the given dictionary with the given measure."
dual(dict::Dictionary, measure = measure(dict); options...) =
    dual(OrthogonalDual(), dict, measure; options...)

# dual(dict::Dictionary, measure::Measure=measure(dict); dualtype=gramdual, options...) =
    # dualtype(dict, measure; options...)

dual(::OrthogonalDual, dict, measure; options...) = gramdual(dict, measure; options...)

gramdual(dict::Dictionary, measure::Measure; options...) =
    default_gramdual(dict, measure; options...)

function default_gramdual(dict::Dictionary, measure::Measure; options...)
    try
        conj(inv(gram(dict, measure; options...))) * dict
    catch DimensionMismatch
        @warn "Convert DictionaryOperator to dense ArrayOperator"
        ArrayOperator(inv(conj(Matrix(gram(dict, measure; options...)))),dict,dict) * dict
    end
end


text:
facts("Pointer") do
    context("constructor") do
        pointer = WordNet.Pointer("s", 123, 'v', "1234")

        @fact pointer.sym    --> "s"
        @fact pointer.offset --> 123
        @fact pointer.pos    --> 'v'
        @fact pointer.source --> "12"
        @fact pointer.target --> "34"
    end

    context("is not semantic for non-0") do
        ptr = WordNet.Pointer("s", 123, 'v', "1234")
        @fact WordNet.is_semantic(ptr) --> false
    end

    context("is semantic for all-0") do
        ptr = WordNet.Pointer("s", 123, 'v', "0000")
        @fact WordNet.is_semantic(ptr) --> true
    end
end


text:
function extendedsqrt(x)
    try sqrt(x)
    catch
        if x isa Number
            sqrt(complex(x, 0))
        else
            throw(DomainError())
        end
    end
end

@show extendedsqrt(1)   # 1
@show extendedsqrt(-1)  # 0.0 + 1.0im
@show extendedsqrt('x') # ERROR: DomainError

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
# table_modes

const table_modes = Dict(
    :markdown => TableMode(:markdown; corner_corner = '|', header_fillchar = '-'),
    :grid => TableMode(:grid; corner_corner = '+', header_fillchar = '='),
)

display_style = Dict(
    :table_mode => table_modes[:markdown],
    :prepend_newline => false,
)

function set_table_mode(mode::Symbol)
    display_style[:table_mode] = table_modes[mode]
end


text:
using SMC, Base.Test
srand(125)

## Linear Gaussian

dx, dy = 5, 3
A = randn(dx,dx); A /= 0.9norm(A)
B = randn(dy,dx); B /= 1.1norm(B)
Q = randn(dx,dx); Q *= Q'; Q += 0.5*eye(dx); Q += Q'; Q /= 5
R = randn(dy,dy); R *= R'; R += 0.5*eye(dy); R += R'; R /= 20

lg  = LinearGaussian(A,B,Q,R)
hmm = HMM(lg)
x0  = randn(dx)

K = 50
N = 150
(states, observations) = generate(lg, x0, K)

srand(155)
@time (psf, ess) = particlefilter(hmm, observations, N, bootstrapprop(lg))

@test length(psf)==K

pfm  = mean(psf)
pfmm = zeros(dx,K)
for k in 1:K
    pfmm[:,k] = pfm[k]
end

@test norm(pfmm-states)/norm(states) < 0.4
println("PF    : $(norm(pfmm-states)/norm(states))")

srand(521)
@time psffbs  = particlesmoother_ffbs(hmm, psf)

@test length(psffbs)==K

psm  = mean(psffbs)
psmm = zeros(dx,K)
for k in 1:K
    psmm[:,k] = psm[k]
end

@test norm(psmm-states)/norm(states) < 0.25
println("PSFFBS: $(norm(psmm-states)/norm(states))")

srand(521)
@time (psbbis, ess) = particlesmoother_bbis(hmm, observations,
                                        psf, bootstrapprop(lg))

psm3  = mean(psbbis)
psmm3 = zeros(dx,K)
for k in 1:K
    psmm3[:,k] = psm3[k]
end

@test norm(psmm3-states)/norm(states) < 0.23
println("PSBISQ: $(norm(psmm3-states)/norm(states))")

srand(521)
@time (pslbbis, ess) = particlesmoother_lbbis(hmm, observations,
                                              psf, bootstrapprop(lg))

psm4  = mean(pslbbis)
psmm4 = zeros(dx,K)
for k in 1:K
    psmm4[:,k] = psm4[k]
end

@test norm(psmm4-states)/norm(states) < 0.23
println("PSBISL: $(norm(psmm4-states)/norm(states))")

srand(521)
@time (psllbbis, ess) = particlesmoother_llbbis(hmm, observations, psf, 25,
                                                bootstrapprop(lg))

psm5  = mean(psllbbis)
psmm5 = zeros(dx,K)
for k in 1:K
    psmm5[:,k] = psm5[k]
end

@test norm(psmm5-states)/norm(states) < 0.23
println("PSBISLL: $(norm(psmm5-states)/norm(states))")


text:
export replace_codeblocks

"""
    replace_codeblocks(path::AbstractString)
    replace_codeblocks(file::File)
    replace_codeblocks(dir::Dir)

Replaces Pandoc style code block fences with AsciiDoc style code fences.
So replaces code like this:

    ~~~
    x  = 10
    ~~~

With this style:

    [source,julia]
    ----
    x  = 10
    ----
"""
replace_codeblocks(path::AbstractString) = replace_codeblocks(Path(path))

function replace_codeblocks(file::File)
    out = IOBuffer()
    lineno = 0
    open(file.path) do io
        while !eof(io)
            s = readuntil(io, "~~~\n")
            print(out, s)
            lineno += count(==('\n'), s)

            if eof(io)
                break
            end

            println(out, "[source,julia]\n----")
            lineno += 1
            s = readuntil(io, "~~~")
            print(out, s)
            lineno += count(==('\n'), s)

            print(out, "----")
        end
    end
    seekstart(out)
    s = read(out, String)
    close(out)
    open(file.path, "w") do io
        write(io, s)
    end
end

replace_codeblocks(dir::Dir) = visitdir(replace_codeblocks, dir.path)

max_stars_repo_name: ordovician/AsciiDocTools

max_issues_repo_name: ordovician/AsciiDocTools

max_forks_repo_name: ordovician/AsciiDocTools


text:
struct VirtualOffset
    x::UInt64
end

Base.convert(::Type{VirtualOffset}, x::UInt64) = VirtualOffset(x)
Base.convert(::Type{UInt64}, x::VirtualOffset) = x.x

"""
    VirtualOffset(block_offset::Integer, inblock_offset::Integer)

Create a virtual file offset from `block_offset` and `inblock_offset`.
Get the two offsets with `offsets(v)`.

`block_offset` is an offset pointing to the beginning position of a BGZF block
in a BGZF file and `inblock_offset` is an offset pointing to the begining
position of a binary data within a uncompressed BGZF block. These values are
zero-based and their valid ranges are [0, 1 << 48) and [0, 1 << 16),
respectively.
"""
function VirtualOffset(block_offset::Integer, inblock_offset::Integer)
    if !(0 ≤ block_offset < (1 << 48))
        throw(ArgumentError("block file offset must be in [0, $(1 << 48))"))
    elseif !(0 ≤ inblock_offset < (1 << 16))
        throw(ArgumentError("in-block offset must be in [0, $(1 << 16))"))
    end
    return VirtualOffset((UInt64(block_offset) << 16) | UInt64(inblock_offset))
end

Base.isless(x::VirtualOffset, y::VirtualOffset) = isless(x.x, y.x)

# NOTE: This doesn't check the valid range of virtual offset.
Base.:+(voffset::VirtualOffset, x::Integer) = VirtualOffset(voffset.x + UInt64(x))
Base.getindex(voffset::VirtualOffset, i::Integer) = offsets(voffset)[i]

offsets(x::VirtualOffset) = (x.x >>> 16, x.x & 0xffff)

function Base.show(io::IO, x::VirtualOffset)
    v, o = offsets(x)
    print(io, summary(x), '(', v, ", ", o, ')')
end

Base.read(io::IO, ::Type{VirtualOffset}) = VirtualOffset(read(io, UInt64))
Base.write(io::IO, voffset::VirtualOffset) = write(io, voffset.x)