text:
function translate_exported_functions(code)
    println("# NOTE: This file contains machine-generated code by $(basename(@__FILE__)).\n")
    e = 0
    while (s = findnext("HTSLIB_EXPORT", code, e + 1)) !== nothing
        e = findnext(';', code, last(s) + 1)
        @assert !isnothing(e)
        decl = code[last(s)+1:e]
        println("# ", lstrip(replace(decl, r"\s+" => ' ')))
        try
            buf = IOBuffer()
            (rettype, funcname), next = translate_type_and_name(decl, 1, argument = false)
            print(buf, "@defun $(funcname)(")
            @assert !isnothing(next)
            @assert next[1][1] == :lparen
            arguments = String[]
            unnamed = 0
            while !isnothing(next) && next[1][1] != :rparen
                (argtype, argname), next = translate_type_and_name(decl, next[2][1], argument = true)
                if argname ∈ ("end",)
                    argname = string(argname, '_')
                end
                if isempty(argname)
                    unnamed += 1
                end
                push!(arguments, "$(argname)::$(argtype)")
            end
            if length(arguments) == 1 && arguments[1] == "::Cvoid"
                unnamed = 0
                empty!(arguments)
            end
            if unnamed > 0
                error("found unnamed argument(s)")
            end
            print(buf, join(arguments, ", "))
            println(buf, ")::$(rettype)")
            println(String(take!(buf)))
        catch ex
            println("# ", ex)
            println()
        end
    end
end

function translate_type_and_name(code, i; argument)
    token, i = nexttoken(code, i)
    isconst = false
    if token == (:keyword, "const")
        isconst = true
        token, i = nexttoken(code, i)
    end
    if token == (:keyword, "struct") || token == (:keyword, "enum")
        token, i = nexttoken(code, i)
    end
    if token == (:keyword, "signed") || token == (:keyword, "unsigned") || token == (:keyword, "long")
        next = nexttoken(code, i)
        if next[1][1] == :keyword
            typename = "$(token[2]) $(next[1][2])"
            token, i = next
        else
            typename = token[2]
        end
    else
        typename = token[2]
    end
    token, i = nexttoken(code, i)
    if isconst && typename == "char" && token[1] == :asterisk
        type = "Cstring"
        token, i = nexttoken(code, i)
    else
        type = typemap(typename)
    end
    while token[1] == :asterisk
        #type = argument ? "Ref{$(type)}" : "Ptr{$(type)}"
        type = "Ptr{$(type)}"
        token, i = nexttoken(code, i)
    end
    if argument && token[1] == :lparen
        error("function pointer?")
    elseif argument && token[1] != :ident
        return (type, ""), (token, i)
    else
        name = token[2]
        #return (type, token[2]), nexttoken(code, i)
        token, i = nexttoken(code, i)
        if token[1] == :lbracket
            token, i = nexttoken(code, i)
            if token[1] == :integer
                token, i = nexttoken(code, i)
            end
            #type = argument ? "Ref{$(type)}" : "Ptr{$(type)}"
            type = "Ptr{$(type)}"
            return (type, name), nexttoken(code, i)
        else
            return (type, name), (token, i)
        end
    end
end

const TYPEMAP = Dict(
    "void" => "Cvoid",
    "char" => "Cchar",
    "unsigned char" => "Cuchar",
    "short" => "Cshort",
    "unsigned short" => "Cushort",
    "int" => "Cint",
    "unsigned int" => "Cuint",
    "long" => "Clong",
    "unsigned long" => "Culong",
    "long long" => "Clonglong",
    "unsigned long long" => "Culonglong",
    "size_t" => "Csize_t",
    "ssize_t" => "Cssize_t",
    "off_t" => "Coff_t",  # not defined in the standard library
    "float" => "Cfloat",
    "double" => "Cdouble",
)
for n in [8, 16, 32, 64]
    TYPEMAP["int$(n)_t"] = "Int$(n)"
    TYPEMAP["uint$(n)_t"] = "UInt$(n)"
end
typemap(ctype) = get(TYPEMAP, ctype, ctype)

isfirst(c) = 'A' ≤ c ≤ 'Z' || 'a' ≤ c ≤ 'z' || c == '_'
iscont(c) = isfirst(c) || '0' ≤ c ≤ '9'

iskeyword(word) = word ∈ ("void", "char", "short", "int", "long", "float", "double", "struct", "enum", "union", "signed", "unsigned", "const")

function nexttoken(code, i = 1)
    # skip whitespace
    next = iterate(code, i)
    while !isnothing(next) && isspace(next[1])
        next = iterate(code, next[2])
    end
    isnothing(next) && return

    c, i = next
    if c == '*'
        return (:asterisk, "*"), i
    elseif c == ','
        return (:comma, ","), i
    elseif c == '('
        return (:lparen, "("), i
    elseif c == ')'
        return (:rparen, ")"), i
    elseif c == '['
        return (:lbracket, "["), i
    elseif c == ']'
        return (:rbracket, "]"), i
    elseif c == ';'
        return (:semicolon, ";"), i
    elseif isdigit(c)
        s = prevind(code, i)
        next = iterate(code, i)
        while !isnothing(next) && isdigit(next[1])
            i = next[2]
            next = iterate(code, i)
        end
        int = code[s:prevind(code, i)]
        return (:integer, int), i
    elseif isfirst(c)
        s = prevind(code, i)
        next = iterate(code, i)
        while !isnothing(next) && iscont(next[1])
            i = next[2]
            next = iterate(code, i)
        end
        word = code[s:prevind(code, i)]
        return (iskeyword(word) ? :keyword : :ident, word), i
    else
        error("unknown token: $(repr(c))")
    end
end

translate_exported_functions(read(stdin, String))


text:
_groupby(f, d::AbstractDataset, args...; kwargs...) =
    IndexedTables.groupby(f, d, args...; usekey = true, kwargs...)

_groupby(f, args...; kwargs...) = d::AbstractDataset -> _groupby(f, d, args...; kwargs...)

function groupby_helper(args...)
    anon_func, syms = extract_anonymous_function(last(args), replace_column, usekey = true)
    if !isempty(syms) && !(:(_) in syms)
        fields = Expr(:call, :(JuliaDBMeta.distinct_tuple), syms...)
        Expr(:call, :(JuliaDBMeta._groupby), anon_func, Expr(:kw, :select, fields), replace_keywords(args[1:end-1])...)
    else
        Expr(:call, :(JuliaDBMeta._groupby), anon_func, replace_keywords(args[1:end-1])...)
    end
end

"""
`@groupby(d, by, x)`

Group data and apply some summary function to it.
Symbols in expression `x` are replaced by the respective column in `d`. In this context,
`_` refers to the whole table `d`. To use actual symbols, escape them with `^`, as in `^(:a)`.

The second argument is optional (defaults to `Keys()`) and specifies on which column(s) to group.
The `key` column(s) can be accessed with `_.key`.
Use `{}` syntax for automatically named `NamedTuples`.
Use `cols(c)` to refer to column `c` where `c` is a variable that evaluates to a symbol. `c` must be available in
the scope where the macro is called.

## Examples

```jldoctest groupby
julia> t = table([1,2,1,2], [4,5,6,7], [0.1, 0.2, 0.3,0.4], names = [:x, :y, :z]);

julia> @groupby t :x {maximum(:y - :z)}
Table with 2 rows, 2 columns:
x  maximum(y - z)
─────────────────
1  5.7
2  6.6

julia> @groupby t :x {m = maximum(:y - :z)/_.key.x}
Table with 2 rows, 2 columns:
x  m
──────
1  5.7
2  3.3
```

When the summary function returns an iterable, use `flatten=true` to flatten the result:

```jldoctest groupby
julia> @groupby(t, :x, flatten = true, select = {:y+1})
Table with 4 rows, 2 columns:
x  y + 1
────────
1  5
1  7
2  6
2  8
```
"""
macro groupby(args...)
    esc(groupby_helper(args...))
end

ext: jl


text:
# !INPUT/OUTPUT PARAMETERS:
#   sol  : speed of light in atomic units (in,real)
#   n    : principal quantum number (in,integer)
#   l    : quantum number l (in,integer)
#   k    : quantum number k (l or l+1) (in,integer)
#   nr   : number of radial mesh points (in,integer)
#   r    : radial mesh (in,real(nr))
#   vr   : potential on radial mesh (in,real(nr))
#   evals : eigenvalue without rest-mass energy (inout,real)
#   g0   : major component of the radial wavefunction (out,real(nr))
#   f0   : minor component of the radial wavefunction (out,real(nr))
# !DESCRIPTION:
#   Finds the solution to the radial Dirac equation for a given potential $v(r)$
#   and quantum numbers $n$, $k$ and $l$. The method involves integrating the
#   equation using the predictor-corrector method and adjusting $E$ until the
#   number of nodes in the wavefunction equals $n-l-1$. The calling routine must
#   provide an initial estimate for the eigenvalue. Note that the arrays
#   {\tt g0} and {\tt f0} represent the radial functions multiplied by $r$.

function rdirac!(sol, n, l, k, nr, r, vr, evals, g0, f0)

    # ! arguments
    # real(8), intent(in) :: sol
    # integer, intent(in) :: n,l,k,nr
    # real(8), intent(in) :: r(nr),vr(nr)
    # real(8), intent(inout) :: evals
    # real(8), intent(out) :: g0(nr),f0(nr)

    @assert k > 0
    @assert nr >= 4

    # local variables
    maxit = 2000
    # energy convergence tolerance
    SMALL = 1.e-12
    # automatic arrays
    g1 = zeros(Float64,nr)
    f1 = zeros(Float64,nr)
    fr = zeros(Float64,nr)

    if k > n
        println("n = ", n)
        println("k = ", k)
        error("Error incompatible n and k")
    end

    if ( (k == n) && (l != k-1) )
        println("n = ", n)
        println("k = ", k)
        println("l = ", k)
        error("Incompatible n, k and l")
    end

    if k == l
        kpa = k
    elseif k == (l+1)
        kpa = -k
    else
        println("l = ", l)
        println("k = ", k)
        println("Error: incompatible l and k")
    end

    #println("n   = ", n)
    #println("l   = ", l)
    #println("k   = ", k)
    #println("kpa = ", kpa)

    de = 1.0
    nndp = 0
    it = 0
    #
    while true
        #
        it = it + 1
        if it > maxit
            break
        end
        # integrate the Dirac equation
        #println("calling rdiracint")
        #println("kpa = ", kpa)
        #println("nr  = ", nr)
        nn, evals = rdiracint!(sol, kpa, evals, nr, r, vr, g0, g1, f0, f1)
        # check the number of nodes
        nnd = nn - (n-l-1)
        if nnd > 0
            evals = evals - de
        else
            evals = evals + de
        end
        #
        if it > 1
            if ( (nnd != 0) || ( nndp != 0) )
                if nnd*nndp <= 0
                    de = de*0.5
                else
                    de = de*1.1
                end
            end
        end
        #
        nndp = nnd
        if de < SMALL*(abs(evals) + 1.0)
            break
        end
    end

    if it > maxit
        println("Warning(rdirac): maximum iterations exceeded")
    end

    # find effective infinity and set wavefunction to zero after that point
    # major component
    irm = nr
    for ir in 2:nr
        if ( (g0[ir-1]*g0[ir] < 0.0) || (g1[ir-1]*g1[ir] < 0.0) )
            irm = ir
        end
    end
    g0[irm:nr] .= 0.0
    # minor component
    irm = nr
    for ir in 2:nr
        if ( (f0[ir-1]*f0[ir] < 0.0) || (f1[ir-1]*f1[ir] < 0.0) )
            irm = ir
        end
    end
    f0[irm:nr] .= 0.0
    # normalise
    for ir in 1:nr
      fr[ir] = g0[ir]^2 + f0[ir]^2
    end

    t1 = splint(nr, r, fr)
    t1 = sqrt(abs(t1))

    if t1 > 0.0
      t1 = 1.0/t1
    else
      error("Error(rdirac): zero wavefunction")
    end
    g0[:] = t1*g0[:]
    f0[:] = t1*f0[:]
    return evals
end


text:
# custom help for byrow()
function Docs.getdoc(x::typeof(byrow), y)
    if y == Union{}
        return _get_doc_byrow("default")
    elseif y == Tuple{typeof(sum)}
        return _get_doc_byrow("sum")
    elseif y == Tuple{typeof(mean)}
        return _get_doc_byrow("mean")
    elseif y == Tuple{typeof(all)}
        return _get_doc_byrow("all")
    elseif y == Tuple{typeof(any)}
        return _get_doc_byrow("any")
    elseif y == Tuple{typeof(count)}
        return _get_doc_byrow("count")
    elseif y == Tuple{typeof(prod)}
        return _get_doc_byrow("prod")
    end
end

function _get_doc_byrow(fun; text = byrow_docs_text)
    split_text = split(text, "@@@@")
    loc = findfirst(==(fun), split_text)
    Markdown.parse(split_text[loc+1])
end

byrow_docs_text = """
@@@@default@@@@
    byrow(ds, fun, cols; ...)

Perform a row-wise operation specified by `fun` on selected columns `cols`. Generally,
`fun` can be any function that returns a scalar value for each row.

`byrow` is fine tuned for the following operations, to get extra help for each of them search help for `byrow(fun)`, e.g. `?byrow(sum)`;

# Reduction operations

- `all`
- `any`
- `argmax`
- `argmin`
- `coalesce`
- `count`
- `findfirst`
- `findlast`
- `hash`
- `in`
- `isequal`
- `isless`
- `issorted`
- `join`
- `mapreduce`
- `maximum`
- `mean`
- `minimum`
- `nunique`
- `prod`
- `select`
- `std`
- `sum`
- `var`

# Special operations

- `cummax`
- `cummax!`
- `cummin`
- `cummin!`
- `cumprod`
- `cumprod!`
- `cumsum`
- `cumsum!`
- `fill`
- `fill!`
- `sort`
- `sort!`
- `stdze`
- `stdze!`
@@@@sum@@@@
    byrow(ds, sum, cols = names(ds, Number); [by = identity, threads])

Sum results of calling function `by` on each element of each row of `ds`. If `cols` is not specified, `byrow`
computes sum for all numeric columns in `ds`.

Passing `threads = false` disables multitrheaded computations.

Missing values are removed from the calculation. When all values in a row are missing, it returns `missing`.

## Example

```jldoctest
julia> ds = Dataset(x = [1,2,3], y = [2.0, 1.5, 4.0])
3×2 Dataset
 Row │ x         y
     │ identity  identity
     │ Int64?    Float64?
─────┼────────────────────
   1 │        1       2.0
   2 │        2       1.5
   3 │        3       4.0

julia> byrow(ds, sum, :)
3-element Vector{Float64}:
 3.0
 3.5
 7.0
```
@@@@mean@@@@
    byrow(ds, mean, cols = names(ds, Number); [by = identity, threads])

Compute mean of the results of calling function `by` on each element of each row of `ds`. If `cols` is not specified, `byrow`
computes mean for all numeric columns in `ds`.

Passing `threads = false` disables multitrheaded computations.

Missing values are removed from the calculation. When all values in a row are missing, it returns `missing`.

## Example

```jldoctest
julia> ds = Dataset(x = [1,2,3], y = [2.0, 1.5, 4.0])
3×2 Dataset
 Row │ x         y
     │ identity  identity
     │ Int64?    Float64?
─────┼────────────────────
   1 │        1       2.0
   2 │        2       1.5
   3 │        3       4.0

julia> byrow(ds, mean, :)
3-element Vector{Float64}:
 1.5
 1.75
 3.5
```
@@@@all@@@@
    byrow(ds, all, cols = :; [by = isequal(true), threads, mapformats = false])

Test whether all elements in each row in selected columns are `true`, when `by` is passed, determine whether predicate `by` returns `true` for all elements in the row.

By default, `byrow` uses the actual values for test the elements, however, passing `mapformats = true`
change this to the formatted values.

Each columns in `cols` may have its own `by`. This may be achieved by passing a vector of predicates to `by`.

Passing `threads = false` disables multitrheaded computations.

See [`filter`](@ref) or [`filter!`](@ref)

## Example

```jldoctest
julia> ds = Dataset(x = [1,2,3], y = [2.0, 1.5, 4.0])
3×2 Dataset
 Row │ x         y
     │ identity  identity
     │ Int64?    Float64?
─────┼────────────────────
   1 │        1       2.0
   2 │        2       1.5
   3 │        3       4.0

julia> byrow(ds, all, :, by = [==(2), >(1)])
3-element Vector{Bool}:
 0
 1
 0
```
@@@@any@@@@
    byrow(ds, any, cols = :; [by = isequal(true), threads, mapformats = false])

Test whether any elements in each row in selected columns is `true`, when `by` is passed, determine whether predicate `by` returns `true` for any elements in the row.

By default, `byrow` uses the actual values for test the elements, however, passing `mapformats = true`
change this to the formatted values.

Each columns in `cols` may have its own `by`. This may be achieved by passing a vector of predicates to `by`.

Passing `threads = false` disables multitrheaded computations.

See [`filter`](@ref) or [`filter!`](@ref)

## Example

```jldoctest
julia> ds = Dataset(x = [1,2,3], y = [2.0, 1.5, 4.0])
3×2 Dataset
 Row │ x         y
     │ identity  identity
     │ Int64?    Float64?
─────┼────────────────────
   1 │        1       2.0
   2 │        2       1.5
   3 │        3       4.0

julia> byrow(ds, any, :, by = [==(2), >(1)])
3-element Vector{Bool}:
 1
 1
 1
```
@@@@count@@@@
    byrow(ds, count, cols = :; [by = isequal(true), threads])

Count the number of elements in each row for selected columns which the function `by` returns `true`.

Passing `threads = false` disables multitrheaded computations.

## Example

```jldoctest
julia> julia> ds = Dataset(x = [1,2,3], y = [2, 6, 5])
3×2 Dataset
 Row │ x         y
     │ identity  identity
     │ Int64?    Int64?
─────┼────────────────────
   1 │        1         2
   2 │        2         6
   3 │        3         5

julia> byrow(ds, count, :, by = isodd)
3-element Vector{Int32}:
 1
 0
 2
```
@@@@prod@@@@
    byrow(ds, prod, cols = names(ds, Number); [by = identity, threads])

Return the product of the results of calling function `by` on each element of each row of `ds`. If `cols` is not specified, `byrow`
computes product for all numeric columns in `ds`.

Passing `threads = false` disables multitrheaded computations.

Missing values are removed from the calculation. When all values in a row are missing, it returns `missing`.

## Example

```jldoctest
julia>  ds = Dataset(x = [1,2,3], y = [2.0, 1.5, 4.0])
3×2 Dataset
 Row │ x         y
     │ identity  identity
     │ Int64?    Float64?
─────┼────────────────────
   1 │        1       2.0
   2 │        2       1.5
   3 │        3       4.0

julia> byrow(ds, prod, :)
3-element Vector{Union{Missing, Float64}}:
  2.0
  3.0
 12.0
```

"""


text:
"""
    Auto

A singleton type to denote that some argument to a function or constructor should
be automatically determined.
"""
struct Auto end

const LabelsType = Union{Auto, Colon, Tuple{Vararg{Int}}, Tuple{Vararg{Symbol}}}

_labels(::Colon, types) = fieldnames(types)

function _is_suitable_label_type(T)

    return T <: Union{Integer, AbstractString, AbstractChar, Symbol}
end

function _labels(::Auto, types)

    return filter(i -> _is_suitable_label_type(fieldtype(types, i)), fieldnames(types))
end

# TODO we could actually verify that the keys are valid
_labels(keys::Tuple, types) = keys


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

struct UsersApi <: SwaggerApi
    client::Swagger.Client
end

function _swaggerinternal_apiV1FleetUsersGet(_api::UsersApi; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", Nothing, "/api/v1/fleet/users", ["bearerAuth"])
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
    return _ctx
end

@doc raw"""List Users

Params:

Return: Nothing
"""
function apiV1FleetUsersGet(_api::UsersApi; _mediaType=nothing)
    _ctx = _swaggerinternal_apiV1FleetUsersGet(_api; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function apiV1FleetUsersGet(_api::UsersApi, response_stream::Channel; _mediaType=nothing)
    _ctx = _swaggerinternal_apiV1FleetUsersGet(_api; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

export apiV1FleetUsersGet


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:5] <= 1)

                     @variable(m, -36.453305806680525 <= q <= 37.480198521751326)

                     add_NL_constraint(m, :(gelu(-0.5060529352779994 + 0.34605798298901425*gelu(-0.49627455608242954 + -0.46375151869975495*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + 0.4918746175115887*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + 0.38157591143072933*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.5439511060803288*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + 0.8504066842806357*gelu(-0.2321501407718678 + 0.5600091754803458*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.0034071169835434567*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + -0.6765465160367254*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + 0.8220752699067027*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + 0.462211279142271*gelu(-0.9807289687619161 + -0.5968595287514287*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.3897253830589995*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + 0.5397807246416386*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.24558591797668194*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + -0.0428411186394575*gelu(0.7899732054652109 + -0.5363355140855166*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.6727460735415476*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + -0.4129142282119118*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.4150508411017726*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5])))) + gelu(0.02992678336456356 + -0.8781954986928167*gelu(-0.49627455608242954 + -0.46375151869975495*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + 0.4918746175115887*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + 0.38157591143072933*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.5439511060803288*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + -0.84297522225665*gelu(-0.2321501407718678 + 0.5600091754803458*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.0034071169835434567*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + -0.6765465160367254*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + 0.8220752699067027*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + 0.44937020244474857*gelu(-0.9807289687619161 + -0.5968595287514287*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.3897253830589995*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + 0.5397807246416386*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.24558591797668194*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + -0.012040065223148932*gelu(0.7899732054652109 + -0.5363355140855166*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.6727460735415476*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + -0.4129142282119118*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.4150508411017726*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5])))) + gelu(-0.25761034404046734 + -0.19911102915318102*gelu(-0.49627455608242954 + -0.46375151869975495*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + 0.4918746175115887*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + 0.38157591143072933*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.5439511060803288*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + 0.7457041629864394*gelu(-0.2321501407718678 + 0.5600091754803458*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.0034071169835434567*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + -0.6765465160367254*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + 0.8220752699067027*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + 0.7638178262546895*gelu(-0.9807289687619161 + -0.5968595287514287*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.3897253830589995*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + 0.5397807246416386*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.24558591797668194*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + 0.07889233901952375*gelu(0.7899732054652109 + -0.5363355140855166*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.6727460735415476*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + -0.4129142282119118*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.4150508411017726*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5])))) + gelu(0.1153458350428731 + 0.9297971624965538*gelu(-0.49627455608242954 + -0.46375151869975495*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + 0.4918746175115887*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + 0.38157591143072933*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.5439511060803288*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + -0.7017891371439648*gelu(-0.2321501407718678 + 0.5600091754803458*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.0034071169835434567*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + -0.6765465160367254*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + 0.8220752699067027*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + -0.8093911002605614*gelu(-0.9807289687619161 + -0.5968595287514287*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.3897253830589995*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + 0.5397807246416386*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.24558591797668194*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5]))) + 0.43763294749909276*gelu(0.7899732054652109 + -0.5363355140855166*gelu(0.8994638843665332 + -0.21460729883264662*$(x[1]) + -0.6173390778114793*$(x[2]) + 0.5769355957045894*$(x[3]) + -0.29054193627721014*$(x[4]) + 0.9844022485972483*$(x[5])) + -0.6727460735415476*gelu(0.2763051493368929 + 0.8533339132011375*$(x[1]) + -0.36082426348518304*$(x[2]) + -0.694925986364535*$(x[3]) + -0.6948010174882064*$(x[4]) + 0.21743382793841226*$(x[5])) + -0.4129142282119118*gelu(0.044944779340077456 + 0.03687124531051067*$(x[1]) + -0.5175326375722826*$(x[2]) + -0.9986359847691255*$(x[3]) + -0.33739875692716526*$(x[4]) + 0.025638388186982386*$(x[5])) + -0.4150508411017726*gelu(0.8609963866663906 + -0.4203074235446964*$(x[1]) + 0.91553501702727*$(x[2]) + 0.8830101091308449*$(x[3]) + 0.07593641537869811*$(x[4]) + -0.2012556317025167*$(x[5])))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
Base.:(==)(t1::CXType, t2::CXType) = clang_equalTypes(t1, t2) != 0

"""
    canonical(t::CXType) -> CXType
    canonical(t::CLType) -> CLType
Return the canonical type for a CXType.

Clang's type system explicitly models typedefs and all the ways a specific type can be
represented. The canonical type is the underlying type with all the "sugar" removed.
For example, if 'T' is a typedef for 'int', the canonical type for 'T' would be 'int'.
Wrapper for libclang's `clang_getCanonicalType`.
"""
canonical(t::CXType) = clang_getCanonicalType(t)
canonical(t::CLType)::CLType = clang_getCanonicalType(t)

"""
    isconst(t::Union{CXType,CLType}) -> Bool
Determine whether a CXType has the "const" qualifier set, without looking through typedefs
that may have added "const" at a different level.
Wrapper for libclang's `clang_isConstQualifiedType`.
"""
Base.isconst(t::Union{CXType,CLType})::Bool = clang_isConstQualifiedType(t)

"""
    isvolatile(t::Union{CXType,CLType}) -> Bool
Determine whether a CXType has the "volatile" qualifier set, without looking through typedefs
that may have added "volatile" at a different level.
Wrapper for libclang's `clang_isVolatileQualifiedType`.
"""
isvolatile(t::CXType)::Bool = clang_isVolatileQualifiedType(t)

"""
    isrestrict(t::Union{CXType,CLType}) -> Bool
Determine whether a CXType has the "restrict" qualifier set, without looking through typedefs
that may have added "restrict" at a different level.
Wrapper for libclang's `clang_isRestrictQualifiedType`.
"""
isrestrict(t::Union{CXType,CLType})::Bool = clang_isRestrictQualifiedType(t)

"""
    address_space(t::Union{CXType,CLType})
Returns the address space of the given type.
Wrapper for libclang's `clang_getAddressSpace`.
"""
address_space(t::Union{CXType,CLType}) = clang_getAddressSpace(t)

"""
    typedef_name(t::Union{CXType,CLType}) -> String
Return the typedef name of the given type.
Wrapper for libclang's `clang_getTypedefName`.
"""
function typedef_name(t::Union{CXType,CLType})
    cxstr = clang_getTypedefName(t)
    ptr = clang_getCString(cxstr)
    s = unsafe_string(ptr)
    clang_disposeString(cxstr)
    return s
end

"""
    pointee_type(t::CXType) -> CXType
    pointee_type(t::CLType) -> CLType
Return the type of the pointee for pointer types.
Wrapper for libclang's `clang_getPointeeType`.
"""
pointee_type(t::CXType) = clang_getPointeeType(t)
pointee_type(t::CLType)::CLType = clang_getPointeeType(t)

"""
    typedecl(t::CXType) -> CXCursor
    typedecl(t::CLType) -> CLCursor
Return the cursor for the declaration of the given type. To get the type of the cursor,
see [`type`](@ref). Wrapper for libclang's `clang_getTypeDeclaration`.
"""
typedecl(t::CXType) = clang_getTypeDeclaration(t)
typedecl(t::CLType)::CLCursor = clang_getTypeDeclaration(t)

"""
    spelling(t::Union{CXType,CLType}) -> String
Pretty-print the underlying type using the rules of the language of the translation unit
from which it came. If the type is invalid, an empty string is returned.
Wrapper for libclang's `clang_getTypeSpelling`.
"""
function spelling(t::Union{CXType,CLType})
    cxstr = clang_getTypeSpelling(t)
    ptr = clang_getCString(cxstr)
    s = unsafe_string(ptr)
    clang_disposeString(cxstr)
    return s
end

"""
    spelling(kind::CXTypeKind) -> String
Return the spelling of a given CXTypeKind.
"""
function spelling(kind::CXTypeKind)
    cxstr = clang_getTypeKindSpelling(kind)
    ptr = clang_getCString(cxstr)
    s = unsafe_string(ptr)
    clang_disposeString(cxstr)
    return s
end

"""
    calling_conv(t::Union{CXType,CLFunctionNoProto,CLFunctionProto}) -> CXCallingConv
Return the calling convention associated with a function type.
Wrapper for libclang's `clang_getFunctionTypeCallingConv`.
"""
calling_conv(t::Union{CXType,CLFunctionNoProto,CLFunctionProto})::CXCallingConv = clang_getFunctionTypeCallingConv(t)

"""
    result_type(t::CXType) -> CXType
    result_type(t::Union{CLFunctionNoProto,CLFunctionProto}) -> CLType
Return the return type associated with a function type.
Wrapper for libclang's `clang_getResultType`.
"""
result_type(t::CXType) = clang_getResultType(t)
result_type(t::Union{CLFunctionNoProto,CLFunctionProto})::CLType = clang_getResultType(t)

## TODO:
# clang_getExceptionSpecificationType

"""
    argnum(t::Union{CXType,CLFunctionNoProto,CLFunctionProto}) -> Int
Return the number of non-variadic parameters associated with a function type.
Wrapper for libclang's `clang_getNumArgTypes`.
"""
argnum(t::Union{CXType,CLFunctionNoProto,CLFunctionProto,CLUnexposed})::Int = clang_getNumArgTypes(t)

"""
    argtype(t::CXType, i::Unsigned) -> CXType
    argtype(t::Union{CLFunctionNoProto,CLFunctionProto}, i::Integer) -> CLType
Return the type of a parameter of a function type.
Wrapper for libclang's `clang_getArgType`.
"""
argtype(t::CXType, i::Unsigned) = clang_getArgType(t, Unsigned(i))
argtype(t::Union{CLFunctionNoProto,CLFunctionProto,CLUnexposed}, i::Integer)::CLType = argtype(t.type, Unsigned(i))

"""
    isvariadic(t::Union{CXType,CLType}) -> Bool
Return true if the CXType is a variadic function type.
Wrapper for libclang's `clang_isFunctionTypeVariadic`.
"""
isvariadic(t::Union{CXType,CLType})::Bool = clang_isFunctionTypeVariadic(t)

"""
    is_plain_old_data(t::Union{CXType,CLType}) -> Bool
Return true if the CXType is a plain old data type.
Wrapper for libclang's `clang_isPODType`.
"""
is_plain_old_data(t::CXType)::Bool = clang_isPODType(t)

"""
    element_type(t::CXType) -> CXType
    element_type(t::Union{CLVector,CLConstantArray,CLIncompleteArray,CLVariableArray,CLDependentSizedArray,CLComplex}) -> CLType
Return the element type of an array, complex, or vector type.
Wrapper for libclang's `clang_getElementType`.
"""
element_type(t::CXType) = clang_getElementType(t)
element_type(t::Union{CLVector,CLConstantArray,CLIncompleteArray,CLVariableArray,CLDependentSizedArray,CLComplex})::CLType = clang_getElementType(t)
# old API: clang_getArrayElementType

"""
    element_num(t::Union{CXType,CLVector,CLConstantArray,CLIncompleteArray,CLVariableArray,CLDependentSizedArray}) -> Int
Return the number of elements of an array or vector type.
Wrapper for libclang's `clang_getNumElements`.
"""
element_num(t::Union{CXType,CLVector,CLConstantArray,CLIncompleteArray,CLVariableArray,CLDependentSizedArray})::Int = clang_getNumElements(t)
# old API: clang_getArraySize

"""
    get_named_type(t::CXType) -> CXType
    get_named_type(t::CLElaborated) -> CLType
Return the type named by the qualified-id.
Wrapper for libclang's `clang_Type_getNamedType`.
"""
get_named_type(t::CXType) = clang_Type_getNamedType(t)
get_named_type(t::CLElaborated)::CLType = clang_Type_getNamedType(t)

## TODO:
# clang_Type_isTransparentTagTypedef
# clang_Type_getAlignOf
# clang_Type_getClassType
# clang_Type_getSizeOf
# clang_Type_getOffsetOf
# clang_Type_getNumTemplateArguments
# clang_Type_getTemplateArgumentAsType
# clang_Type_getCXXRefQualifier
#

# helper
"""
    kind(t::CXType) -> CXTypeKind
    kind(t::CLType) -> CXTypeKind
Return the kind of the given type.
"""
kind(t::CXType) = CXTypeKind(t.kind)
kind(t::CLType) = kind(t.type)

"""
    isvalid(t::CXType) -> Bool
    isvalid(t::CLType) -> Bool
Return true if the type is a valid type.
"""
isvalid(t::CXType) = kind(t) != CXType_Invalid
isvalid(t::CLType) = isvalid(t.type)

"""
    resolve_type(t::CLType) -> CLType
This function attempts to work around some limitations of the current libclang API.
"""
function resolve_type(t::CLType)::CLType
    if kind(t) == CXType_Unexposed
        # try to resolve Unexposed type to cursor definition.
        cursor = typedecl(t)
        if !isnull(cursor) && kind(cursor) != CXCursor_NoDeclFound
            return type(cursor)
        end
    end
    # otherwise, this will either be a builtin or unexposed client needs to sort out.
    return t
end


text:
module FluxJS

using Flux, MacroTools, BSON
using Flux.Tracker: data

export @code_js

include("dump.jl")
include("trace.jl")
include("compile.jl")
include("lib.jl")

end # module


text:
immutable FDist <: ContinuousUnivariateDistribution
    d1::Float64
    d2::Float64

    function FDist(d1::Real, d2::Real)
        d1 > zero(d1) && d2 > zero(d2) || error("Degrees of freedom must be positive")
        new(float64(d1), float64(d2))
    end
end

@_jl_dist_2p FDist f

@distr_support FDist 0.0 Inf

#### Parameters

params(d::FDist) = (d.d1, d.d2)

#### Statistics

mean(d::FDist) = (d2 = d.d2; d2 > 2.0 ? d2 / (d2 - 2.0) : NaN)

mode(d::FDist) = ((d1, d2) = params(d); d1 > 2.0 ? ((d1 - 2.0)/d1) * (d2 / (d2 + 2.0)) : 0.0)

function var(d::FDist)
    (d1, d2) = params(d)
    d2 > 4.0 ? 2.0 * d2^2 * (d1 + d2 - 2.0) / (d1 * (d2 - 2.0)^2 * (d2 - 4.0)) : NaN
end

function skewness(d::FDist)
    (d1, d2) = params(d)
    if d2 > 6.0
        return (2.0 * d1 + d2 - 2.0) * sqrt(8.0 * (d2 - 4.0)) / ((d2 - 6.0) * sqrt(d1 * (d1 + d2 - 2.0)))
    else
        return NaN
    end
end

function kurtosis(d::FDist)
    (d1, d2) = params(d)
    if d2 > 8.0
        a = d1 * (5. * d2 - 22.) * (d1 + d2 - 2.) + (d2 - 4.) * (d2 - 2.)^2
        b = d1 * (d2 - 6.) * (d2 - 8.) * (d2 - 2.)
        return 12. * a / b
    else
        return NaN
    end
end

function entropy(d::FDist)
    (d1, d2) = params(d)
    hd1 = d1 * 0.5
    hd2 = d2 * 0.5
    hs = (d1 + d2) * 0.5
    return log(d2 / d1) + lgamma(hd1) + lgamma(hd2) - lgamma(hs) +
        (1.0 - hd1) * digamma(hd1) + (-1.0 - hd2) * digamma(hd2) +
        hs * digamma(hs)
end


text:
# Unit tests for nbs_integration.jl

@testset "nbs_integration.jl" begin
    # TODO
end

max_stars_repo_name: jrdegreeff/cesmix-julia

max_issues_repo_name: jrdegreeff/cesmix-julia

max_forks_repo_name: jrdegreeff/cesmix-julia


text:
using OrthographicProjection
using FileManager
using Common
using Visualization

txtpotreedirs = "C:/Users/marte/Documents/potreeDirectory/pointclouds/CAVA" #"C:/Users/marte/Documents/GEOWEB/wrapper_file/directory.txt"
# txtpotreedirs = "C:/Users/marte/Documents/GEOWEB/wrapper_file/directory.txt"
potreedirs = OrthographicProjection.get_potree_dirs(txtpotreedirs)
metadata = CloudMetadata(potreedirs[1])
bbin = metadata.tightBoundingBox
#bbin = "C:/Users/marte/Documents/GEOWEB/wrapper_file/JSON/volume_COLOMBELLA.json"
ucs = Matrix{Float64}(Common.I,4,4)
GSD = 0.3
PO = "XY+"
quota = 210.0 #11.8 #458277.430, 4493982.030, 210.840
thickness = 5.
outputimage = "examples/prova.jpg"
pc = true
background = [0.0,0.0,0.0]
epsg = nothing #2049
@time OrthographicProjection.orthophoto(txtpotreedirs, outputimage, bbin, GSD, PO, quota, thickness, ucs, background, pc, epsg)

## VIEW
# using Visualization
# source = ""
# files = FileManager.get_files_in_potree_folder(source,0)
# PC = FileManager.las2pointcloud(files...)
# V,EV,FV = getmodel(bbin)
#
# GL.VIEW(
#     [
#     GL.GLGrid(V,EV),
#     Visualization.points_color_from_rgb(PC.coordinates,PC.rgbs)
#     ]
# )
#
# PC = FileManager.source2pc("examples/risultato/prova.las")
# model = Common.getmodel(FileManager.las2aabb("examples/risultato/prova.las"))
# Visualization.VIEW([
#     Visualization.points(PC.coordinates,PC.rgbs)
#     Visualization.GLGrid(model[1],model[3])
#     # Visualization.axis_helper()
# ])


text:
using ReduxImGui
using ReduxImGui.Redux
using Test

struct ItemSeparator <: MenuItems.AbstractGenericMenuItem end
(x::ItemSeparator)() = ReduxImGui.CImGui.Separator()

@testset "Menus | MenuItem" begin
    name = "MenuItem_test"
    store = create_store(MenuItems.reducer, MenuItem(name))
    state = get_state(store)

    # test initial state
    @test state.label == name
    @test state.shortcut == ""
    @test state.is_enabled == true
    @test state.is_triggered == false

    # test actions
    new_name = "MenuItem_new_name"
    state = get_state(store)
    dispatch!(store, MenuItems.Rename(state.label, new_name))
    @test get_state(store).label == new_name
    dispatch!(store, MenuItems.Rename(state.label, name))
    @test get_state(store).label == name

    new_shortcut = "Ctrl+Z"
    state = get_state(store)
    dispatch!(store, MenuItems.ChangeShortcut(state.label, new_shortcut))
    @test MenuItems.get_shortcut(get_state(store)) == new_shortcut

    dispatch!(store, MenuItems.Enable(state.label))
    @test MenuItems.is_enabled(get_state(store)) == true

    dispatch!(store, MenuItems.Disable(state.label))
    @test MenuItems.is_enabled(get_state(store)) == false

    dispatch!(store, MenuItems.SetTriggeredTo(state.label, true))
    @test MenuItems.is_triggered(get_state(store)) == true

    # test vectors
    store = create_store(MenuItems.reducer, [MenuItem("m1"),MenuItem("m2"),ItemSeparator()])
    state = get_state(store)
    dispatch!(store, MenuItems.AddMenuItem("m3"))
    dispatch!(store, MenuItems.DeleteMenuItem("m1"))
    state = get_state(store)
    @test state[1] == MenuItem("m2")
    @test state[3] == MenuItem("m3")
    dispatch!(store, MenuItems.SetTriggeredTo("m2", false))
    @test MenuItems.is_triggered(get_state(store)[1]) == false

    # test dicts
    store = create_store(MenuItems.reducer, Dict("m1"=>MenuItem("m1"),"m2"=>MenuItem("m2")))
    state = get_state(store)
    dispatch!(store, MenuItems.Enable("m2"))
    state = get_state(store)
    @test MenuItems.is_enabled(state["m2"]) == true
end

@testset "Menus | ToggleMenuItem" begin
    name = "MenuItem_test"
    store = create_store(ToggleMenuItems.reducer, ToggleMenuItem(name))
    state = get_state(store)

    # test initial state
    @test state.is_selected == false

    # test actions
    new_name = "MenuItem_new_name"
    state = get_state(store)
    dispatch!(store, ToggleMenuItems.Rename(state.label, new_name))
    @test get_state(store).label == new_name
    dispatch!(store, ToggleMenuItems.Rename(state.label, name))
    @test get_state(store).label == name

    new_shortcut = "Ctrl+Z"
    state = get_state(store)
    dispatch!(store, ToggleMenuItems.ChangeShortcut(state.label, new_shortcut))
    @test ToggleMenuItems.get_shortcut(get_state(store)) == new_shortcut

    dispatch!(store, ToggleMenuItems.SetSelectedTo(state.label, true))
    @test ToggleMenuItems.is_selected(get_state(store)) == true

    dispatch!(store, ToggleMenuItems.Toggle(state.label))
    @test ToggleMenuItems.is_selected(get_state(store)) == false

    dispatch!(store, ToggleMenuItems.Enable(state.label))
    @test ToggleMenuItems.is_enabled(get_state(store)) == true

    dispatch!(store, ToggleMenuItems.Disable(state.label))
    @test ToggleMenuItems.is_enabled(get_state(store)) == false

    dispatch!(store, ToggleMenuItems.SetTriggeredTo(state.label, true))
    @test ToggleMenuItems.is_triggered(get_state(store)) == true

    # test vectors
    store = create_store(ToggleMenuItems.reducer, [ToggleMenuItem("m1"),ToggleMenuItem("m2")])
    state = get_state(store)
    dispatch!(store, ToggleMenuItems.AddMenuItem("m3"))
    dispatch!(store, ToggleMenuItems.DeleteMenuItem("m1"))
    state = get_state(store)
    @test state[1] == ToggleMenuItem("m2")
    @test state[2] == ToggleMenuItem("m3")
    dispatch!(store, ToggleMenuItems.SetTriggeredTo("m2", false))
    @test ToggleMenuItems.is_triggered(get_state(store)[1]) == false

    # test dicts
    store = create_store(ToggleMenuItems.reducer, Dict("m1"=>ToggleMenuItem("m1"),"m2"=>ToggleMenuItem("m2")))
    state = get_state(store)
    dispatch!(store, ToggleMenuItems.Enable("m2"))
    state = get_state(store)
    @test ToggleMenuItems.is_enabled(state["m2"]) == true
end

@testset "Menus | Menus" begin
    name = "Menus_test"
    store = create_store(Menus.reducer, Menu(name))
    state = get_state(store)

    # test initial state
    @test state.label == name
    @test state.items == []
    @test state.is_enabled == true
    @test state.is_triggered == false

    # test actions
    new_name = "Menus_new_name"
    state = get_state(store)
    dispatch!(store, Menus.Rename(state.label, new_name))
    @test get_state(store).label == new_name
    dispatch!(store, Menus.Rename(state.label, name))
    @test get_state(store).label == name

    dispatch!(store, Menus.Enable(state.label))
    @test Menus.is_enabled(get_state(store)) == true

    dispatch!(store, Menus.Disable(state.label))
    @test Menus.is_enabled(get_state(store)) == false

    dispatch!(store, Menus.SetTriggeredTo(state.label, true))
    @test Menus.is_triggered(get_state(store)) == true

    dispatch!(store, Menus.EditMenuItems(state.label, MenuItems.AddMenuItem("mt")))
    @test get_state(store).items[1].label == "mt"

    dispatch!(store, Menus.EditMenuItems(state.label, ToggleMenuItems.AddMenuItem("mtc")))
    @test get_state(store).items[2].label == "mtc"

    # submenu
    name = "SubMenu_test"
    store = create_store(Menus.reducer, Menu(name, [MenuItem("item1"), Menu("submenu1")]))
    state = get_state(store)
    dispatch!(store, Menus.EditMenuItems(state.label, ToggleMenuItems.AddMenuItem("item2")))
    @test get_state(store).items[3].label == "item2"

    dispatch!(
        store,
        Menus.EditMenuItems(
            state.label,
            Menus.EditMenuItems(
                "submenu1",
                ToggleMenuItems.AddMenuItem("item2")
            )
        )
    )
    @test get_state(store).items[2].items[].label == "item2"

    # test vectors
    store = create_store(Menus.reducer, [Menu("m1"),Menu("m2")])
    state = get_state(store)
    dispatch!(store, Menus.AddMenu("m3"))
    dispatch!(store, Menus.DeleteMenu("m1"))
    state = get_state(store)
    @test state[1].label == "m2"
    @test state[2].label == "m3"
    dispatch!(store, Menus.SetTriggeredTo("m2", false))
    @test Menus.is_triggered(get_state(store)[1]) == false

    # test dicts
    store = create_store(Menus.reducer, Dict("m1"=>Menu("m1"),"m2"=>Menu("m2")))
    state = get_state(store)
    dispatch!(store, Menus.Enable("m2"))
    state = get_state(store)
    @test Menus.is_enabled(state["m2"]) == true
end

@testset "Menus | MenuBar" begin
    name = "MenuBar_test"
    store = create_store(MenuBars.reducer, MenuBar(name))
    state = get_state(store)

    # test initial state
    @test state.label == name
    @test state.menus == []
    @test state.is_hidden == false
    @test state.is_triggered == false

    # test actions
    new_name = "MenuBar_new_name"
    state = get_state(store)
    dispatch!(store, MenuBars.Rename(state.label, new_name))
    @test get_state(store).label == new_name
    dispatch!(store, MenuBars.Rename(state.label, name))
    @test get_state(store).label == name

    dispatch!(store, MenuBars.Show(state.label))
    @test MenuBars.is_hidden(get_state(store)) == false

    dispatch!(store, MenuBars.Hide(state.label))
    @test MenuBars.is_hidden(get_state(store)) == true

    dispatch!(store, MenuBars.SetTriggeredTo(state.label, true))
    @test MenuBars.is_triggered(get_state(store)) == true

    dispatch!(store, MenuBars.EditMenus(state.label, Menus.AddMenu("m")))
    @test get_state(store).menus[1].label == "m"

    dispatch!(store, MenuBars.EditMenus(state.label, Menus.AddMenu("m2")))
    @test get_state(store).menus[2].label == "m2"
end

@testset "Menus | MainMenuBar" begin
    name = "MainMenuBar_test"
    store = create_store(MainMenuBars.reducer, MainMenuBar(name))
    state = get_state(store)

    # test initial state
    @test state.label == name
    @test state.menus == []
    @test state.is_hidden == false
    @test state.is_triggered == false

    # test actions
    new_name = "MainMenuBar_new_name"
    state = get_state(store)
    dispatch!(store, MainMenuBars.Rename(state.label, new_name))
    @test get_state(store).label == new_name
    dispatch!(store, MainMenuBars.Rename(state.label, name))
    @test get_state(store).label == name

    dispatch!(store, MainMenuBars.Show(state.label))
    @test MainMenuBars.is_hidden(get_state(store)) == false

    dispatch!(store, MainMenuBars.Hide(state.label))
    @test MainMenuBars.is_hidden(get_state(store)) == true

    dispatch!(store, MainMenuBars.SetTriggeredTo(state.label, true))
    @test MainMenuBars.is_triggered(get_state(store)) == true

    dispatch!(store, MainMenuBars.EditMenus(state.label, Menus.AddMenu("m")))
    @test get_state(store).menus[1].label == "m"

    dispatch!(store, MainMenuBars.EditMenus(state.label, Menus.AddMenu("m2")))
    @test get_state(store).menus[2].label == "m2"
end


text:
@testset "examples" begin
    for size in [3, 792, 40_000]
        for generator in [hyper_pa]
            @test example(generator, size) isa Vector{Vector{Int}}
        end
        for generator in [DCHSBM_sampler, Kronecker_sampler]
            @test example(generator, size) isa Vector{<:NTuple}
        end
    end
    println("\nMillions of entries per second")
    display(MEPS(size=10_000, trials=6))
    println("\n")
end

max_stars_repo_name: LilithHafner/FBD

max_issues_repo_name: LilithHafner/FBD

max_forks_repo_name: LilithHafner/FBD


text:
using PyPlot
using DelimitedFiles
using Hwloc
using Printf

GiB=2^30
MiB=2^20
kiB=2^10

topology=Hwloc.topology_load()
nsockets=collectobjects(topology,:Package) |> length
ncores=collectobjects(topology,:Core) |> length
L3Cache=first(collectobjects(topology,:L3Cache)).attr.size÷MiB
L2Cache=first(collectobjects(topology,:L2Cache)).attr.size÷kiB
L1Cache=first(collectobjects(topology,:L1Cache)).attr.size÷kiB
RAM=Sys.total_memory()÷GiB

CPU="$(nsockets) socket(s) $(ncores) cores $(first(Sys.cpu_info()).model)"
mem="RAM=$(RAM)GiB Cache: L3=$(L3Cache)MiB  L2=$(L2Cache)kiB  L1=$(L1Cache)kiB"

scalar=readdlm("jlvtriad-scalar.dat",comments=true)'
cvtriad=readdlm("cvtriad-omp4.dat",comments=true)'
threads=readdlm("jlvtriad-threads-4.dat",comments=true)'
spawn=readdlm("jlvtriad-spawn-4.dat",comments=true)'

PyPlot.rc("font", size=8)
PyPlot.clf()
PyPlot.semilogx(scalar[1,:],scalar[2,:],"r--",label="julia scalar")
PyPlot.semilogx(cvtriad[1,:],cvtriad[2,:],"g--",label="gcc scalar")
PyPlot.semilogx(cvtriad[1,:],cvtriad[3,:],"g",label="4 threads gcc omp")
PyPlot.semilogx(cvtriad[1,:],cvtriad[4,:],"g-.",label="4 threads gcc omp dynamic")
PyPlot.semilogx(threads[1,:],threads[2,:],"r",label="4 threads julia Threads.@threads")
PyPlot.semilogx(spawn[1,:],spawn[2,:],"b",label="4 threads julia Threads.@spawn")
PyPlot.legend()
PyPlot.grid()
PyPlot.ylim(0,20)
PyPlot.xlabel("Array Size")
PyPlot.ylabel("GFlops/s")
PyPlot.title("Julia vs GCC Thread Performance: A[i]=B[i]+C[i]*D[i]\n$(CPU)\n$(mem)")
PyPlot.savefig("gcc-vs-threads-vs-spawn.pdf")
PyPlot.savefig("gcc-vs-threads-vs-spawn.png")

max_stars_repo_name: j-fu/julia-tests

max_issues_repo_name: j-fu/julia-tests

max_forks_repo_name: j-fu/julia-tests


text:
function profile_test(n)
    for i = 1:n
        A = randn(100,100,20)
        m = maximum(A)
        Afft = fft(A)
        Am = mapslices(sum, A, 2)
        B = A[:,:,5]
        Bsort = mapslices(sort, B, 1)
        b = rand(100)
        C = B.*b
    end
end

function profile_simple_test(n)
    for i = 1:n
        A = randn(100,100,20)
        m = max(A)
    end
end

profile_test(1)
Profile.clear()
@profile profile_test(10)
ProfileView.view()


text:
using GeometricMultigrid
using GeometricMultigrid: multL, multU, mult, increment!, δ

# Classical smoothers
@fastmath function GS!(st;inner=3,kw...)
    @inbounds for I ∈ st.iD.R  # optimized first iteration
        st.ϵ[I] = st.iD[I]*(st.r[I]-multL(I,st.A.L,st.ϵ))
    end
    @inbounds for _ ∈ 2:inner, I ∈ st.iD.R
        st.ϵ[I] = st.iD[I]*(st.r[I]-multL(I,st.A.L,st.ϵ)-multU(I,st.A.L,st.ϵ))
    end
    increment!(st;kw...)
end
@fastmath function SOR!(st;inner=3,ω=0.9,kw...)
    @inbounds for I ∈ st.iD.R  # optimized first iteration
        st.ϵ[I] = ω*st.iD[I]*(st.r[I]-multL(I,st.A.L,st.ϵ))
     end
     @inbounds for _ ∈ 2:inner, I ∈ st.iD.R
       st.ϵ[I] = (1-ω)*st.ϵ[I]+ω*st.iD[I]*(st.r[I]-multL(I,st.A.L,st.ϵ)-multU(I,st.A.L,st.ϵ))
    end
    increment!(st;kw...)
end
@fastmath Jacobi!(st;inner=1,kw...) = for _ ∈ 1:inner
    @loop st.ϵ[I] = st.r[I]*st.iD[I]
    increment!(st;kw...)
end

# Create parameterized MG state
function state(A,x,b;p=p₀,xT::Type=eltype(p),smooth! =GS!,damp=false,kw...)
    y = zero(x,xT)     # make FieldVector of type xT
    @loop y[I] = x[I]  # copy values
    err = sum(b)/length(b)
    @loop b[I] -= err
    st = mg_state(A,y,b)
    smooth! == pseudo! && fill_pseudo!(st;p,kw...)
    damp && adjust_iD!(st;p)
    st
end
state(A,b;kw...) = state(A,zero(b),b;kw...)
fill_pseudo!(st;kw...) = !isnothing(st.child) && (st.P=PseudoInv(st.A;kw...); fill_pseudo!(st.child;kw...))
adjust_iD!(st;p) = !isnothing(st.child) && (@loop st.iD[I] *= p[end]; adjust_iD!(st.child;p))

# Apply smoother
@inline pseudo!(st;kw...) = pseudo!(st,st.P;kw...)
@fastmath pseudo!(st,P::FieldMatrix;inner=2,kw...) = for _=1:inner
    @loop st.ϵ[I] = mult(I,P.L,P.D,st.r)
    increment!(st)
end

# Parameterized approximate inverse matrix P
p₀ = Float32[-0.104447, -0.00238399, 0.00841367, -0.158046, -0.115103] # result from tune_synthetic
function PseudoInv(A::FieldMatrix; scale=maximum(A.L),p::AbstractVector{T}=p₀,
    pmodels=p->(D->1+p[1]+D*(p[2]+D*p[3]),L->L*(p[4]*(L-2)+p[5]*(L-1))),kw...) where T

    L,D,N = zeros(T,size(A.L)),zeros(T,size(A.D)),length(size(A.D))
    Dm,Lm = pmodels(p)
    for I ∈ A.R
        invD = (abs(A.D[I])<1e-8) ? 0. : inv(A.D[I])
        D[I] = invD*Dm(A.D[I]/scale)
        for i ∈ 1:N
            J = I-δ(i,N)
            invD = (abs(A.D[I]+A.D[J])<2e-8) ? 0. : 2inv(A.D[I]+A.D[J])
            L[I,i] = invD*Lm(A.L[I,i]/scale)
        end
    end
    FieldMatrix(L,D,A.R)
end


text:
using MySignalProcessing
using Test

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

max_stars_repo_name: gjunqueira-sys/MySignalProcessing

max_issues_repo_name: gjunqueira-sys/MySignalProcessing

max_forks_repo_name: gjunqueira-sys/MySignalProcessing


text:
### observation simulation and beam fitting

## baseline coordinates
## arr: DataFrames with at least :X, :Y, :Z
## check at https://web.njit.edu/~gary/728/Lecture6.html

function calc_baselines(arr::AbstractDataFrame , lat=-23.0262015)

    coordinates= vcat(hcat(convert(Vector{Float64},arr[:X]))' ,
        hcat(convert(Vector{Float64},arr[:Y]))' ,
        hcat(convert(Vector{Float64},arr[:Z]))')
    rot= [0 -sind(lat) cosd(lat) ; 1 0 0 ; 0  cosd(lat)  sind(lat)]
    xyz= *(rot,coordinates)

    Nc= size(xyz)
    Nbl= convert(Int64,(Nc[2]*(Nc[2]-1))/2)
    bl= zeros(Float64,3,2Nbl)   ## symmetry of the bl

    ibl= 1
    for i in 1:Nc[2]
        for j in i+1:Nc[2]
            bl[1,ibl]= xyz[1,i]-xyz[1,j] ; bl[1,ibl+Nbl]= xyz[1,j]-xyz[1,i]
            bl[2,ibl]= xyz[2,i]-xyz[2,j] ; bl[2,ibl+Nbl]= xyz[2,j]-xyz[2,i]
            bl[3,ibl]= xyz[3,i]-xyz[3,j] ; bl[3,ibl+Nbl]= xyz[3,j]-xyz[3,i]
            ibl += 1
        end
    end
    return(bl)
end

####
### bl: baselines computed in calc_baselines
### h0: hour angle in degrees
### d0: source declination in degrees
### only snapshot still...
function calc_uv(bl, h0=0, d0=-50)

    h0 *= 15   #hours to degree
    proj= [sind(h0) cosd(h0) 0 ; -sind(d0)cosd(h0) sind(d0)sind(h0) cosd(d0) ; cosd(d0)cosd(h0) -cosd(d0)sind(h0) sind(d0)]
    uv= *(proj, bl)
    return(uv)
end

function calc_uv_coverage
    ## will compute the uv_coverage with an observing and sampling time ..
    ## for now only a snapshot.
    ## ...
end

################################
## setup the npix,fov, freq, etc for the beam extraction from the uv
## coverage. It is based on the uniform weighting 2/FOV for the uv-cell
##
function calc_dirtybeam(uv, npix=511, sizefit=255 ; robust=2)
    c= 299792458.0  ; ν= 100*1e9 ; λ= c / ν
    D= 12 ; PB= 1.13 * λ / D
    duv= 2/(PB*npix) ; ds= duv/λ
    dr= 180*3600/(π*ds*npix)
    lmax= maximum(abs.(uv))

    if (duv*npix/2) < lmax
        println("##UV-gridding error, npix too small...")
    end

    binuv= range(-duv*npix/2, stop=duv*npix/2, length=npix)
    Hh= fit(Histogram, (uv[1,:] , uv[2,:]) , (binuv , binuv))
    H= Hh.weights

    ## Robust weighting R (Briggs)
    ## R=-2 : uniform
    ## R=2  : natural
    ## R=0.5: "briggs"
    Hsum= sum(H)
    H2sum= sum(1 ./ H[H .> 0].^2)/Hsum
    f2= (5 * 10.0^(-robust))^2 * H2sum
    H2 = H ./ (1 .+ f2 .* H)

    h= fft(H2)
    hshift= fftshift(abs.(real.(h)))

    center= npix/2
    coord_a= convert(Int64,center-sizefit/2)
    coord_b= convert(Int64,center+sizefit/2)

    hshiftcut= hshift'[coord_a:coord_b, coord_a:coord_b]
    return(hshiftcut , dr)
end

## fitting of the Gaussian 2D for the beam
## assuming offset=0 for the beam

function gaussian2D(x,y, amplitude, xo, yo, σx, σy, θ)

    a = (cosd(θ)^2)/(2σx^2) + (sind(θ)^2)/(2*σy^2)
    b = -(sind(2θ))/(2σx^2) - (sind(2θ))/(2σy^2)
    c = (sind(θ)^2)/(2σx^2) + (cosd(θ)^2)/(2σy^2)
    gauss2d= amplitude*exp( -( a*((x-xo)^2) + 2b*(x-xo)*(y-yo) + c*((y-yo)^2)) )
    return(gauss2d)
end

#################################
function fit_beam(beam , dr)
    bs= size(beam)
    h= reshape(beam,(bs[1]*bs[2],))

    xy= zeros(Float64,bs[1]*bs[2], 2)

    for i in 1:bs[1]
        for j in 1:bs[2]
            xy[(i-1)*bs[1]+j,1]= i
        end
    end

    for i in 1:bs[1]
        for j in 1:bs[2]
            xy[(i-1)*bs[1]+j,2]= bs[2]+1-j
        end
    end

    @. multimodel(x, p) = gaussian2D(x[:,1], x[:,2], p[1], p[2] , p[3] , p[4] , p[5], p[6])
    p0 = [maximum(beam) , bs[1]/2 , bs[2]/2 , 1, 1, 0]
    f= curve_fit(multimodel, xy, h, p0)

    gaussian_sigma_to_fwhm=2.3548200450309493

    ## some bad fitting turn to be negative....
    bx= abs(f.param[4]*dr*gaussian_sigma_to_fwhm)
    by= abs(f.param[5]*dr*gaussian_sigma_to_fwhm)

    e= max(bx/by, by/bx)
    ar= sqrt(bx*by)
    sidelobe= maximum(abs.(f.resid * 100 / f.param[1]))

    b = synthbeam(bx, by,ar,e, sidelobe)

    return(b)
end

#################
### MRS in arcsec at 100 GHz
function calc_mrs(uv)
    minbl = minimum(uv[:,1].^2 .+ uv[:,2].^2)
    lmin= sqrt(minbl)
    ν= 100

    mrs= 37100 / (lmin*ν)
    return(mrs)
end

max_stars_repo_name: bosscha/GASS

max_issues_repo_name: bosscha/GASS

max_forks_repo_name: bosscha/GASS


text:
points = [
    3im
    1 + im
    0im
    -1 - im
    0 - 2im
    1.5 + 0.5im
    2im
    -1.5 + 0.5im
    0 - 2im
    1 - im
    0im
    -1 + im
]

function draw_curve_and_tangents(points)
    newdraw()
    draw_curve(points, color = :black, line = 3)

    S = Spline(points, :closed)
    n = npatches(S)

    d = 1 / 3
    T = 1:d:n+1-d

    for t in T
        tt = t + d / 3
        v = S'(tt)
        v /= 2 * abs(v)
        draw_vector(v, S(tt), color = :green)
    end

    finish()
end

function tangent_plot(points)
    S = Spline(points, :closed)
    f(t) = angle(S'(t)) / (2pi)
    plot(f, 0.99, npatches(S) + 1.01)
    plot!(legend = false)
end


text:
using SparseArrays

abstract type GraphDataType end

mutable struct AdjacencyList <: GraphDataType
    flist::Vector{Array{Int64}}
    flist_w::Vector{Array{Float64}}
    blist::Vector{Array{Int64}}
    blist_w::Vector{Array{Float64}}

    directed::Bool
end

function Base.show(io::IO, p::AdjacencyList)
    dire = "directed"
    if !p.directed
        dire = "undirected"
    end

    print(io, "AdjacencyList: $dire")
end

function AdjacencyList(mat::SparseMatrixCSC)

    flist = Array{Int64}[]
    flist_w = Array{Float64}[]
    blist = Array{Int64}[]
    blist_w = Array{Float64}[]
    directed = false

    for i = 1:mat.m
        vec = findall(x -> x > 0, mat[i, :])
        push!(flist, vec)
        push!(flist_w, mat[i, vec'])
    end

    for i = 1:mat.n
        vec = findall(x -> x > 0, mat[:, i])
        push!(blist, vec)
        push!(blist_w, mat[vec', i])
    end

    if mat != mat'
        directed = true
    end

    return AdjacencyList(flist, flist_w, blist, blist_w, directed)

end

import Graphs.LinAlg.adjacency_matrix
function adjacency_matrix(adj_list::AdjacencyList)
    n = length(adj_list.flist)
    mat = zeros(n, n)
    for i = 1:n
        row = adj_list.flist[i]
        j = 1
        for r in row
            mat[i, r] = adj_list.flist_w[i][j]
            j = j + 1
        end
    end

    return SparseMatrixCSC(mat)

end

function edge_list(adj_matrix::SparseMatrixCSC)
    b = []
    weigth = 0
    for c in 1:adj_matrix.m
        for r in 1:adj_matrix.n
            weight = adj_matrix[r, c]
            if weight > 0
                push!(b, [r, c, weight])
            end
        end
    end
    b
end

function edge_list_to_matrix(adj_list)

    dim = 0.0
    for vec in adj_list
        m = maximum([vec[1], vec[2]])
        if m > dim
            dim = m
        end
    end
    dim = trunc(Int, dim)

    adj_mat = zeros(dim, dim)
    for node in adj_list
        if length(node) > 2
            adj_mat[trunc(Int, node[1]), trunc(Int, node[2])] = node[3]
        else
            adj_mat[trunc(Int, node[1]), trunc(Int, node[2])] = 1
        end
    end
    return SparseMatrixCSC(adj_mat)
end

max_stars_repo_name: tragisch/NetworkOptimization

max_issues_repo_name: tragisch/NetworkOptimization

max_forks_repo_name: tragisch/NetworkOptimization


text:
import Adapt

"""
    BoundaryCondition{C<:BCType}(condition)

Construct a boundary condition of type `C` with a `condition` that may be given by a
number, an array, or a function with signature:

    condition(i, j, grid, time, iteration, U, Φ, parameters) = # function definition

that returns a number and where `i` and `j` are indices along the boundary.

Boundary condition types include `Periodic`, `Flux`, `Value`, `Gradient`, and `NoPenetration`.
"""
struct BoundaryCondition{C<:BCType, T}
    condition :: T
end

BoundaryCondition(Tbc, c) = BoundaryCondition{Tbc, typeof(c)}(c)

bctype(bc::BoundaryCondition{C}) where C = C

# Adapt boundary condition struct to be GPU friendly and passable to GPU kernels.
Adapt.adapt_structure(to, b::BoundaryCondition{C, A}) where {C<:BCType, A<:AbstractArray} =
    BoundaryCondition(C, Adapt.adapt(to, parent(b.condition)))

#####
##### Some abbreviations to make life easier.
#####

# These type aliases make dispatching on BCs easier (not exported).
const BC   = BoundaryCondition
const FBC  = BoundaryCondition{<:Flux}
const PBC  = BoundaryCondition{<:Periodic}
const NPBC = BoundaryCondition{<:NoPenetration}
const VBC  = BoundaryCondition{<:Value}
const GBC  = BoundaryCondition{<:Gradient}
const NFBC = BoundaryCondition{Flux, Nothing}

# More readable BC constructors for the public API.
     PeriodicBoundaryCondition() = BoundaryCondition(Periodic,      nothing)
NoPenetrationBoundaryCondition() = BoundaryCondition(NoPenetration, nothing)
       NoFluxBoundaryCondition() = BoundaryCondition(Flux,          nothing)

    FluxBoundaryCondition(val) = BoundaryCondition(Flux, val)
   ValueBoundaryCondition(val) = BoundaryCondition(Value, val)
GradientBoundaryCondition(val) = BoundaryCondition(Gradient, val)

# Multiple dispatch on the type of boundary condition
getbc(bc::BC{C, <:Number}, args...)              where C = bc.condition
getbc(bc::BC{C, <:AbstractArray}, i, j, args...) where C = bc.condition[i, j]
getbc(bc::BC{C, <:Function}, args...)            where C = bc.condition(args...)

Base.getindex(bc::BC{C, <:AbstractArray}, inds...) where C = getindex(bc.condition, inds...)


text:
using LinearAlgebra

function TLSesprit(Y,K,m=0)
    # Estimation of signal parameters via rotational invariance techniques
    # (ESPRIT) algorithm for line spectral estimation from measurements.
    # This is an augmented version of ESPRIT which uses a total least-squares
    # (TLS) step for improved performance.
    # Can handle multiple snapshots by constructing a low rank Hankel matrix
    # from the data.
    #
    # Inputs:
    # Y: Data matrix
    # K: number of sinusoids
    # m: Hankel parameter of the Hankel matrix of the data
    #
    # Parameters:
    # N = size(Y,1): number of measurements per snapshot
    # L = size(Y,2): number of snapshots
    #
    # Output:
    # f_hat: estimate of the frequencies of the K sinusoids in [rad]

    (N,L) = size(Y)

    if m == 0
    m = ceil(Int,N/2)
    end

    C = zeros(m,m)
    for j = 1:L
        for i = m : N
            C = C + Y[i-m+1:i,j]*Y[i-m+1:i,j]'/(L*N);
        end
    end

    N = m
    svdC = svd(C)
    V1 = svdC.U[1:N-1,1:K]
    V2 = svdC.U[2:N,1:K]

    #evdC = eigen(C)
    #p = sortperm(real(evdC.values),rev=true)[1:K]
    #V1 = evdC.vectors[1:N-1,p]
    #V2 = evdC.vectors[2:N,p]

    svdV1V2 = svd(hcat(V1,V2))
    E = svdV1V2.V
    E12 = E[1:K,(K+1):2*K]
    E22 = E[(K+1):2*K,(K+1):2*K]

    phi = -E12/E22

    f_hat = ((angle.(eigvals(phi)))/(2*pi) .+ 1).%1
end


text:
module TestBaseline

using Random
using Test
using DataFrames: nrow
using AMLPipelineBase

function test_baseline()
    Random.seed!(123)
    iris=getiris()
    features=iris[:,1:4]
    labels=iris[:,5] |> collect
    bl = Baseline()
    fit!(bl,features,labels)
	 @test bl.model[:choice] == "setosa"
    @test sum(transform!(bl,features) .== repeat(["setosa"],nrow(iris))) == nrow(iris)
    @test sum(fit_transform(bl,features,labels) .== repeat(["setosa"],nrow(iris))) == nrow(iris)
    idy = Identity()
    fit!(idy,features,labels)
    @test (transform!(idy,features) .== features) |> Matrix |> sum == 150*4
    @test (fit_transform(idy,features) .== features) |> Matrix |> sum == 150*4
end
@testset "Baseline Tests" begin
  test_baseline()
end

end


text:
using Base.Test
using DataFrames

let
	autocor(DataArray([1, 2, 3, 4, 5]))
end


text:
module XLargerYs

	export XLargerY
	import Base: length

	struct XLargerY{T <: Real}
		x::Vector{T}
		y::Vector{T}
		Δ::Vector{Int64} # How many steps to make in x before y needs to be increased
		N::Int64 # Number of combinations of x and y

		# Basic constructor
		function XLargerY(x::AbstractVector{T}, y::AbstractVector{T}, Δ::AbstractVector{<: Integer}) where T <: Real
			@assert all(Δ .> 0)
			@assert length(x) >= maximum(Δ)
			@assert length(y) == length(Δ)
			return new{T}(x, y, Δ, sum(Δ))
		end

		# Constructor if Δ has to be determined
		function XLargerY(x::AbstractVector{T}, y::AbstractVector{T}) where T <: Real
			# Check if sorted
			if any(diff(x) .<= 0) || any(diff(y) .<= 0)
				error("x and y must be sorted and cannot contain duplicates")
			end
			# Only use combinations where y > x
			Δ = Vector{Int64}(undef, length(y))
			local i
			local j = 1
			@inbounds for outer i = 1:length(y)
				for outer j = j:length(x)
					x[j] > y[i] && break
				end
				if x[j] > y[i]
					j -= 1
				else
					break
				end
				Δ[i] = j
			end
			# Fill remaining elements up with maximum possible Δ
			Δ[i:end] .= length(x)
			return new{T}(x, y, Δ, sum(Δ))
		end
	end

	"""
		 XLargerYs.iterate(xly, loop2, loop1)

		 Two loops, one for y (outer) and one for x (inner).
		 For your purposes, use a vector with the length of XLargerY.N.
		 In each iteration of y, the respective elements in that array are in i:j (x varies over these).

		 loop2: iterate through y.
		 Do everything independent of x here.
		 To get the respective y use `xly.y[n]`.

		 loop1: x varies
		 To get the respective x use `xly.x[m]`.
		 Additionally, index `l` is provided according to `l = i:j`.

		 No @inbounds is used.
	"""
	macro iterate(xly, loop2, loop1)
		esc(quote
			local i = 1
			for (n, δ) = enumerate($xly.Δ)
				j = i + δ - 1
				$loop2
				for (m, l) = enumerate(i:j)
					$loop1
				end
				i += δ
			end
		end)
	end

	function convert(::Type{XLargerY{<: T}}, b::XLargerY) where T
		XLargerY(convert(T, b.x), convert(T, b.y), b.Δ)
	end

	@inline function length(xly::XLargerY)
		xly.N
	end

	function combinations(xly::XLargerY{T})::Vector{NTuple{2, T}} where T <: Real
		q = Vector{NTuple{2, T}}(undef, xly.N)
		@iterate(
			xly,
			# Do nothing in the outer loop
			nothing,
			# Store x and y in the inner loop
			q[l] = (xly.x[m], xly.y[n])
		)
		return q
	end

end


text:
using CSV
using Statistics
using DataFrames

cd(@__DIR__)
fedfunds = CSV.read("fedfunds.txt"; header = 0)
deflator = CSV.read("gnpdeflator.txt", header = 0)
rgdp = CSV.read("realgnp.txt", header = 0)

irate = Vector{Float64}()
for i = 1:3:length(fedfunds[:, 3])
    push!(irate, mean(fedfunds[i:i+2, 3]))
end

infl = diff(log.(deflator[:, 3])) * 100
drgdp = diff(log.(rgdp[:, 3])) * 100

kilian_data = DataFrame(drgdp = drgdp, irate = irate, infl = infl)

CSV.write("../kilian_data.csv", kilian_data)


text:
using DrWatson
@quickactivate "NonlinearDynamicsTextbook"
include(srcdir("colorscheme.jl"))
using GLMakie, DynamicalBilliards, InteractiveDynamics

# Set style to book colors
InteractiveDynamics.obcolor(::Antidot) = to_color(COLORS[1])
InteractiveDynamics.obcolor(::Obstacle) = to_color(COLORS[1])
InteractiveDynamics.obfill(o::Antidot) = RGBAf0(0,0,0,0)
InteractiveDynamics.obls(::Antidot) = nothing

max_stars_repo_name: JuliaDynamics/NonlinearDynamicsTextbook

max_issues_repo_name: JuliaDynamics/NonlinearDynamicsTextbook

max_forks_repo_name: JuliaDynamics/NonlinearDynamicsTextbook


text:
# This Example requires
#   * JuLIP.jl,
#   * atomistica
#   * Isaac.jl
#

using JuLIP, JuLIP.Potentials, SaddleSearch, Optim
using Isaac

using PyCall
@pyimport atomistica
kumagai() = JuLIP.ASE.ASECalculator(atomistica.KumagaiScr())
tersoff() = JuLIP.ASE.ASECalculator(atomistica.TersoffScr())
sw() = StillingerWeber()

function vacancy_saddle(L)
    at = bulk("Si", cubic=true, pbc = true) * L
    xv = positions(at)[1]
    deleteat!(at, 1)
    X = positions(at)
    xn = X[1]
    @assert norm(xv - xn) ≈ rnn("Si")
    X[1] = 0.5 * (xv + xn)
    set_positions!(at, X)
    v0 = zeros(length(at) * 3)
    v0[1:3] = xn - xv
    # v0 += 0.01 * (rand(v0) - 0.5)

    # set_constraint!(at, JuLIP.Constraints.FixedCell(at, clamp = [10]))
    set_constraint!(at, JuLIP.Constraints.FixedCell(at))
    set_calculator!(at, kumagai())
    return at, v0
end

L = 8
at, v0 = vacancy_saddle(L)
x0 = dofs(at)

E = xx -> energy(at, xx)
dE = xx -> gradient(at, xx)

Estab = xx -> energy(at, xx) + 0.5 * norm(xx[1:3] - x0[1:3])^2
dEstab = xx -> gradient(at, xx) + [xx[1:3] - x0[1:3]; zeros(length(x0)-3)]
dE0 = dE(x0)

function check_saddle(x0)
   x = copy(x0)
   H = zeros(length(x0), length(x0))
   h = 1e-7
   dE0 = dE(x)
   for n = 1:length(x0)
      x[n] += h
      H[:, n] = (dE(x) - dE0) / h
      x[n] -= h
   end
   σ = sort(eigvals(Symmetric(H)))
   return σ
end

# NewtonKrylov - I
nkI = NK(len = 1e-4, verbose=1, maxnumdE = 500, maxstep = 0.2,
         krylovinit = :resrot )
x1, gcalls = run!(nkI, Estab, dEstab, x0, v0)
println("  NK(I): gcalls =  ", gcalls, "     | res = $(norm(dE(x1)))")
L <= 4 && println("         σ[1:6] = ", check_saddle(x1)[1:6])

# Superlinear - I
sld = SuperlinearDimer( maximum_translation=0.2, max_num_rot=1, maxnumdE=500,
                          verbose=1 )
x3, v, res = run!(sld, E, dE, x0, v0)
println("  SLD(I): gcalls = ", SaddleSearch.numdE(res)[end], "    | res = $(norm(dE(x3), Inf))")
L <= 4 && println("          σ[1:6] = ", check_saddle(x3)[1:6])
println("          |x_nk - x_sld| = ", norm(x1 - x3, Inf))

# NewtonKrylov - P
nkP = NK(len = 1e-4, verbose=1, maxnumdE = 500, maxstep = 0.2,
         krylovinit = :res,
         precon = JuLIP.Preconditioners.Exp(at),
         precon_prep! = (P, x) -> JuLIP.update!(P, at, x).amg.A)
x1P, gcalls = run!(nkP, Estab, dEstab, x0, v0)
println("  NK(EXP): gcalls =  ", gcalls, "     | res = $(norm(dE(x1P)))")
L <= 4 && println("           σ[1:6] = ", check_saddle(x1P)[1:6])
println("           |x_nk - x_nkP| = ", norm(x1 - x1P, Inf))

# NewtonKrylov - FF
nkFF = NK(len = 1e-4, verbose=1, maxnumdE = 500, maxstep = 0.2,
         krylovinit = :resrot,
         precon = JuLIP.Preconditioners.FF(at, sw()),
         precon_prep! = (P, x) -> JuLIP.update!(P, at, x).amg.A)
x1FF, gcalls = run!(nkFF, Estab, dEstab, x0, v0)
println("  NK(FF): gcalls =  ", gcalls, "     | res = $(norm(dE(x1FF)))")
L <= 4 && println("          σ[1:6] = ", check_saddle(x1FF)[1:6])
println("          |x_nk - x_nkFF| = ", norm(x1 - x1FF, Inf))

# # Superlinear - P
# sldP = SuperlinearDimer( maximum_translation=0.2, max_num_rot=1, maxnumdE=500,
#                           verbose=1,
#                           precon = JuLIP.Preconditioners.Exp(at),
#                           precon_prep! = (P, x) -> JuLIP.update!(P, at, x) )
# x3P, v, res = run!(sldP, Estab, dEstab, x0, v0)
# println("  SLD: gcalls = ", SaddleSearch.numdE(res)[end], "    | res = $(norm(dE(x3P), Inf))")
# L <= 4 && println("       σ[1:6] = ", check_saddle(x3P)[1:6])
# println("       |x_nk - x_sldP| = ", norm(x1 - x3P, Inf))

# function runsaddle(init, LL; verbose = 1)
#     gcalls_nk = Int[]
#     gcalls_nk_exp = Int[]
#     gcalls_nk_ff = Int[]
#
#     for L in LL
#         at, v0 = init(L)
#         X0 = positions(at)
#         println("len(at) = ", length(at))
#
#         E = x -> energy(set_dofs!(at, x))
#         dE = x -> gradient(set_dofs!(at, x))
#
#
#         # NewtonKrylov  (ID)
#         set_positions!(at, X0)
#         nkI = NK(len = 1e-4, verbose=3, maxnumdE = 100, maxstep = 0.1,
#                   krylovinit = :res,
#                   precon = JuLIP.Preconditioners.Exp(at),
#                   precon_prep! = (P, x) -> JuLIP.update!(P, at, x).amg.A)
#         x0 = dofs(at)
#         x0 += 0.01 * rand(x0)
#         x, gcalls = run!(nkI, E, dE, dofs(at), v0)
#         println("    >> gcalls(NK-I) =  ", gcalls, "     | res = $(norm(dE(x)))")
#         push!(gcalls_nk, gcalls)
#     end
# end
#
#
# # LL = [2, 4, 8, 16]
#
# runsaddle(vacancy_saddle, [4])

# at, v0 = vacancy_saddle(4)
# println("len(at) = ", length(at))
# E = x -> energy(set_dofs!(at, x))
# T = x -> 0.5 * sum(sum(reshape(x, 3, length(x) ÷ 3), 2).^2)
# dT = x -> ForwardDiff.gradient(T, x)
# dE = x -> gradient(set_dofs!(at, x)) + dT(x)
#
# x = dofs(at)
# N = length(x)
# H = zeros(N, N)
# g0 = dE(x)
# h = 1e-6
# for n = 1:N
#    x[n] += h
#    H[:, n] = (dE(x) - g0) / h
#    x[n] -= h
# end
# H = 0.5 * (H + H')
#
# λ = eigvals(H)
# @show λ[1:11]

# TESTING HOW THE HESSIAN BEHAVES
# H = zeros(length(x0), length(x0))
# h = 1e-7
# x = copy(x0)
# for n = 1:length(x0)
#    x[n] += h
#    H[:, n] = (dE(x) - dE0) / h
#    x[n] -= h
# end
# σ = sort(eigvals(Symmetric(H)))
# @show σ[1:6]

# b = dE0
# V0 = [b v0]
# blocklanczos( dE0, dE, x0, 0.5 * norm(b), 100;
#       P = I, b = b, V0 = V0,
#       eigatol = 1e-1, eigrtol = 1e-1,
#       debug = true, h = 1e-7 )

# TESTING HOW THE HESSIAN BEHAVES

# b = dE0
# V0 = [b v0]
# blocklanczos( dE0, dE, x0, 0.5 * norm(b), 100;
#       P = I, b = b, V0 = V0,
#       eigatol = 1e-1, eigrtol = 1e-1,
#       debug = true, h = 1e-7 )


text:
using Gadfly, RDatasets, Dates

set_default_plot_size(6inch, 3inch)

approval = dataset("Zelig", "approval")
dates = Date[Date(y, m)
             for (y, m) in zip(approval[:Year], approval[:Month])]
approval[:Date] = dates

p = plot(approval, x="Date", y="Approve", Geom.line)


text:
include("bm_test.jl")
include("bm_drift_test.jl")
include("brownian_bridge_test.jl")
include("first_time_test.jl")
include("poisson_test.jl")

using Base.Test
using StochasticProcesses

t=linspace(0, 1, 10)

let process = GeometricBrownianMotion(1., .1, 100)
  @test size(cumsim(process, t, 3)) == (10, 3)
  @test length(sim(process, t, 3)) == 3
  distribution(process, 0)
  distribution(process, 10);
  rand(process, t, 10)
end

let process = ItoIntegral((t, b)->t)
  @test size(cumsim(process, t, 3)) == (10, 3)
  @test length(sim(process, t, 3)) == 3
  rand(process, t, 10)
end

let process = SDE((x,y)->x, (x,y)->y, 0.)
  @test size(cumsim(process, t, 3)) == (10, 3)
  @test length(sim(process, t, 3)) == 3
  rand(process, t, 10)
end

let process = CompositeProcess(BrownianMotion(), (t, y) -> y.^2)
  @test size(cumsim(process, t, 3)) == (10, 3)
  @test length(sim(process, t, 3)) == 3
  rand(process, t, 10)
end


text:
using Random, Distributions, FreqTables, Statistics
using LinearAlgebra
using JLD2, JLD, CSV, DataFrames

Random.seed!(1234);

function q1()
    #Initializing variables and practice with basic matrix operations
    # 1a
    A = rand(Uniform(-5,10), 10,7)

    # i
    B = rand(Normal(-2, 15), 10, 7)

    # ii
    C = [A[1:5, 1:5] B[1:5, end-1:end:-1]] #TODO Check latter

    # iii
    D = copy(A)
    D[A .> 0] .= 0
    D

    length(A)

    # 1c
    unique(D) |> length

    # 1d
    E = reshape(B, (length(B),1))

    # 1e
    F = cat(A, B, dims=3)

    # 1f
    #F = permutedims(F, (3,1,2))

    # 1g
    G = kron(B, C)
    #kron(C,F)

    # 1h
    save("./PS1-julia-intro/matrixpractice.jld",
        "A", A,
        "B", B,
        "C", C,
        "D", D,
        "E", E,
        "F", F,
        "G", G)

    # 1i
    save("./PS1-julia-intro/firstmatrix.jld", "A", A,"B", B, "C", C, "D", D)

    # 1j
    convert(DataFrame, C) |> CSV.write("./PS1-julia-intro/Cmatrix.csv", )

    # 1k
    convert(DataFrame, D) |> CSV.write("./PS1-julia-intro/Dmatrix.csv", delim="\t")

    return A, B, C, D

end

function q2(A,B,C)
#  Practice with loops and comprehensions
# 2a
    AB = [x*y for (x,y) in zip(A, B)]

    AB2 = A .* B

    # 2b

    Cprime = Vector{Float64}()
    for i in C
        if  -5 <= i  <= 5.0
            append!(Cprime, i)
        end
    end

    Cprime2 = C[-5 .<= C .<= 5]

    # 2c
    N = 15169
    K = 6
    T = 5
    X = zeros(N,K,T)
    for t in 1:T
        X[:,1,t] .= ones(N) # stationary over time.
        X[:,2,t] .= rand(Bernoulli(.75*(6-t)/5), N)
        X[:,3,t] .= rand(Normal(15+t-1, 5*(t-1)), N)
        X[:,4,t] .= rand(Normal(π*(6-t)/3, 1/ℯ), N)
        X[:,5,t] .= rand(Binomial(20, 0.6), N)
        X[:,6,t] .= rand(Binomial(20,0.5),N) # Discrete normal stationary over time.
    end
    # 2d

    β = zeros(K,T)
    β[1,:] .= [1 + t*(.25) for t in 1:T] # d1
    β[2,:] .= [log(t) for t in 1:T] # d2
    β[3,:] .= [-sqrt(t) for t in 1:T] # d3
    β[4,:] .= [(ℯ^(t)  - ℯ^(t+1)) for t in 1:T] # d4
    β[5,:] .= [t for t in 1:T] # d5
    β[6,:] .= [t/3 for t in 1:T] # d6

    # 2e
    Y = zeros(N,T)
    for t in 1:T # How to use comprehensions in this case?
       Y[:,t] .= X[:,:,t]*β[:,t] + rand(Normal(0, .36), N)
    end
end

# 3
function q3()
    df = CSV.read("./PS1-julia-intro/nlsw88.csv")# |> dropmissing
    save("./PS1-julia-intro/nlsw88.jld.jld", "df", df)
    # 3b
    println((df.never_married |> sum)*100/nrow(df) |> round,"% sample has never been married")
    println((df.collgrad |> sum)*100/nrow(df) |> round,"% are college graduates")

    # 3c
    freqtable(df.race) |> prop
    # 3d
    summarystats = describe(df)
    println(df.grade .|> ismissing |> sum, " grades observations are missing")

    # 3e
    freqtable(df.occupation, df.industry) |> prop

    # 3f
    gdf = groupby(df, ["occupation","industry"], sort=true)
    combine(gdf, :wage => mean => :avg_ind_occ_wage) |> dropmissing
    return nothing
end

# Practice with functions
# 4a Load firstmatrix.jld.
function q4()
    load("./PS1-julia-intro/firstmatrix.jld")

    function matrixops(m1,m2)
        if size(m1) != size(m2)
            error("inputs must have the same size.")
        end
        #=
        Takes as inputs the matrices A and B from question (a) of problem 1 and has three outputs:
            (i) the element-by-element product of the inputs,
            (ii) the product A'B, and
            (iii) the sum of all the elements of A + B.
        =#
        return m1 .* m2, m1' * m2, m1 + m2
    end

    a,b, c = matrixops(A, B);

    df = CSV.read("./PS1-julia-intro/nlsw88.csv") |> dropmissing
    convert(Array,df.ttl_exp); convert(Array,df.wage);
    matrixops(
        df.ttl_exp,
        df.wage);
    return nothing
end

A, B, C, D = q1();
q2(A,B,C)
q3()
q4()


text:
module UnicodeSliders

# using UnicodePlots

export @manipulate

macro manipulate(args...)
    @assert length(args) == 1 # TODO: add error message

    for_block = args[1]
    @assert for_block.head == :for # TODO: add error message

    loop_vars = get_loop_vars(Val(for_block.args[1].head), for_block.args[1].args)
    var_exprs = init_loop_var.(loop_vars)

    pushfirst!(for_block.args[2].args, var_exprs...)

    # Clear console screen
    println("\33[2J")

    return for_block.args[2]
end

head_val(expr::Expr) = Val(expr.head)
args(expr::Expr) = expr.args

get_loop_vars(::Val{:block}, expr) = vcat(get_loop_vars.(head_val.(expr), args.(expr)))
get_loop_vars(::Val{:(=)}, expr) = (name=expr[1], range=eval(expr[2]))

init_loop_var(loop_var::NamedTuple{(:name, :range)}) =
    Expr(:(=), loop_var.name, loop_var.range[1])

# run_loop(loop)

end # module


text:
include("Draw.jl")

tl = open("../logs/timeLog.txt", "a")
T = time()
ags2 = (size(ARGS, 1) < 2) ? "20,20" : ARGS[2]
DrawNetwork(ARGS[1], ags2)
T = time() - T
println(tl, ARGS[1], " ", T)


text:
# Consider tuple case: out = (a1, a2, a3); how to properly record which has been initialized?
# Defined as an alias rather than wrapper.
# allocated is a dict where there is a key per allocated arg, mapping to a boolean value indicating whether it must be explicitly deallocated
struct InitializedVarTracker
    aliases::Dict{Symbol,Vector{Vector{Symbol}}}
    initialized::Set{Symbol}
    allocated::Dict{Symbol,Bool}
end
InitializedVarTracker() = InitializedVarTracker(Dict{Symbol,Vector{Vector{Symbol}}}(), Set{Symbol}(), Dict{Symbol,Bool}())

isinitialized(ivt::InitializedVarTracker, s::Symbol) = s ∈ ivt.initialized
isallocated(ivt::InitializedVarTracker, root::Symbol) = root ∈ keys(ivt.allocated)

"""
`b` is added as an alias to `a`.
Either of the two (but not both) may be a collection.
If `b` is a collection, this means that `a` was unpacked to produce `b`.
If `a` is a collection, this means that `b` is an aggregate.
"""
function add_aliases!(ivt::InitializedVarTracker, a::Symbol, b::Symbol)
    if a ∈ ivt.initialized
        push!(ivt.initialized, b)
    elseif b ∈ ivt.initialized
        push!(ivt.initialized, a)
    end
    if isallocated(ivt, a)
        ivt.allocated[b] = false
    end
    push!(get!(() -> Vector{Symbol}[], ivt.aliases, a), [b])
    push!(get!(() -> Vector{Symbol}[], ivt.aliases, b), [a])
    nothing
end
function add_aliases!(ivt::InitializedVarTracker, a::Symbol, B::Vector{Symbol})
    #A is a collection, aliasing all members of B
    if a ∈ ivt.initialized
        for b ∈ B
            push!(ivt.initialized, b)
        end
    elseif all(b -> b ∈ ivt.initialized, B)
        push!(ivt.initialized, a)
    end
    if isallocated(ivt, a)
        for b ∈ B
            ivt.allocated[b] = false
        end
    end
    push!( get!(() -> Vector{Symbol}[], ivt.aliases, a),  B )
    for b ∈ B
        push!(get!(() -> Vector{Symbol}[], ivt.aliases, b), [Symbol("####AGGREGATE####"), a])
    end
    nothing
end
function add_aliases!(ivt::InitializedVarTracker, A::Vector{Symbol}, b::Symbol)
    #A is a collection, aliasing all members of B
    if b ∈ ivt.initialized
        for a ∈ A
            push!(ivt.initialized, a)
        end
    elseif all(a -> a ∈ ivt.initialized, A)
        push!(ivt.initialized, b)
    end
    if any(a -> isallocated(ivt, a), A)
        ivt.allocated[b] = false
    end
    for a ∈ A
        push!(get!(() -> Vector{Symbol}[], ivt.aliases, a), [Symbol("####AGGREGATE####"), b])
    end
    push!( get!(() -> Vector{Symbol}[], ivt.aliases, b),  A )
    nothing
end
function add_aliases!(ivt::InitializedVarTracker, a::Symbol, B)
    Bsyms = Symbol[s for s ∈ B if s isa Symbol]
    add_aliases!(ivt, a, Bsyms)
end
function add_aliases!(ivt::InitializedVarTracker, A, b::Symbol)
    Asyms = Symbol[s for s ∈ A if s isa Symbol]
    add_aliases!(ivt, Asyms, b)
end

"""
Return value indicates whether it must uninitialize arg
"""
function initialize!(ivt::InitializedVarTracker, pass::Vector{Any}, root::Symbol, skip::Symbol, mod::Symbol)
    root ∈ ivt.initialized && return false
    push!(ivt.initialized, root)
    root ∈ keys(ivt.aliases) || return true
    must_declare_uninitialized = true
    # We're traversing a diverging tree. We just have to move through all branches of each node and avoid back tracking.
    # Each node can only map to up to 1 collection of components.
    # ie, if it is declared a collection of one set, it cannot then be declared of another set.
    for alias ∈ ivt.aliases[root]
        a = first(alias)
        if length(alias) == 1
            if a !== skip
                must_declare_uninitialized &= initialize!(ivt, pass, a, root, mod)
            end
        else
            if a === Symbol("####AGGREGATE####")
                # then rooot is a member of collection A, corresponding specifically to that found in alias[3]
                A = alias[2]
                if A !== skip
                    init = false
                    for aalias ∈ ivt.aliases[A]
                        if root ∈ aalias
                            init = all(s -> s ∈ ivt.initialized, ivt.aliases[A])
                            break
                        end
                    end
                    if init
                        must_declare_uninitialized &= initialize!(ivt, pass, A, root, mod)
                    end
                end
            else # root is a collection
                # Check if we're supposed to skip
                any(s -> s === skip, alias) && continue
                if any(s -> s ∈ ivt.initialized, alias)
                    must_declare_uninitialized = false
                    for a ∈ alias
                        if a ∉ ivt.initialized
                            push!(pass, :($mod.zero_initialize!($a)))
                            initialize!(ivt, pass, a, root, mod)
                        end
                    end
                else# all must be uninitialized
                    for a ∈ alias
                        must_declare_uninitialized &= initialize!(ivt, pass, a, root, mod)
                    end
                end
            end
        end
    end
    must_declare_uninitialized
end

function deallocate!(ivt::InitializedVarTracker, deallocated::Vector{Symbol}, root::Symbol, skip::Symbol )
    if isallocated(ivt, root)
        ivt.allocated[root] && push!(deallocated, root)
        delete!(ivt.allocated, root)
    end
    root ∈ keys(ivt.aliases) || return deallocated
    for alias ∈ ivt.aliases[root]
        a = first(alias)
        if length(alias) == 1
            a === skip || deallocate!(ivt, deallocated, a, root)
        elseif first(alias) === Symbol("####AGGREGATE####")
            # then rooot is a member of collection A
            A = alias[2]
            A === skip || union!(deallocated, deallocate!(ivt, deallocated, A, root))
        else # root is a collection
            for a ∈ alias
                a === skip || union!(deallocated, deallocate!(ivt, deallocated, a, root))
            end
        end
    end
    deallocated
end
function deallocate!(ivt::InitializedVarTracker, root::Symbol)
    deallocate!(ivt, Symbol[], root, root)
end

function allocate!(ivt::InitializedVarTracker, a::Symbol)
    ivt.allocated[a] = true
    nothing
end
function allocate!(ivt::InitializedVarTracker, pass::Vector{Any}, a::Symbol, mod)
    ivt.allocated[a] = true
    push!(pass, :($mod.lifetime_start!($a)))
    nothing
end

# function uninitialize!(ivt::InitializedVarTracker, pass::Vector{Any}, root::Symbol, skip::Symbol, mod::Symbol)
#     push!(ivt.uninitialized, root)
#     # if any aliases are not uninitialized, we cannot endlife.
#     # So we search aliases to see if any are still live.
#     # if there are no aliases, we can go ahead and return true
#     root ∈ keys(ivt.aliases) || return true
#     # If any alias is not uninitialized, we return false
#     for alias ∈ ivt.aliases[root]
#         for a ∈ alias
#             search_for_uninitialized!(ivt, a, root) || return false
#         end
#     end
#     true
# end
# function search_for_uninitialized!(ivt, root::Symbol, skip::Symbol)
#     root ∈ ivt.uninitialized || return false
#     # if not uninitialized, we go ahead and abort

#     # We're traversing a diverging tree. We just have to move through all branches of each node and avoid back tracking.
#     # Each node can only map to up to 1 collection of components.
#     # ie, if it is declared a collection of one set, it cannot then be declared of another set.
#     for alias ∈ ivt.aliases[root]
#         a = first(alias)
#         if length(alias) == 1
#             if a !== skip
#                 search_for_uninitialized!(ivt, a, root) || return false
#             end
#         else
#             if first(alias) === Symbol("####AGGREGATE####")
#                 # then rooot is a member of collection A
#                 A = alias[2]
#                 if A !== skip
#                     search_for_uninitialized!(ivt, A, root) || return false
#                 end
#             else # root is a collection
#                 for a ∈ alias
#                     if a !== skip
#                         search_for_uninitialized!(ivt, a, root) || return false
#                     end
#                 end
#             end
#         end
#     end
#     true
# end


text:
@doc """
Return a new processing key with the number incremented.
It checks for existing keys and returns a string with the next key to be used.

#### Arguments

* `d`: Dictionary containing existing keys
* `key_name`: Base of the

#### Returns

* AbstractString with new key name

#### Returns

```julia
results_storage = Dict()
results_storage[new_processing_key(results_storage, "FTest")] = 4
results_storage[new_processing_key(results_storage, "FTest")] = 49

# Dict(Any, Any) with 2 entries
#   "FTest1" => 4
#   "FTest2" => 49
```
""" ->
function new_processing_key(d::Dict, key_name::AbstractString)
    key_numb = 1
    key = string(key_name, key_numb)
    while haskey(d, key)
        key_numb += 1
        key = string(key_name, key_numb)
    end
    return key
end

@doc """
Find dictionary keys containing a string.

#### Arguments

* `d`: Dictionary containing existing keys
* `partial_key`: AbstractString you want to find in key names

#### Returns

* Array containg the indices of dictionary containing the partial_key

#### Returns

```julia
results_storage = Dict()
results_storage[new_processing_key(results_storage, "FTest")] = 4
results_storage[new_processing_key(results_storage, "Turtle")] = 5
results_storage[new_processing_key(results_storage, "FTest")] = 49

find_keys_containing(results_storage, "FTest")

# 2-element Array{Int64,1}:
#  1
#  3
```
""" ->
function find_keys_containing(d::Dict, partial_key::AbstractString)
    valid_keys = [startswith(i, partial_key) for i = collect(keys(d))]
    findin(valid_keys, true)
end

@doc """
Extract the path, filename and extension of a file

#### Arguments

* `fname`: AbstractString with the full path to a file

#### Output

* Three strings containing the path, file name and file extension

#### Returns

```julia
fileparts("/Users/test/subdir/test-file.bdf")

# ("/Users/test/subdir/","test-file","bdf")
```
""" ->
function fileparts(fname::AbstractString)
    if fname==""
        pathname  = ""
        filename  = ""
        extension = ""
    else
        separators = sort(unique([search(fname, '/', i) for i = 1:length(fname)]))
        pathname = fname[1:last(separators)]
        extension  = last(sort(unique([search(fname, '.', i) for i = 1:length(fname)])))
        filename = fname[last(separators)+1:extension-1]
        extension  = fname[extension+1:end]
    end

    return pathname, filename, extension
end

@doc """
Find the closest number to a target in an array and return the index

#### Arguments

* `list`: Array containing numbers
* `target`: Number to find closest to in the list

#### Output

* Index of the closest number to the target

#### Returns

```julia
_find_closest_number_idx([1, 2, 2.7, 3.2, 4, 3.1, 7], 3)

# 6
```
""" ->
function _find_closest_number_idx{T <: Number}(list::AbstractArray{T, 1}, target::Number)
    diff_array = abs(list .- target)
    targetIdx  = findfirst(diff_array , minimum(diff_array))
end

#######################################
#
# DataFrame manipulation
#
#######################################

function add_dataframe_static_rows(a::DataFrame, args...)
    debug("Adding column(s)")
    for kwargs in args
        debug(kwargs)
        for k in kwargs
            name = convert(Symbol, k[1])
            code = k[2]
            expanded_code = vec(repmat([k[2]], size(a, 1), 1))
            debug("Name: $name  Code: $code")
            DataFrames.insert_single_column!(a, DataFrames.upgrade_vector(expanded_code), size(a,2)+1)
            rename!(a, convert(Symbol, string("x", size(a,2))),  name)
        end
    end
    return a
end