text:
@testset "Monodromy" begin
    function toric_ed(A)
        d, n = size(A)
        @polyvar t[1:d] y[1:n] u[1:n]

        φ = map(j -> prod(i -> t[i]^A[i, j], 1:d), 1:n)
        Dφ = [differentiate(φ[i], t[j]) for i = 1:n, j = 1:d]

        F = [φ + y - u; Dφ' * y]

        # We sample a random t, find a normal vector on this point and then assemble
        # an u where we know the solution to.
        t_rand = randn(Float64, size(A, 1))
        null = nullspace(map(fi -> fi(t => t_rand), Dφ'))
        y_rand = null * randn(Float64, size(null, 2))
        u₀ = map(fi -> fi(t => t_rand), φ) + y_rand

        x₀ = complex.([t_rand; y_rand])

        F, u, u₀, x₀
    end

    @testset "monodromy_solve" begin
        F, p, p₀, x₀ = toric_ed([3 2 1 0; 0 1 2 3])

        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            max_loops_no_progress = 20,
            threading = false,
        )
        @test is_success(result)
        @test length(solutions(result)) == 21
        @test length(solutions(result, only_real = true)) >= 1
        @test result.statistics.ntrackedpaths ≥ 21
        @test result.statistics.nparametergenerations ≥ 1
        @test length(HC.UniquePoints(result.solutions).points) == 21
        @test isempty(sprint(show, result)) == false

        # test seed
        result2 = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            max_loops_no_progress = 20,
            threading = false,
            seed = result.seed,
        )
        @test result2.statistics.ntrackedpaths == result.statistics.ntrackedpaths

        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            max_loops_no_progress = 20,
            threading = true,
        )
        @test is_success(result)
        @test length(solutions(result)) == 21

        # test that timeout works
        result_timeout = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            timeout = 1e-12,
        )
        @test length(result_timeout.solutions) < 21

        # test input of length > 1
        result = monodromy_solve(F, [x₀ for _ = 1:30], p₀, parameters = p)
        @test length(solutions(result)) == 21

        # test with false input
        result = monodromy_solve(F, [rand(6) for _ = 1:10], p₀, parameters = p)
        @test result.returncode == :invalid_startvalue
        result = monodromy_solve(F, [x₀, rand(6)], p₀, parameters = p)
        @test length(solutions(result)) == 21

        # different distance function
        result = monodromy_solve(F, x₀, p₀, parameters = p, distance = (x, y) -> 0.0)
        @test length(solutions(result)) == 1

        # Test stop heuristic using too high target_solutions_count
        result = monodromy_solve(F, x₀, p₀, parameters = p, target_solutions_count = 25)
        @test is_heuristic_stop(result)
        # Test stop heuristic with no target solutions count
        result = monodromy_solve(F, x₀, p₀, parameters = p)
        @test is_heuristic_stop(result)
        # Test stop heuristic with no target solutions count
        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            strategy = Triangle(useweights = true),
        )
        @test is_heuristic_stop(result)

        # By group_actions=nothing we force that complex conjugation is not used.
        result2 = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            complex_conjugation = false,
            max_loops_no_progress = 100,
        )
        @test is_success(result2)

        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            done_callback = ((_, _) -> true),
        )
        @test length(result.solutions) == 2

        roots_of_unity(s) = begin
            t = cis(π * 2 / 3)
            t² = t * t
            (vcat(t * s[1], t * s[2], s[3:end]), vcat(t² * s[1], t² * s[2], s[3:end]))
        end

        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            max_loops_no_progress = 100,
            equivalence_classes = false,
            group_action = roots_of_unity,
        )
        @test length(result.solutions) == 21

        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            max_loops_no_progress = 100,
            complex_conjugation = false, # disable complex conjugation to test it as a group action.
            equivalence_classes = false,
            group_actions = (roots_of_unity, s -> (conj.(s),)),
        )
        @test length(result.solutions) == 21
        @test length(solutions(result)) == 21
        @test length(real_solutions(result)) < 21
        test_treeviews(result)

        # group_actions as a vector
        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            target_solutions_count = 21,
            max_loops_no_progress = 100,
            complex_conjugation = false,
            equivalence_classes = false,
            group_actions = [roots_of_unity, s -> (conj.(s),)],
        )
        @test length(result.solutions) == 21

        # equivalence classes
        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            equivalence_classes = true,
            target_solutions_count = 7,
            max_loops_no_progress = 100,
            group_actions = roots_of_unity,
        )
        @test length(result.solutions) == 7
        # Test that equivalence classes are on by default if we supply a group action
        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            group_action = roots_of_unity,
            max_loops_no_progress = 20,
        )
        @test length(result.solutions) == 7

        # Test affine tracking
        result = monodromy_solve(
            F,
            x₀,
            p₀,
            parameters = p,
            affine_tracking = true,
            group_action = roots_of_unity,
            target_solutions_count = 7,
            max_loops_no_progress = 200,
        )
        @test length(result.solutions) == 7

        # AbstractSystem as input
        F_p = SPSystem(F; parameters = p)
        result = monodromy_solve(
            F_p,
            x₀,
            p₀,
            affine_tracking = true,
            group_action = roots_of_unity,
            target_solutions_count = 7,
            max_loops_no_progress = 200,
        )
        @test length(result.solutions) == 7

        # test reuse strategies
        result = monodromy_solve(
            F_p,
            x₀,
            p₀,
            group_action = roots_of_unity,
            target_solutions_count = 7,
            reuse_loops = :all,
            max_loops_no_progress = 200,
        )
        @test length(result.solutions) == 7
        result = monodromy_solve(
            F_p,
            x₀,
            p₀,
            group_action = roots_of_unity,
            target_solutions_count = 7,
            reuse_loops = :random,
            max_loops_no_progress = 200,
        )
        @test length(result.solutions) == 7
        result = monodromy_solve(
            F_p,
            x₀,
            p₀,
            group_action = roots_of_unity,
            target_solutions_count = 7,
            reuse_loops = :none,
            max_loops_no_progress = 200,
        )
        @test length(result.solutions) == 7
    end

    @testset "Method of Moments" begin
        Random.seed!(130793)
        @polyvar a[1:3] x[1:3] s[1:3]

        f0 = a[1] + a[2] + a[3]
        f1 = a[1] * x[1] + a[2] * x[2] + a[3] * x[3]
        f2 = a[1] * (x[1]^2 + s[1]) + a[2] * (x[2]^2 + s[2]) + a[3] * (x[3]^2 + s[3])
        f3 = a[1] * (x[1]^3 + 3 * s[1] * x[1]) +
            a[2] * (x[2]^3 + 3 * s[2] * x[2]) +
            a[3] * (x[3]^3 + 3 * s[3] * x[3])
        f4 = a[1] * (x[1]^4 + 6 * s[1] * x[1]^2 + 3 * s[1]^2) +
            a[2] * (x[2]^4 + 6 * s[2] * x[2]^2 + 3 * s[2]^2) +
            a[3] * (x[3]^4 + 6 * s[3] * x[3]^2 + 3 * s[3]^2)
        f5 = a[1] * (x[1]^5 + 10 * s[1] * x[1]^3 + 15 * x[1] * s[1]^2) +
            a[2] * (x[2]^5 + 10 * s[2] * x[2]^3 + 15 * x[2] * s[2]^2) +
            a[3] * (x[3]^5 + 10 * s[3] * x[3]^3 + 15 * x[3] * s[3]^2)
        f6 = a[1] * (x[1]^6 + 15 * s[1] * x[1]^4 + 45 * x[1]^2 * s[1]^2 + 15 * s[1]^3) +
            a[2] * (x[2]^6 + 15 * s[2] * x[2]^4 + 45 * x[2]^2 * s[2]^2 + 15 * s[2]^3) +
            a[3] * (x[3]^6 + 15 * s[3] * x[3]^4 + 45 * x[3]^2 * s[3]^2 + 15 * s[3]^3)
        f7 = a[1] * (
            x[1]^7 + 21 * s[1] * x[1]^5 + 105 * x[1]^3 * s[1]^2 + 105 * x[1] * s[1]^3
        ) +
            a[2] * (
            x[2]^7 + 21 * s[2] * x[2]^5 + 105 * x[2]^3 * s[2]^2 + 105 * x[2] * s[2]^3
        ) +
            a[3] * (
            x[3]^7 + 21 * s[3] * x[3]^5 + 105 * x[3]^3 * s[3]^2 + 105 * x[3] * s[3]^3
        )
        f8 = a[1] * (
            x[1]^8 +
                28 * s[1] * x[1]^6 +
                210 * x[1]^4 * s[1]^2 +
                420 * x[1]^2 * s[1]^3 +
                105 * s[1]^4
        ) +
            a[2] * (
            x[2]^8 +
                28 * s[2] * x[2]^6 +
                210 * x[2]^4 * s[2]^2 +
                420 * x[2]^2 * s[2]^3 +
                105 * s[2]^4
        ) +
            a[3] * (
            x[3]^8 +
                28 * s[3] * x[3]^6 +
                210 * x[3]^4 * s[3]^2 +
                420 * x[3]^2 * s[3]^3 +
                105 * s[3]^4
        )
        f = [f0, f1, f2, f3, f4, f5, f6, f7, f8]

        S₃ = SymmetricGroup(3)
        relabeling(v) = map(p -> (v[1:3][p]..., v[4:6][p]..., v[7:9][p]...), S₃)

        @polyvar p[1:9]

        function sample_moments(_ = nothing)
            a₀ = rand(3)
            a₀ ./= sum(a₀)
            x₀ = randn(3)
            s₀ = rand(3) .* 2

            y₀ = [a₀; x₀; s₀]
            p₀ = [fᵢ(a => a₀, x => x₀, s => s₀) for fᵢ in f]
            y₀, p₀
        end

        y₀, p₀ = sample_moments()

        R = monodromy_solve(
            f - p,
            y₀,
            p₀;
            parameters = p,
            group_action = relabeling,
            parameter_sampler = last ∘ sample_moments,
            show_progress = false,
            max_loops_no_progress = 5,
        )
        @test length(solutions(R)) ≤ 225

        R = monodromy_solve(
            f - p,
            y₀,
            p₀;
            parameters = p,
            group_action = relabeling,
            target_solutions_count = 225,
            affine_tracking = true,
            parameter_sampler = last ∘ sample_moments,
            show_progress = false,
            max_loops_no_progress = 20,
        )
        @test length(solutions(R)) == 225
    end

    @testset "Trace Test" begin

        @testset "Simple" begin
            @polyvar x y a b c
            f = x^2 + y^2 - 1
            l = a * x + b * y + c
            res = monodromy_solve(
                [f, l],
                [-0.6 - 0.8im, -1.2 + 0.4im],
                [1, 2, 3];
                parameters = [a, b, c],
            )
            @test verify_solution_completeness([f, l], res; parameters = [a, b, c])
        end

        @testset "ED Example" begin
            Random.seed!(1222)
            # define f
            @polyvar x y
            f = (x^4 + y^4 - 1) * (x^2 + y^2 - 2) + x^5 * y
            # define new variables u₁, u₂ and λ₁
            @polyvar u[1:2] λ[1:1]
            # define the jacobian of F
            J = differentiate([f], [x, y])
            # J' defines the transpose of J
            C = [[x, y] - u - J' * λ; f]

            # create a random linear space
            l = sum(randn(ComplexF64, 3) .* [x, y, 1])
            # compute intersection points of the V(f) and V(l) and take the first solution
            s₀ = first(solutions(solve([f, l])))
            # The normal space is now generated by
            J_s₀ = [p([x, y] => s₀) for p in J]
            # create normal vector
            λ₀ = cis(2π * rand()) / norm(J_s₀)
            # x₀ - u₀ = J_s₀' * λ₀ => u = x -  J_s₀' * λ₀
            u₀ = s₀ - transpose(J_s₀) * λ₀ |> vec

            # This is not as realiable as I would like it to be, so just make a couple runs...
            is_complete = false
            for i = 1:5
                res = monodromy_solve(C, [s₀; λ₀], u₀; parameters = u)
                if verify_solution_completeness(C, res; parameters = u)
                    is_complete = true
                    break
                end
            end
            @test is_complete
        end
    end

    @testset "monodromy - automatic start pair" begin
        @polyvar x[1:4]
        # declare the variables for the 3 points
        @polyvar p[1:3, 1:3]
        p₁, p₂, p₃ = p[:, 1], p[:, 2], p[:, 3]
        quartic_monomials = monomials(sum(x)^4)
        @polyvar c[1:35]
        f = sum(c .* quartic_monomials)
        ∇f = differentiate(f, x)
        @polyvar u v
        F = [
            subs(f, x => [p₁; 1])
            subs(f, x => [p₂; 1])
            subs(f, x => [p₃; 1])
            (subs(∇f, x => [p₁; 1]) - u * subs(∇f, x => [p₂; 1]))
            (subs(∇f, x => [p₁; 1]) - v * subs(∇f, x => [p₃; 1]))
        ]

        x₀, c₀ = HC.find_start_pair(F, c)
        @test norm([f([p₁; p₂; p₃; u; v] => x₀, c => c₀) for f in F]) < 1e-8

        F1 = [subs(f, c[1] => 0.232) for f in F]
        x₀, c₀ = HC.find_start_pair(F1, c[2:end])
        @test norm([f([p₁; p₂; p₃; u; v] => x₀, c[2:end] => c₀) for f in F1]) < 1e-8

        # only use a small target_solutions_count, this is just to test that we actually
        # compute something
        res = monodromy_solve(F; parameters = c, target_solutions_count = 50)
        @test is_success(res)

        # Example where we cannot compute a start pair naively.
        @polyvar x y
        f = (x^4 + y^4 - 1) * (x^2 + y^2 - 2) + x^5 * y
        # define new variables u₁, u₂ and λ₁
        @polyvar u[1:2] λ[1:1]
        # define the jacobian of F
        J = differentiate([f], [x, y])
        # J' defines the transpose of J
        C = [[x, y] - u - J' * λ; f]

        @test_throws ArgumentError monodromy_solve(C; parameters = u)
        @test_throws ArgumentError HC.find_start_pair(C, u)
    end

    @testset "projective" begin
        @polyvar x y z a b c
        f = x^2 + y^2 - z^2
        l = a * x + b * y + c * z

        v = PVector([-0.6 - 0.8im, -1.2 + 0.4im, 1])
        res = monodromy_solve(
            [f, l],
            v,
            [1, 2, 3];
            parameters = [a, b, c], max_loops_no_progress = 20,
        )
        @test is_heuristic_stop(res)
        @test nsolutions(res) == 2
        @test isempty(real_solutions(res))

        @polyvar x y u v a b
        f = [x * y - a * u * v, x^2 - b * u^2]
        res = monodromy_solve(
            f,
            PVector([√2, 1], [√2, 1]),
            [2, 2];
            variable_groups = [[x, u], [y, v]],
            parameters = [a, b],
            max_loops_no_progress = 20,
        )
        @test is_heuristic_stop(res)
        @test nsolutions(res) == 2
        @test nreal(res) == 2
        @test sum(fubini_study.(real_solutions(res), solutions(res))) ≈ 0.0 atol = 1e-6
    end

    @testset "monodromy group" begin
        @polyvar x[1:2]  a b c
        p₁ = x - [2;0]
        p₂ = x - [-2;0]
        c₁ = p₁[1]^2 + p₁[2]^2 - 1
        c₂ = p₂[1]^2 + p₂[2]^2 - 1

        F = [c₁ * c₂; a * x[1] + b * x[2] - c]
        S = monodromy_solve(F, [[1.0, 0.0]], [1, 1, 1], parameters = [a;b;c])
        A = permutations(S)
        B = permutations(S, reduced = false)

        @test size(A) == (2,2)
        @test A == [1 2; 2 1] || A == [2 1; 1 2]
        @test size(B, 1) == 2
        @test size(B, 2) > 2

        F₀ = [c₁ * c₂; x[1] + x[2] - 1]
        start_sols=solutions(solve(F₀))
        S = monodromy_solve(F, start_sols, [1, 1, 1], parameters = [a;b;c])
        C = permutations(S)

        @test size(C, 1) == 4
    end

    @testset "monodromy group Fano problem" begin
        # Problem from Thomas Yahl
        k = 1; #dim of linear spaces
        m = 6; #ambient dim
        n = [2,2,3]; #hypersurface degrees
        r = length(n);
        np = sum(binomial.(n.+m,m));

        #hypersurface equations
        @polyvar x[1:m+1] t[1:k+1] y[1:(m-k)*(k+1)] p[1:np];
        monoms = [reshape(monomials(x,[s]),(1,binomial(s+m,m))) for s in n];
        splits = vcat([0],[sum(length.(monoms[1:i])) for i=1:r]);
        G = [(monoms[i]*p[splits[i]+1:splits[i+1]])[1] for i=1:r];

        #linear space substitution
        ℓ = vcat([sum(y[(k+1)*(i-1)+1:(k+1)*i].*t) for i=1:m-k],t);
        F̂ = subs(G,x=>ℓ).+0*prod(p);

        # Compute all monomials of a given degree d
        function segre(x, d)
            if d == 1
                return x
            else
                return unique(kron(x,segre(x,d-1)))
            end
        end

        F = vcat(map(1:3) do i
        	d = n[i]
        	g = F̂[i]
        	[coefficient(g, v, t) for v in segre(t,d)]
        end...)
        F = [subs(f, t=>zeros(2)) for f in F] # annoying bug in MVP

        #base system
        startSol = randn(ComplexF64,(m-k)*(k+1));
        params = (nullspace(transpose(hcat(map(f->coefficient.(f,p),subs.(F,y=>startSol))...)))*randn(ComplexF64,np-(m-k)*(k+1),1))[:,1];
        #subs.(F,y=>startSol,p=>params) #testing base system and solution

        #monodromy_solve
        F̂ = subs.(F,p=>params);
        Ĝ = subs.(F,p=>randn(ComplexF64,np));
        @polyvar τ
        H = @. (1-τ)*F̂+τ*Ĝ;
        S = monodromy_solve(H,startSol,[0.0+0.0im];parameters = [τ], target_solutions_count = 720)

        #permutations
        T = permutations(S)
        @test size(T,1) == 720
    end
end


text:
function normpdf(x::Float64, mu::Float64, sigma::Float64)
	return 1.0 / ( sqrt(2.0 * pi) * sigma ) * exp( - 0.5 * (x - mu)^2 / sigma^2 )
end

ext: jl


text:
# ------------ Choice sites ------------ #

@inline function (ctx::UpdateContext)(call::typeof(rand),
                                      addr::T,
                                      d::Distribution{K}) where {T <: Address, K}
    visit!(ctx, addr)

    # Check if in previous trace's choice map.
    in_prev_chm = has_top(ctx.prev.trace, addr)
    in_prev_chm && begin
        prev = get_top(ctx.prev.trace, addr)
        prev_ret = prev.val
        prev_score = prev.score
    end

    # Check if in selection.
    in_selection = has_top(ctx.select, addr)

    # Ret.
    if in_selection
        ret = get_top(ctx.select, addr)
        in_prev_chm && begin
            add_choice!(ctx.discard, addr, prev)
        end
    elseif in_prev_chm
        ret = prev_ret
    else
        ret = rand(d)
    end

    # Update.
    score = logpdf(d, ret)
    if in_prev_chm
        increment!(ctx, score - prev_score)
    elseif in_selection
        increment!(ctx, score)
    end
    add_choice!(ctx, addr, ChoiceSite(score, ret))

    return ret
end

# ------------ Learnable ------------ #

@inline function (ctx::UpdateContext)(fn::typeof(learnable), addr::Address)
    visit!(ctx, addr)
    has_top(ctx.params, addr) && return get_top(ctx.params, addr)
    error("Parameter not provided at address $addr.")
end

# ------------ Black box call sites ------------ #

@inline function (ctx::UpdateContext)(c::typeof(rand),
                                      addr::T,
                                      call::Function,
                                      args...) where {T <: Address, D <: Diff}
    visit!(ctx, addr)
    has_addr = has_top(ctx.prev.trace, addr)
    if has_addr
        cs = get_prev(ctx, addr)
        ps = get_subparameters(ctx, addr)
        ss = get_subselection(ctx, addr)

        # TODO: Mjolnir.
        ret, new_site, lw, retdiff, discard = update(ss, ps, cs, args...)

        add_call!(ctx.discard, addr, CallSite(discard, cs.score, cs.fn, cs.args, cs.ret))
    else
        ps = get_subparameters(ctx, addr)
        ss = get_subselection(ctx, addr)
        ret, new_site, lw = generate(ss, ps, call, args...)
    end
    add_call!(ctx, addr, new_site)
    increment!(ctx, lw)
    return ret
end


text:
mutable struct TimeStepWizard{FT, C, D}
                         cfl :: FT
               diffusive_cfl :: FT
                  max_change :: FT
                  min_change :: FT
                      max_Δt :: FT
                      min_Δt :: FT
                          Δt :: FT
    cell_advection_timescale :: C
    cell_diffusion_timescale :: D
end

infinite_diffusion_timescale(args...) = Inf # its not very limiting

"""
    TimeStepWizard(cfl=0.1, max_change=2.0, min_change=0.5, max_Δt=Inf, min_Δt=0.0, Δt=0.01)

A type for calculating adaptive time steps based on capping the CFL number at `cfl`.

On calling `update_Δt!(wizard, model)`, the `TimeStepWizard` computes a time-step such that
``cfl = max(u/Δx, v/Δy, w/Δz) Δt``, where ``max(u/Δx, v/Δy, w/Δz)`` is the maximum ratio
between model velocity and along-velocity grid spacing anywhere on the model grid. The new
`Δt` is constrained to change by a multiplicative factor no more than `max_change` or no
less than `min_change` from the previous `Δt`, and to be no greater in absolute magnitude
than `max_Δt` and no less than `min_Δt`.
"""
function TimeStepWizard(FT=Float64; cfl = 0.1,
                                    diffusive_cfl = Inf,
                                    max_change = 2.0,
                                    min_change = 0.5,
                                    max_Δt = Inf,
                                    min_Δt = 0.0,
                                    Δt = 0.01,
                                    cell_advection_timescale = cell_advection_timescale,
                                    cell_diffusion_timescale = infinite_diffusion_timescale)

    isfinite(diffusive_cfl) && # user wants to limit by diffusive CFL
    !(cell_diffusion_timescale === infinite_diffusion_timescale) && # user did not provide custom timescale
        (cell_diffusion_timescale = Oceananigans.TurbulenceClosures.cell_diffusion_timescale)

    C = typeof(cell_advection_timescale)
    D = typeof(cell_diffusion_timescale)

    return TimeStepWizard{FT, C, D}(cfl, diffusive_cfl, max_change, min_change, max_Δt, min_Δt, Δt,
                                    cell_advection_timescale, cell_diffusion_timescale)
end

using Oceananigans.Grids: topology

"""
    update_Δt!(wizard, model)

Compute `wizard.Δt` given the velocities and diffusivities of `model`, and the parameters
of `wizard`.
"""
function update_Δt!(wizard, model)

    Δt = min(
             wizard.cfl * wizard.cell_advection_timescale(model),          # advective
             wizard.diffusive_cfl * wizard.cell_diffusion_timescale(model) # diffusive
            )

    # Put the kibosh on if needed
    Δt = min(wizard.max_change * wizard.Δt, Δt)
    Δt = max(wizard.min_change * wizard.Δt, Δt)
    Δt = clamp(Δt, wizard.min_Δt, wizard.max_Δt)

    wizard.Δt = Δt

    return nothing
end

(c::CFL{<:TimeStepWizard})(model) = c.Δt.Δt / c.timescale(model)


text:
@testset "343.integer-break.jl" begin
    for (i, j) in zip([2, 4, 5, 6, 7, 8, 9, 12, 46, 53],
            [1, 4, 6, 9, 12, 18, 27, 81, 19131876, 258280326])
        @test integer_break(i) == j
    end
end


text:
using Documenter, MacroTools

makedocs(
    sitename = "MacroTools",
    pages = [
        "Home" => "index.md",
        "Pattern Matching" => "pattern-matching.md",
        "Utilities" => "utilities.md"],
    format = Documenter.HTML(prettyurls = haskey(ENV, "CI")))

deploydocs(
  repo = "github.com/FluxML/MacroTools.jl.git",
  push_preview = true)


text:
# Helper data for CIE observer functions
include("cie_data.jl")

# Linear interpolation in [a, b] where x is in [0,1],
# or coerced to be if not.
function lerp(x, a, b)
    a + (b - a) * max(min(x, one(x)), zero(x))
end

# Print a color as a RGB hex triple.
function hex(c::RGB)
    @sprintf("%02X%02X%02X",
             round(Int, lerp(c.r, 0.0, 255.0)),
             round(Int, lerp(c.g, 0.0, 255.0)),
             round(Int, lerp(c.b, 0.0, 255.0)))
end

hex(c::ColorValue) = hex(convert(RGB, c))

# set source color as a ColorValue
function set_source(gc::GraphicsContext, c::ColorValue)
    rgb = convert(RGB, c)
    set_source_rgb(gc, rgb.r, rgb.g, rgb.b)
end

# weighted_color_mean(w1, c1, c2) gives a mean color "w1*c1 + (1-w1)*c2".
for (T,a,b,c) in ((:RGB,:r,:g,:b), (:HSV,:h,:s,:v), (:HSL,:h,:s,:l),
                  (:XYZ,:x,:y,:z), (:Lab,:l,:a,:b), (:LCHab,:l,:c,:h),
                  (:Luv,:l,:u,:v), (:LCHuv,:l,:c,:h), (:LMS,:l,:m,:s))
    @eval weighted_color_mean(w1::Real, c1::$T, c2::$T) =
      let w2 = w1 >= 0 && w1 <= 1 ? 1 - w1 : throw(DomainError())
          $T(c1.($(Expr(:quote, a))) * w1 + c2.($(Expr(:quote, a))) * w2,
             c1.($(Expr(:quote, b))) * w1 + c2.($(Expr(:quote, b))) * w2,
             c1.($(Expr(:quote, c))) * w1 + c2.($(Expr(:quote, c))) * w2)
      end
end
weighted_color_mean(w1::Real, c1::RGB24, c2::RGB24) =
    convert(RGB24, weighted_color_mean(w1, convert(RGB, c1), convert(RGB, c2)))

# return a linear ramp of n colors from c1 to c2, inclusive
function linspace{T<:ColorValue}(c1::T, c2::T, n=100)
    a = Array(T, convert(Int, n))
    if n == 1
        a[1] = c1
        return a
    end
    n -= 1
    for i = 0:n
        a[i+1] = weighted_color_mean((n-i)/n, c1, c2)
    end
    a
end

#Double quadratic Bezier curve
function Bezier{T<:Real}(t::T, p0::T, p2::T, q0::T, q1::T, q2::T)
    B(t,a,b,c)=a*(1.0-t)^2.0+2.0b*(1.0-t)*t+c*t^2.0
    if t <= 0.5
        return B(2.0t, p0, q0, q1)
    else #t > 0.5
        return B(2.0(t-0.5), q1, q2, p2)
    end
end

#Inverse double quadratic Bezier curve
function invBezier{T<:Real}(t::T, p0::T, p2::T, q0::T, q1::T, q2::T)
    invB(t,a,b,c)=(a-b+sqrt(b^2.0-a*c+(a-2.0b+c)*t))/(a-2.0b+c)
    if t < q1
        return 0.5*invB(t,p0,q0,q1)
    else #t >= q1
        return 0.5*invB(t,q1,q2,p2)+0.5
    end
end


text:
function bond_length_NO(x)
    """
    Computes the bond length, i.e. the distance between the N and O Nuclei
    """
    r_N = x[1, :]
    r_O = x[2, :]
    return Euclidean()(r_N, r_O)
end

function zcom_NO(x)
    """
    Computes the z component of the center of mass of the NO projectile
    """
    z_N = x[1, 3]
    z_O = x[2, 3]
    zcom = (z_N * m_N + z_O*m_O)/(m_N + m_O)
    return zcom
end

function generate_therm_surf!(surfp, occnum, surfh, surfpinit)
    global eigval_H
    #generate thermalized populations for electronic states
    for j in 1:Ne
        surfp[j] = j
    end

    for j in 1:Ne
        occnum[surfp[j]] = 1
    end
    k = 1
    for j in 1:Ms+1
        if occnum[j] == 0
            surfh[k] = j
            k = k+1
        end
    end
    for t in 1:Ne
        for k in 1:Ne*(Ms + 1 - Ne)
            hoprand = rand(Float64, 3)
            jp = Int(floor(hoprand[1]*Ne)) + 1
            jh = Int(floor(hoprand[2] * (Ms + 1 - Ne))) + 1
            rtemp = exp(-(eigval_H[surfh[jh]] - eigval_H[surfp[jp]])) / (kb * tsurf)
            if hoprand[3] < rtemp
                m = surfh[jh]
                surfh[jh] = surfp[jp]
                surfp[jp] = m
            end
        end
    end
    surfpinit = copy(surfp)
    return surfp, occnum, surfh, surfpinit
end


text:
export @snoopr

"""
    list = @snoopr expr

Capture method cache invalidations triggered by evaluating `expr`.
`list` is a sequence of invalidated `Core.MethodInstance`s together with "explanations," consisting
of integers (encoding depth) and strings (documenting the source of an invalidation).

Unless you are working at a low level, you essentially always want to pass `list`
directly to [`SnoopCompile.invalidation_trees`](@ref).

# Extended help

`list` is in a format where the "reason" comes after the items.
Method deletion results in the sequence

    [zero or more (mi, "invalidate_mt_cache") pairs..., zero or more (depth1 tree, loctag) pairs..., method, loctag] with loctag = "jl_method_table_disable"

where `mi` means a `MethodInstance`. `depth1` means a sequence starting at `depth=1`.

Method insertion results in the sequence

    [zero or more (depth0 tree, sig) pairs..., same info as with delete_method except loctag = "jl_method_table_insert"]
"""
macro snoopr(expr)
    quote
        local list = ccall(:jl_debug_method_invalidation, Any, (Cint,), 1)
        Expr(:tryfinally,
            $(esc(expr)),
            ccall(:jl_debug_method_invalidation, Any, (Cint,), 0)
        )
        list
    end
end


text:
# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
#  Niccolò Antonello <nantonel@idiap.ch>

using Flux

struct FullyConnected{T<:AbstractFloat}
  M::Matrix{T}
  b::Matrix{T}
end

init_bias(Ny,Nx) =
2/sqrt(Float32(first(Flux.nfan(Ny,Nx)))) * Float32.(rand(Ny) .- 0.5)

function FullyConnected(Nx::Int,Ny::Int)
  M = Flux.kaiming_uniform(Ny,Nx)'[:,:]
  b = reshape(init_bias(Ny,Nx),1,Ny)
  return FullyConnected(M,b)
end

# TODO: in future Flux versions this can be replaced by Dense
function (model::FullyConnected{T})(X::AbstractArray{T,3}) where {T}
  Nt, Nx, Nb = size(X)
  Ny = size(model.M,2)

  X = permutedims(X,(1,3,2))
  X = reshape(X,Nt*Nb,Nx)

  Y = X*model.M .+ model.b

  Y = reshape(Y,Nt,Nb,Ny)
  Y = permutedims(Y,(1,3,2))
  return Y
end
Flux.@functor FullyConnected

export get_convnet
function get_convnet(Nf,Ns;
                     Nhs=128*ones(Int,2),
                     Nks=[3,3],
                     strides=[1,3],
                     dilations=[1,2],
                     dropout=[0.0,0.0],
                     fout = x->logsoftmax(x,dims=2)
                    )
  T = Float32
  Nl = length(Nhs)
  @assert length(Nhs) == length(Nks) == length(strides) == length(dilations)
  convs = [Conv((Nks[i],), (i == 1 ? Nf : Nhs[i-1]) => Nhs[i],
                stride=strides[i],
                dilation=dilations[i],
                pad=SamePad(),
                init = Flux.kaiming_uniform,
                bias = init_bias(Nhs[i], i==1 ? Nf : Nhs[i-1])
               ) for i=1:Nl]
  bns = [BatchNorm(Nhs[i],relu) for i=1:Nl]
  dro =[Dropout(dropout[i],dims=2) for i=1:Nl]
  out = FullyConnected(Nhs[end],Ns)
  layers = []
  for i=1:Nl
    push!(layers,convs[i])
    push!(layers,bns[i])
    push!(layers,dro[i])
  end
  push!(layers,out)
  push!(layers,fout)
  return Chain(layers...)
end


text:
# ------------ unistd.h ------------
# Justification: "In the GNU C Library, this is an int."
# from http://www.gnu.org/software/libc/manual/html_node/Process-Identification.html
const pid_t = Cint

"""
Returns the process ID (PID) of the calling process.

Ref: [docs](https://man7.org/linux/man-pages/man2/getpid.2.html)
"""
getpid() = @ccall getpid()::pid_t
"""
Returns the process ID of the parent of the calling process.

Ref: [docs](https://man7.org/linux/man-pages/man2/getpid.2.html)
"""
getppid() = @ccall getppid()::pid_t

"""
Returns the caller's thread ID (TID).  In a single-
threaded process, the thread ID is equal to the process ID (PID,
as returned by `getpid(2)`).  In a multithreaded process, all
threads have the same PID, but each one has a unique TID.

Ref: [docs](https://man7.org/linux/man-pages/man2/gettid.2.html)
"""
gettid() = @ccall gettid()::pid_t

# ------------ sched.h ------------
"""
Returns the number of the CPU on which the calling thread
is currently executing.

Ref: [docs](https://man7.org/linux/man-pages/man3/sched_getcpu.3.html)
"""
sched_getcpu() = @ccall sched_getcpu()::Cint

# """
# https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html
# """
# sched_getaffinity(pid::Integer) = @ccall sched_getaffinity(pid::Cint)::Cint
# int sched_getaffinity(pid_t pid, size_t cpusetsize,
#                         cpu_set_t *mask);

# sched_getaffinity(getpid())


text:
module Day5

export solvePart1, solvePart2

import DataStructures

function lettersReact(a, b)
    (a != b) && (lowercase(a) == lowercase(b))
end

function reactString(s)
    q = DataStructures.deque(Char)
    for c in s
        if isempty(q)
            push!(q, c)
        else
            last = DataStructures.back(q)
            if lettersReact(c, last)
                pop!(q)
            else
                push!(q, c)
            end
        end
    end

    return join(q, "")
end

function getInput()
    open("day5input.txt") do f
        return read(f, String)
    end
end

function solvePart1()
    length(reactString(getInput()))
end

function getLowercaseLettersSet(s)
    letters = Set{Char}()
    for c in s
        if islowercase(c)
            push!(letters, c)
        end
    end
    return collect(letters)
end

function solvePart2()
    s = getInput()
    minLen = typemax(Int32)
    cs = getLowercaseLettersSet(s)
    for c in cs
        alteredSequence = filter(c1 -> lowercase(c1) != lowercase(c), s)
        n = length(reactString(alteredSequence))
        minLen = min(n, minLen)
    end
    return minLen
end

end


text:
"""
    bypass_graph(nf_func, ef_func, gf_func)

Bypassing graph in FeaturedGraph and let other layer process (node, edge and global)features only.
"""
function bypass_graph(nf_func=identity, ef_func=identity, gf_func=identity)
    return function (fg::FeaturedGraph)
        FeaturedGraph(fg,
                      nf=nf_func(node_feature(fg)),
                      ef=ef_func(edge_feature(fg)),
                      gf=gf_func(global_feature(fg)))
    end
end


text:
using Annette
using Base.Test

include("ann.jl")
include("ca.jl")


text:
"""
Fonctions auxiliaires
"""

function myIsLess(elt1::Elt, elt2::Elt)
	if elt1.idReq == elt2.idReq
		if elt1.state == E
			return false
		else
			return elt2.state == E
		end
	else
		return elt1.idReq < elt2.idReq
	end
end


text:
using PhilipsHue, Colors, Test

println("loaded PhilipsHue")

# for a proper test, supply the IP and username for an active bridge!

B = PhilipsHueBridge(
    "192.168.1.2",
    "50iUI23ZkGnvLN9SvC8xbU-kxJnZjcNd4RCPiELK")

if !isinitialized(B)
    @info "cursory tests passed, there being no bridge available"
else
    lightnumbers = getlightnumbers(B)

    @test isa(lightnumbers, Array{Int64, 1})

    firstlight = first(lightnumbers)
    @test isa(firstlight, Int64)

    println("Bridge config: \n\t"       , getbridgeconfig(B))
    println("Bridge IP: \n\t"           , getIP())
    println("Bridge initialized?: \n\t" , isinitialized(B))
    println("Light config: \n\t"        , getlights(B))
    println("Get light config: \n\t"    , getlight(B, firstlight))
    println("Get light config: \n\t"    , getlight(B, 4))

    println("Set first light on: \n\t"  , setlight(B, firstlight, Dict("on" => true)))
    println("Set first light off: \n\t" , setlight(B, firstlight, Dict("on" => false)))
    println("Set first light  \n\t"     , setlight(B, firstlight, Dict("on" => true, "sat" => 123, "bri" => 243, "hue" => 123)))

    # random change all lights
    for i in 1:3
        setlights(B, Dict("bri" => rand(0:255), "hue" => rand(1:65000), "sat" => rand(1:255)))
        sleep(0.1)
    end

    # for a random light, set RGB color

    # Thanks, @ScottPJones!
    for r in 0:0.25:1, g in 0:0.25:1, b in 0:0.25:1
        setlight(B, lightnumbers[rand(1:end)], Colors.RGB(r, g, b))
        sleep(.25)
    end

    setlights(B, Dict("bri" => 255))
end


text:
@testset "NumField/QQ" begin
  @test Hecke.ideal_type(ZZ) == Hecke.ZZIdl
  @test Hecke.ideal_type(Hecke.FlintIntegerRing) == Hecke.ZZIdl
  @test Hecke.fractional_ideal_type(QQ) == Hecke.ZZFracIdl
  @test_throws MethodError Hecke.ideal_type(QQ)

  I = 2*ZZ
  @test I == ZZ(2)*ZZ

  @test I == ideal(ZZ, 2)
  @test I == ideal(ZZ, [2])
  @test I == ideal(ZZ, [8, 26])

  @test I == ideal(ZZ, ZZ(2))
  @test I == ideal(ZZ, fmpz[2])
  @test I == ideal(ZZ, fmpz[8, 26])

  QQ(1, 2)*ZZ

  @test maximal_order(QQ)==ZZ
  @test isreal(inf)

  @test sign(ZZ(2), inf)==1
  @test ispositive(ZZ(1), inf)
  @test number_field(inf)==QQ
  @test 2*ZZ + 3*ZZ == 1*ZZ
end


text:
julia> [RpcApi.SimpleOrganism(0x000000000001a301,:(function (o::Creature.Organism,)
        local var_142::Int16 = -24600
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.stepUp(o)
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            var_134 = var_134 * var_134
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.eatRight(o,Int(var_89))
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            var_140 = var_140 | var_140
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_70 = func_90(var_70)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepRight(o)
            o.mem[var_141] = var_141
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,79781,0x0000024b,Dict(17739=>17739,19301=>19301,0=>19867,13720=>13720,19867=>19867,20863=>20863,10465=>10465,-1562=>-1562,-566=>19867,21977=>21977,1=
>1),[154,1],121),RpcApi.SimpleOrganism(0x000000000001a33d,:(function (o::Creature.Organism,)
        local var_142::Int16 = -24600
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.stepUp(o)
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            var_134 = var_134 * var_134
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.eatRight(o,Int(var_89))
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            var_140 = var_140 | var_140
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_70 = func_90(var_70)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepRight(o)
            o.mem[var_141] = var_141
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,76788,0x0000024b,Dict(17739=>17739,19301=>19301,0=>19867,13720=>13720,19867=>19867,20863=>20863,10465=>10465,-1562=>-1562,-566=>19867,21977=>21977,1=
>1),[38,1],121),RpcApi.SimpleOrganism(0x000000000001a334,:(function (o::Creature.Organism,)
        local var_142::Int16 = -24600
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.stepUp(o)
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            var_134 = var_134 * var_134
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.eatRight(o,Int(var_89))
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            var_140 = var_140 | var_140
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_70 = func_90(var_70)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepRight(o)
            o.mem[var_141] = var_141
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,62783,0x0000024a,Dict(17739=>17739,19301=>19301,0=>19867,13720=>13720,19867=>19867,20863=>20863,10465=>10465,-1562=>-1562,-566=>19867,21977=>21977,1=
>1),[28,2],119),RpcApi.SimpleOrganism(0x000000000001a2fc,:(function (o::Creature.Organism,)
        local var_142::Int16 = -24600
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.stepUp(o)
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_134 = var_134 * var_134
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.eatRight(o,Int(var_89))
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            var_140 = var_140 | var_140
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_70 = func_90(var_70)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepRight(o)
            o.mem[var_141] = var_141
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,55035,0x0000024a,Dict(17739=>17739,19301=>19301,0=>19867,13720=>13720,19867=>19867,20863=>20863,10465=>10465,-1562=>-1562,-566=>19867,21977=>21977,1=
>1),[22,1],120),RpcApi.SimpleOrganism(0x000000000001a33b,:(function (o::Creature.Organism,)
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_144::ASCIIString = "bZ5IZj5L"
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            if var_134 === var_134
                local var_145::Int8 = 9
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_142::Int64 = 251641968649170020
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatDown(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,52885,0x00000245,Dict(17739=>17739,19301=>19301,-28587=>13720,0=>19867,13720=>13720,19867=>19867,20863=>20863,-1562=>-1562,-566=>19867,21977=>21977,1
=>1),[900,576],118),RpcApi.SimpleOrganism(0x000000000001a2e9,:(function (o::Creature.Organism,)
        local var_142::Int16 = -24600
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.stepUp(o)
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            var_134 = var_134 * var_134
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.eatRight(o,Int(var_89))
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            var_140 = var_140 | var_140
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_70 = func_90(var_70)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepRight(o)
            o.mem[var_141] = var_141
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,51385,0x00000249,Dict(17739=>17739,19301=>19301,0=>19867,13720=>13720,19867=>19867,20863=>20863,10465=>10465,-1562=>-1562,-566=>19867,21977=>21977,1=
>1),[16,2],119),RpcApi.SimpleOrganism(0x000000000001a352,:(function (o::Creature.Organism,)
        local var_142::Int16 = -24600
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.stepUp(o)
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            var_134 = var_134 * var_134
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.eatRight(o,Int(var_89))
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            var_140 = var_140 | var_140
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepRight(o)
        o.mem[var_142] = var_142
        var_70 = func_90(var_70)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepRight(o)
            o.mem[var_141] = var_141
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,43728,0x0000024a,Dict(-24600=>-24600,17739=>17739,19301=>19301,0=>19867,13720=>13720,19867=>19867,20863=>20863,10465=>10465,-1562=>-1562,-566=>19867,
21977=>21977,1=>1),[17,1],120),RpcApi.SimpleOrganism(0x000000000001a0b5,:(function (o::Creature.Organism,)
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_144::ASCIIString = "bZ5IZj5L"
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            if var_134 === var_134
                local var_145::Int8 = 9
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_142::Int64 = 251641968649170020
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatDown(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,43016,0x00000245,Dict(17739=>17739,19301=>19301,-28587=>13720,0=>19867,13720=>13720,19867=>19867,20863=>20863,-1562=>-1562,-566=>19867,21977=>21977,1
=>1),[900,567],118),RpcApi.SimpleOrganism(0x000000000001a32c,:(function (o::Creature.Organism,)
        local var_142::Int16 = -24600
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.stepUp(o)
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            var_134 = var_134 * var_134
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            o.mem[var_136] = var_132
            Creature.eatRight(o,Int(var_89))
            var_132 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_132
                end
            Creature.eatRight(o,Int(var_89))
            var_140 = var_140 | var_140
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.eatUp(o,Int(var_70))
        Creature.stepRight(o)
        var_70 = func_90(var_70)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepRight(o)
            o.mem[var_141] = var_141
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        var_85 = var_85 - var_85
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,42438,0x0000024a,Dict(17739=>17739,19301=>19301,0=>19867,13720=>13720,19867=>19867,20863=>20863,10465=>10465,-1562=>-1562,-566=>19867,21977=>21977,1=
>1),[12,1],119),RpcApi.SimpleOrganism(0x000000000001a33f,:(function (o::Creature.Organism,)
        local var_142::Int8 = -51
        local var_138::Int8 = 118
        local var_115::Bool = false
        local var_110::Int8 = -127
        local var_109::Int16 = 19867
        function func_90(var_89::Int8=116)
            local var_140::Bool = false
            local var_136::Int16 = -28587
            local var_134::ASCIIString = "HpPDfak3"
            local var_132::Int16 = 13720
            Creature.eatDown(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            o.mem[var_132] = var_132
            Creature.eatUp(o,Int(var_89))
            Creature.eatLeft(o,Int(var_89))
            var_134 = var_134 * var_134
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            var_132 = if haskey(o.mem,var_136)
                    o.mem[var_136]
                else
                    var_132
                end
            Creature.stepUp(o)
            var_136 = if haskey(o.mem,var_132)
                    o.mem[var_132]
                else
                    var_136
                end
            Creature.eatUp(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 >= var_89
                Creature.stepRight(o)
            end
            Creature.eatRight(o,Int(var_89))
            Creature.eatDown(o,Int(var_89))
            Creature.stepRight(o)
            Creature.eatRight(o,Int(var_89))
            Creature.eatUp(o,Int(var_89))
            if var_89 > var_89
                local var_133::ASCIIString = "ydaVCXle"
            end
            Creature.eatUp(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            o.mem[var_136] = var_132
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            Creature.eatRight(o,Int(var_89))
            return var_89
        end
        local var_85::Int16 = 19301
        local var_70::Int8 = 88
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatDown(o,Int(var_70))
        Creature.eatDown(o,Int(var_70))
        if var_70 == var_70
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepLeft(o)
            Creature.stepRight(o)
        end
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.stepDown(o)
        Creature.stepLeft(o)
        Creature.eatDown(o,Int(var_70))
        var_115 = Bool(abs(var_115 - var_115))
        var_115 = var_115 & var_115
        Creature.eatDown(o,Int(var_70))
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        var_107 = var_85 / var_85
        var_107 = var_85 * var_107
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatRight(o,Int(var_70))
        if var_85 !== var_85
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
        end
        if var_85 == var_109
        end
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        Creature.eatLeft(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepRight(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.stepDown(o)
        if var_85 >= var_85
            local var_137::Bool = true
            local var_141::Int16 = 10465
            Creature.stepDown(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
        end
        Creature.stepUp(o)
        o.mem[var_109] = var_85
        Creature.eatDown(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        Creature.stepUp(o)
        var_85 = if haskey(o.mem,var_85)
                o.mem[var_85]
            else
                var_85
            end
        Creature.eatDown(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        Creature.eatUp(o,Int(var_70))
        o.mem[var_85] = var_109
        Creature.eatLeft(o,Int(var_70))
        Creature.stepUp(o)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        var_70 = func_90(var_70)
        Creature.stepRight(o)
        Creature.stepUp(o)
        Creature.eatRight(o,Int(var_70))
        Creature.eatRight(o,Int(var_70))
        var_70 = func_90(var_70)
        return true
    end),[110,300,95,0,1,1,1],1,8307,13,42270,0x00000249,Dict(0=>19867,13720=>13720,-1562=>-1562,-566=>19867,17739=>17739,19301=>19867,21977=>21977,19867=>19867,20863=>20863,1=>1),[11,590],
116)]

max_stars_repo_name: tmptrash/jevo

max_issues_repo_name: tmptrash/jevo

max_forks_repo_name: tmptrash/jevo


text:
using CSV
using DataFrames
# df = CSV.read("parkinsons_updrs", header=false, delim=',')
# df = readtable("~/test/parkinsons_updrs.csv")
medData = CSV.read("/home/puranjay/ubc/term3/SGDBabysitter.jl/test/parkinsons_updrs.csv", delim=',')

# deletecols!(medData, :motor_UPDRS)

y1 = medData[[:total_UPDRS]]
y2 = medData[[:motor_UPDRS]]
deletecols!(medData, [:motor_UPDRS, :total_UPDRS])
xtrain = convert(Array,first(medData, 4000))
ytrain1 = convert(Array,first(y1, 4000))
ytrain2 = convert(Array,first(y2, 4000))
xvalid = convert(Array,last(medData, 1875))
yvalid1 = convert(Array,last(y1, 1875))
yvalid2 = convert(Array,last(y2, 1875))

n2 = size(xtrain,1)
xtrain = [ones(n2,1) xtrain]
d2 = size(xtrain,2)

# Choose network structure and randomly initialize weights
include("NeuralNet.jl")
nHidden = [3,3,4,3]
# nHidden = [5,5,5,5]
nParams = NeuralNet_nParams(d2,nHidden)
w = randn(nParams,1)

# Train with stochastic gradient
include("sgdfunc.jl")
maxIter = 10000

#----Uncomment below for hyperparameter search:----#

aTest = [0.1, 0.01, 0.001, 0.0001, 0.00001]
BTest = [1, 5, 10, 20, 100] #200 500 1000

bestvalid = Inf
bestw = []
bestparams2 = [0,0]
for B in BTest
    for a in aTest
        global bestvalid, bestw, bestparams2
        wb, validerr = VanillaSGD(NeuralNet_backprop, NeuralNet_predict, maxIter, nHidden, nParams, xtrain, ytrain1, xvalid, yvalid1, a, B)
        if (validerr[end]<bestvalid)
            bestvalid=validerr[end]
            bestw=wb
            bestparams2 = [a,B]
        end
    end
end

#best hyperparams found to be [0.1, 10]

wb_park, valid_park = SGDBabysitter(NeuralNet_backprop, NeuralNet_predict,
maxIter, nHidden, nParams, xtrain, ytrain1, xvalid, yvalid1)
savefig("SGDB_Parkinsons.pdf")

wb_vpark, valid_vpark = VanillaSGD(NeuralNet_backprop, NeuralNet_predict, maxIter, nHidden,nParams, xtrain, ytrain1, xvalid, yvalid1, bestparams2[1], convert(Int64, bestparams2[2]))
savefig("Vanilla_Parkinsons.pdf")


text:
function formatinfo(s::Spec, ::Nothing)
    size = 7  # ncodeunits("nothing")
    return size + paddingsize(s, size), nothing
end

function formatfield(data::Vector{UInt8}, p::Int, s::Spec, ::Nothing, ::Nothing)
    align = default(s.align, ALIGN_LEFT)
    pw = paddingwidth(s, 7)
    p = padleft(data, p, s.fill, align, pw)
    p = @copy data p "nothing"
    p = padright(data, p, s.fill, align, pw)
    return p
end


text:
export
    CuArray, CuVector, CuMatrix, CuVecOrMat,
    device

type CuArray{T,N} <: AbstractCuArray{T,N}
    ptr::CuPtr{T}
    dims::NTuple{N,Int}
end

typealias CuVector{T} CuArray{T,1}
typealias CuMatrix{T} CuArray{T,2}
typealias CuVecOrMat{T} Union{CuVector{T},CuMatrix{T}}

(::Type{CuArray{T}}){T,N}(dims::NTuple{N,Int}) = CuArray(alloc(T,prod(dims)), dims)
(::Type{CuArray{T}}){T}(dims::Int...) = CuArray{T}(dims)
CuArray{T,N}(x::Array{T,N}) = copy!(CuArray{T}(size(x)), x)
Base.Array{T,N}(x::CuArray{T,N}) = copy!(Array{T}(size(x)), x)

device(x::CuArray) = x.ptr.dev
Base.pointer{T}(x::CuArray{T}, index::Int=1) = Ptr{T}(x.ptr) + sizeof(T) * (index-1)

Base.length(x::CuArray) = prod(x.dims)
Base.size(x::CuArray) = x.dims
Base.size(x::CuArray, dim::Int) = x.dims[dim]
Base.ndims{T,N}(x::CuArray{T,N}) = N
Base.eltype{T}(x::CuArray{T}) = T
Base.isempty(x::CuArray) = length(x) == 0

Base.strides{T}(x::CuArray{T,1}) = (1,)
Base.strides{T}(x::CuArray{T,2}) = (1,size(x,1))
function Base.strides{T}(x::CuArray{T,3})
    s2 = size(x,1)
    s3 = s2 * size(x,2)
    (1,s2,s3)
end
function Base.strides{T}(x::CuArray{T,4})
    s2 = size(x,1)
    s3 = s2 * size(x,2)
    s4 = s3 * size(x,3)
    (1,s2,s3,s4)
end
function Base.stride{T,N}(x::CuArray{T,N}, dim::Int)
    d = 1
    for i = 1:dim-1
        d *= size(x,i)
    end
    d
end

Base.similar{T,N}(x::CuArray{T}, dims::NTuple{N,Int}) = CuArray{T}(dims)
Base.similar(x::CuArray) = similar(x, size(x))
Base.similar(x::CuArray, dims::Int...) = similar(x, dims)

Base.convert{T}(::Type{Ptr{T}}, x::CuArray) = Ptr{T}(x.ptr)
Base.convert(::Type{CUdeviceptr}, x::CuArray) = CUdeviceptr(x.ptr)
Base.convert{T,N}(::Type{CuArray{T,N}}, x::Array{T,N}) = CuArray(x)
Base.convert{T,N}(::Type{Array{T,N}}, x::CuArray{T,N}) = Array(x)
Base.unsafe_convert{T}(::Type{Ptr{T}}, x::CuArray) = Ptr{T}(x.ptr)
Base.unsafe_convert(::Type{CUdeviceptr}, x::CuArray) = CUdeviceptr(x.ptr)

Base.zeros{T,N}(::Type{CuArray{T}}, dims::NTuple{N,Int}) = fill(CuArray, T(0), dims)
Base.zeros{T,N}(x::CuArray{T,N}) = zeros(CuArray{T}, size(x))
Base.zeros{T}(::Type{CuArray{T}}, dims::Int...) = zeros(CuArray{T}, dims)

Base.ones{T}(x::CuArray{T}) = ones(CuArray{T}, x.dims)
Base.ones{T}(::Type{CuArray{T}}, dims::Int...) = ones(CuArray{T}, dims)
Base.ones{T}(::Type{CuArray{T}}, dims) = fill(CuArray, T(1), dims)

##### copy #####
function cucopy!(f::Function, dest, src, n::Int, stream)
    nbytes = n * sizeof(eltype(src))
    f(dest, src, nbytes, stream)
    dest
end
function Base.copy!{T}(dest::Array{T}, src::CuArray{T}; stream=C_NULL)
    cucopy!(cuMemcpyDtoHAsync, dest, src, length(src), stream)
end
function Base.copy!{T}(dest::CuArray{T}, src::Array{T}; stream=C_NULL)
    cucopy!(cuMemcpyHtoDAsync, dest, src, length(src), stream)
end
function Base.copy!{T}(dest::CuArray{T}, src::CuArray{T}; stream=C_NULL)
    cucopy!(cuMemcpyDtoDAsync, dest, src, length(src), stream)
end
Base.copy(x::CuArray) = copy!(similar(x),x)

function Base.fill!{T,N}(x::CuArray{T,N}, value)
    t = ctype(T)
    f = @nvrtc """
    $array_h
    __global__ void f(Array<$t,$N> x, $t value) {
        int idx = blockIdx.x * blockDim.x + threadIdx.x;
        if (idx < x.length()) {
            x[idx] = value;
        }
    } """
    f(x, T(value), dx=length(x))
    x
end
Base.fill{T}(::Type{CuArray}, value::T, dims::NTuple) = fill!(CuArray{T}(dims), value)

Base.reshape{T,N}(x::CuArray{T}, dims::NTuple{N,Int}) = CuArray{T,N}(x.ptr, dims)
Base.reshape{T}(x::CuArray{T}, dims::Int...) = reshape(x, dims)

Base.getindex(x::CuArray, indexes...) = CuArray(view(x,indexes))

Base.setindex!{T,N}(y::CuArray{T,N}, x::CuArray{T,N}, indexes...) = copy!(view(y,indexes),x)

box(x::CuArray) = box(Interop.Array(x))


text:
using Gadfly

set_default_plot_size(6inch, 3inch)

n = 10
plot(x=rand(n), y=rand(n),
     Scale.x_continuous(format=:scientific),
     Scale.y_continuous(format=:plain))


text:
using Gadfly
using Cairo
using DataFrames
using Colors

# General plot/data variables
path     = "/scratch/cns7ae/kmc-spin/" #"/home/cns/Desktop/"
infile1  = "new_kt.wsv"
infile2  = "new_kthop.wsv"
infile3  = "pxt.wsv"
outfile  = "kt.pdf"
title    = "HFI (Chfi=7) and Exchange Effects on Px(t)"
ylabel   = "Px(t)"
keylabel = "Type"
xmax     = 0
xmin     = 10
ymax     = 1
ymin     = 0

# Plot theme variables
plottheme = Gadfly.Theme(
    highlight_width = 0pt,
    default_point_size = 1pt,
    line_width=2pt,
    minor_label_font_size=13pt,
    minor_label_color=colorant"black",
    major_label_font_size=15pt,
    major_label_color=colorant"black",
    key_label_color=colorant"black",
    key_title_color=colorant"black",
    key_title_font_size=15pt,
    key_label_font_size=10pt,
    grid_color=colorant"black")

println("Now reading $infile1 contents")
kt = readtable(
    path*infile1,
    names = [:Time,:Pxt],
    eltypes = [Float64,Float64]
)

println("Now reading $infile2 contents")
kthop = readtable(
    path*infile2,
    names = [:Time,:Pxt],
    eltypes = [Float64,Float64]
)

println("Now reading $infile3 contents")
pxt = readtable(
    path*infile3,
    names = [:Time,:Pxt],
    eltypes = [Float64,Float64]
)

kt[:Type] = "Kubo-Toyabe"
kthop[:Type] = "Hopping(khop=2)"
pxt[:Type] = "Model"

pltdf = DataFrame()

pltdf = vcat(pltdf, kt, kthop, pxt)

p1 = plot(
    pltdf[pltdf[:Pxt].<1.0,:],
    x="Time",
    y="Pxt",
    Geom.point,
    color = "Type",
    Guide.colorkey(keylabel),
    Guide.title(title),
    Guide.ylabel(ylabel),
    Guide.xlabel("tΔ")
    )

# Apply the theme to the plot
push!(p1,plottheme)

println("Now exporting PDF for $outfile")
draw(PDF(path*outfile,6inch,5inch),p1)

println("ENDING SCRIPT")
quit()