text:
#!/usr/bin/env julia
# -*- julia -*-

# remez.jl - implementation of the Remez algorithm for polynomial approximation
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

import Base.\

# ----------------------------------------------------------------------
# Helper functions to cope with different Julia versions.
if VERSION >= v"0.7.0"
    array1d(T, d) = Array{T, 1}(undef, d)
    array2d(T, d1, d2) = Array{T, 2}(undef, d1, d2)
else
    array1d(T, d) = Array(T, d)
    array2d(T, d1, d2) = Array(T, d1, d2)
end
if VERSION < v"0.5.0"
    String = ASCIIString
end
if VERSION >= v"0.6.0"
    # Use Base.invokelatest to run functions made using eval(), to
    # avoid "world age" error
    run(f, x...) = Base.invokelatest(f, x...)
else
    # Prior to 0.6.0, invokelatest doesn't exist (but fortunately the
    # world age problem also doesn't seem to exist)
    run(f, x...) = f(x...)
end

# ----------------------------------------------------------------------
# Global variables configured by command-line options.
floatsuffix = "" # adjusted by --floatsuffix
xvarname = "x" # adjusted by --variable
epsbits = 256 # adjusted by --bits
debug_facilities = Set() # adjusted by --debug
full_output = false # adjusted by --full
array_format = false # adjusted by --array
preliminary_commands = array1d(String, 0) # adjusted by --pre

# ----------------------------------------------------------------------
# Diagnostic and utility functions.

# Enable debugging printouts from a particular subpart of this
# program.
#
# Arguments:
#    facility   Name of the facility to debug. For a list of facility names,
#               look through the code for calls to debug().
#
# Return value is a BigFloat.
function enable_debug(facility)
    push!(debug_facilities, facility)
end

# Print a diagnostic.
#
# Arguments:
#    facility   Name of the facility for which this is a debug message.
#    printargs  Arguments to println() if debugging of that facility is
#               enabled.
macro debug(facility, printargs...)
    printit = quote
        print("[", $facility, "] ")
    end
    for arg in printargs
        printit = quote
            $printit
            print($(esc(arg)))
        end
    end
    return quote
        if $facility in debug_facilities
            $printit
            println()
        end
    end
end

# Evaluate a polynomial.

# Arguments:
#    coeffs   Array of BigFloats giving the coefficients of the polynomial.
#             Starts with the constant term, i.e. coeffs[i] is the
#             coefficient of x^(i-1) (because Julia arrays are 1-based).
#    x        Point at which to evaluate the polynomial.
#
# Return value is a BigFloat.
function poly_eval(coeffs::Array{BigFloat}, x::BigFloat)
    n = length(coeffs)
    if n == 0
        return BigFloat(0)
    elseif n == 1
        return coeffs[1]
    else
        return coeffs[1] + x * poly_eval(coeffs[2:n], x)
    end
end

# Evaluate a rational function.

# Arguments:
#    ncoeffs  Array of BigFloats giving the coefficients of the numerator.
#             Starts with the constant term, and 1-based, as above.
#    dcoeffs  Array of BigFloats giving the coefficients of the denominator.
#             Starts with the constant term, and 1-based, as above.
#    x        Point at which to evaluate the function.
#
# Return value is a BigFloat.
function ratfn_eval(ncoeffs::Array{BigFloat}, dcoeffs::Array{BigFloat},
                    x::BigFloat)
    return poly_eval(ncoeffs, x) / poly_eval(dcoeffs, x)
end

# Format a BigFloat into an appropriate output format.
# Arguments:
#    x        BigFloat to format.
#
# Return value is a string.
function float_to_str(x)
    return string(x) * floatsuffix
end

# Format a polynomial into an arithmetic expression, for pasting into
# other tools such as gnuplot.

# Arguments:
#    coeffs   Array of BigFloats giving the coefficients of the polynomial.
#             Starts with the constant term, and 1-based, as above.
#
# Return value is a string.
function poly_to_string(coeffs::Array{BigFloat})
    n = length(coeffs)
    if n == 0
        return "0"
    elseif n == 1
        return float_to_str(coeffs[1])
    else
        return string(float_to_str(coeffs[1]), "+", xvarname, "*(",
                      poly_to_string(coeffs[2:n]), ")")
    end
end

# Format a rational function into a string.

# Arguments:
#    ncoeffs  Array of BigFloats giving the coefficients of the numerator.
#             Starts with the constant term, and 1-based, as above.
#    dcoeffs  Array of BigFloats giving the coefficients of the denominator.
#             Starts with the constant term, and 1-based, as above.
#
# Return value is a string.
function ratfn_to_string(ncoeffs::Array{BigFloat}, dcoeffs::Array{BigFloat})
    if length(dcoeffs) == 1 && dcoeffs[1] == 1
        # Special case: if the denominator is just 1, leave it out.
        return poly_to_string(ncoeffs)
    else
        return string("(", poly_to_string(ncoeffs), ")/(",
                      poly_to_string(dcoeffs), ")")
    end
end

# Format a list of x,y pairs into a string.

# Arguments:
#    xys      Array of (x,y) pairs of BigFloats.
#
# Return value is a string.
function format_xylist(xys::Array{Tuple{BigFloat,BigFloat}})
    return ("[\n" *
            join(["  "*string(x)*" -> "*string(y) for (x,y) in xys], "\n") *
            "\n]")
end

# ----------------------------------------------------------------------
# Matrix-equation solver for matrices of BigFloat.
#
# I had hoped that Julia's type-genericity would allow me to solve the
# matrix equation Mx=V by just writing 'M \ V'. Unfortunately, that
# works by translating the inputs into double precision and handing
# off to an optimised library, which misses the point when I have a
# matrix and vector of BigFloat and want my result in _better_ than
# double precision. So I have to implement my own specialisation of
# the \ operator for that case.
#
# Fortunately, the point of using BigFloats is that we have precision
# to burn, so I can do completely naïve Gaussian elimination without
# worrying about instability.

# Arguments:
#    matrix_in    2-dimensional array of BigFloats, representing a matrix M
#                 in row-first order, i.e. matrix_in[r,c] represents the
#                 entry in row r col c.
#    vector_in    1-dimensional array of BigFloats, representing a vector V.
#
# Return value: a 1-dimensional array X of BigFloats, satisfying M X = V.
#
# Expects the input to be an invertible square matrix and a vector of
# the corresponding size, on pain of failing an assertion.
function \(matrix_in :: Array{BigFloat,2},
           vector_in :: Array{BigFloat,1})
    # Copy the inputs, because we'll be mutating them as we go.
    M = copy(matrix_in)
    V = copy(vector_in)

    # Input consistency criteria: matrix is square, and vector has
    # length to match.
    n = length(V)
    @assert(n > 0)
    @assert(size(M) == (n,n))

    @debug("gausselim", "starting, n=", n)

    for i = 1:1:n
        # Straightforward Gaussian elimination: find the largest
        # non-zero entry in column i (and in a row we haven't sorted
        # out already), swap it into row i, scale that row to
        # normalise it to 1, then zero out the rest of the column by
        # subtracting a multiple of that row from each other row.

        @debug("gausselim", "matrix=", repr(M))
        @debug("gausselim", "vector=", repr(V))

        # Find the best pivot.
        bestrow = 0
        bestval = 0
        for j = i:1:n
            if abs(M[j,i]) > bestval
                bestrow = j
                bestval = M[j,i]
            end
        end
        @assert(bestrow > 0) # make sure we did actually find one

        @debug("gausselim", "bestrow=", bestrow)

        # Swap it into row i.
        if bestrow != i
            for k = 1:1:n
                M[bestrow,k],M[i,k] = M[i,k],M[bestrow,k]
            end
            V[bestrow],V[i] = V[i],V[bestrow]
        end

        # Scale that row so that M[i,i] becomes 1.
        divisor = M[i,i]
        for k = 1:1:n
            M[i,k] = M[i,k] / divisor
        end
        V[i] = V[i] / divisor
        @assert(M[i,i] == 1)

        # Zero out all other entries in column i, by subtracting
        # multiples of this row.
        for j = 1:1:n
            if j != i
                factor = M[j,i]
                for k = 1:1:n
                    M[j,k] = M[j,k] - M[i,k] * factor
                end
                V[j] = V[j] - V[i] * factor
                @assert(M[j,i] == 0)
            end
        end
    end

    @debug("gausselim", "matrix=", repr(M))
    @debug("gausselim", "vector=", repr(V))
    @debug("gausselim", "done!")

    # Now we're done: M is the identity matrix, so the equation Mx=V
    # becomes just x=V, i.e. V is already exactly the vector we want
    # to return.
    return V
end

# ----------------------------------------------------------------------
# Least-squares fitting of a rational function to a set of (x,y)
# points.
#
# We use this to get an initial starting point for the Remez
# iteration. Therefore, it doesn't really need to be particularly
# accurate; it only needs to be good enough to wiggle back and forth
# across the target function the right number of times (so as to give
# enough error extrema to start optimising from) and not have any
# poles in the target interval.
#
# Least-squares fitting of a _polynomial_ is actually a sensible thing
# to do, and minimises the rms error. Doing the following trick with a
# rational function P/Q is less sensible, because it cannot be made to
# minimise the error function (P/Q-f)^2 that you actually wanted;
# instead it minimises (P-fQ)^2. But that should be good enough to
# have the properties described above.
#
# Some theory: suppose you're trying to choose a set of parameters a_i
# so as to minimise the sum of squares of some error function E_i.
# Basic calculus says, if you do this in one variable, just
# differentiate and solve for zero. In this case, that works fine even
# with multiple variables, because you _partially_ differentiate with
# respect to each a_i, giving a system of equations, and that system
# turns out to be linear so we just solve it as a matrix.
#
# In this case, our parameters are the coefficients of P and Q; to
# avoid underdetermining the system we'll fix Q's constant term at 1,
# so that our error function (as described above) is
#
# E = \sum (p_0 + p_1 x + ... + p_n x^n - y - y q_1 x - ... - y q_d x^d)^2
#
# where the sum is over all (x,y) coordinate pairs. Setting dE/dp_j=0
# (for each j) gives an equation of the form
#
# 0 = \sum 2(p_0 + p_1 x + ... + p_n x^n - y - y q_1 x - ... - y q_d x^d) x^j
#
# and setting dE/dq_j=0 gives one of the form
#
# 0 = \sum 2(p_0 + p_1 x + ... + p_n x^n - y - y q_1 x - ... - y q_d x^d) y x^j
#
# And both of those row types, treated as multivariate linear
# equations in the p,q values, have each coefficient being a value of
# the form \sum x^i, \sum y x^i or \sum y^2 x^i, for various i. (Times
# a factor of 2, but we can throw that away.) So we can go through the
# list of input coordinates summing all of those things, and then we
# have enough information to construct our matrix and solve it
# straight off for the rational function coefficients.

# Arguments:
#    f        The function to be approximated. Maps BigFloat -> BigFloat.
#    xvals    Array of BigFloats, giving the list of x-coordinates at which
#             to evaluate f.
#    n        Degree of the numerator polynomial of the desired rational
#             function.
#    d        Degree of the denominator polynomial of the desired rational
#             function.
#    w        Error-weighting function. Takes two BigFloat arguments x,y
#             and returns a scaling factor for the error at that location.
#             A larger value indicates that the error should be given
#             greater weight in the square sum we try to minimise.
#             If unspecified, defaults to giving everything the same weight.
#
# Return values: a pair of arrays of BigFloats (N,D) giving the
# coefficients of the returned rational function. N has size n+1; D
# has size d+1. Both start with the constant term, i.e. N[i] is the
# coefficient of x^(i-1) (because Julia arrays are 1-based). D[1] will
# be 1.
function ratfn_leastsquares(f::Function, xvals::Array{BigFloat}, n, d,
                            w = (x,y)->BigFloat(1))
    # Accumulate sums of x^i y^j, for j={0,1,2} and a range of x.
    # Again because Julia arrays are 1-based, we'll have sums[i,j]
    # being the sum of x^(i-1) y^(j-1).
    maxpow = max(n,d) * 2 + 1
    sums = zeros(BigFloat, maxpow, 3)
    for x = xvals
        y = f(x)
        weight = w(x,y)
        for i = 1:1:maxpow
            for j = 1:1:3
                sums[i,j] += x^(i-1) * y^(j-1) * weight
            end
        end
    end

    @debug("leastsquares", "sums=", repr(sums))

    # Build the matrix. We're solving n+d+1 equations in n+d+1
    # unknowns. (We actually have to return n+d+2 coefficients, but
    # one of them is hardwired to 1.)
    matrix = array2d(BigFloat, n+d+1, n+d+1)
    vector = array1d(BigFloat, n+d+1)
    for i = 0:1:n
        # Equation obtained by differentiating with respect to p_i,
        # i.e. the numerator coefficient of x^i.
        row = 1+i
        for j = 0:1:n
            matrix[row, 1+j] = sums[1+i+j, 1]
        end
        for j = 1:1:d
            matrix[row, 1+n+j] = -sums[1+i+j, 2]
        end
        vector[row] = sums[1+i, 2]
    end
    for i = 1:1:d
        # Equation obtained by differentiating with respect to q_i,
        # i.e. the denominator coefficient of x^i.
        row = 1+n+i
        for j = 0:1:n
            matrix[row, 1+j] = sums[1+i+j, 2]
        end
        for j = 1:1:d
            matrix[row, 1+n+j] = -sums[1+i+j, 3]
        end
        vector[row] = sums[1+i, 3]
    end

    @debug("leastsquares", "matrix=", repr(matrix))
    @debug("leastsquares", "vector=", repr(vector))

    # Solve the matrix equation.
    all_coeffs = matrix \ vector

    @debug("leastsquares", "all_coeffs=", repr(all_coeffs))

    # And marshal the results into two separate polynomial vectors to
    # return.
    ncoeffs = all_coeffs[1:n+1]
    dcoeffs = vcat([1], all_coeffs[n+2:n+d+1])
    return (ncoeffs, dcoeffs)
end

# ----------------------------------------------------------------------
# Golden-section search to find a maximum of a function.

# Arguments:
#    f        Function to be maximised/minimised. Maps BigFloat -> BigFloat.
#    a,b,c    BigFloats bracketing a maximum of the function.
#
# Expects:
#    a,b,c are in order (either a<=b<=c or c<=b<=a)
#    a != c             (but b can equal one or the other if it wants to)
#    f(a) <= f(b) >= f(c)
#
# Return value is an (x,y) pair of BigFloats giving the extremal input
# and output. (That is, y=f(x).)
function goldensection(f::Function, a::BigFloat, b::BigFloat, c::BigFloat)
    # Decide on a 'good enough' threshold.
    threshold = abs(c-a) * 2^(-epsbits/2)

    # We'll need the golden ratio phi, of course. Or rather, in this
    # case, we need 1/phi = 0.618...
    one_over_phi = 2 / (1 + sqrt(BigFloat(5)))

    # Flip round the interval endpoints so that the interval [a,b] is
    # at least as large as [b,c]. (Then we can always pick our new
    # point in [a,b] without having to handle lots of special cases.)
    if abs(b-a) < abs(c-a)
        a,  c  = c,  a
    end

    # Evaluate the function at the initial points.
    fa = f(a)
    fb = f(b)
    fc = f(c)

    @debug("goldensection", "starting")

    while abs(c-a) > threshold
        @debug("goldensection", "a: ", a, " -> ", fa)
        @debug("goldensection", "b: ", b, " -> ", fb)
        @debug("goldensection", "c: ", c, " -> ", fc)

        # Check invariants.
        @assert(a <= b <= c || c <= b <= a)
        @assert(fa <= fb >= fc)

        # Subdivide the larger of the intervals [a,b] and [b,c]. We've
        # arranged that this is always [a,b], for simplicity.
        d = a + (b-a) * one_over_phi

        # Now we have an interval looking like this (possibly
        # reversed):
        #
        #    a            d       b            c
        #
        # and we know f(b) is bigger than either f(a) or f(c). We have
        # two cases: either f(d) > f(b), or vice versa. In either
        # case, we can narrow to an interval of 1/phi the size, and
        # still satisfy all our invariants (three ordered points,
        # [a,b] at least the width of [b,c], f(a)<=f(b)>=f(c)).
        fd = f(d)
        @debug("goldensection", "d: ", d, " -> ", fd)
        if fd > fb
            a,  b,  c  = a,  d,  b
            fa, fb, fc = fa, fd, fb
            @debug("goldensection", "adb case")
        else
            a,  b,  c  = c,  b,  d
            fa, fb, fc = fc, fb, fd
            @debug("goldensection", "cbd case")
        end
    end

    @debug("goldensection", "done: ", b, " -> ", fb)
    return (b, fb)
end

# ----------------------------------------------------------------------
# Find the extrema of a function within a given interval.

# Arguments:
#    f         The function to be approximated. Maps BigFloat -> BigFloat.
#    grid      A set of points at which to evaluate f. Must be high enough
#              resolution to make extrema obvious.
#
# Returns an array of (x,y) pairs of BigFloats, with each x,y giving
# the extremum location and its value (i.e. y=f(x)).
function find_extrema(f::Function, grid::Array{BigFloat})
    len = length(grid)
    extrema = array1d(Tuple{BigFloat, BigFloat}, 0)
    for i = 1:1:len
        # We have to provide goldensection() with three points
        # bracketing the extremum. If the extremum is at one end of
        # the interval, then the only way we can do that is to set two
        # of the points equal (which goldensection() will cope with).
        prev = max(1, i-1)
        next = min(i+1, len)

        # Find our three pairs of (x,y) coordinates.
        xp, xi, xn = grid[prev], grid[i], grid[next]
        yp, yi, yn = f(xp), f(xi), f(xn)

        # See if they look like an extremum, and if so, ask
        # goldensection() to give a more exact location for it.
        if yp <= yi >= yn
            push!(extrema, goldensection(f, xp, xi, xn))
        elseif yp >= yi <= yn
            x, y = goldensection(x->-f(x), xp, xi, xn)
            push!(extrema, (x, -y))
        end
    end
    return extrema
end

# ----------------------------------------------------------------------
# Winnow a list of a function's extrema to give a subsequence of a
# specified length, with the extrema in the subsequence alternating
# signs, and with the smallest absolute value of an extremum in the
# subsequence as large as possible.
#
# We do this using a dynamic-programming approach. We work along the
# provided array of extrema, and at all times, we track the best set
# of extrema we have so far seen for each possible (length, sign of
# last extremum) pair. Each new extremum is evaluated to see whether
# it can be added to any previously seen best subsequence to make a
# new subsequence that beats the previous record holder in its slot.

# Arguments:
#    extrema   An array of (x,y) pairs of BigFloats giving the input extrema.
#    n         Number of extrema required as output.
#
# Returns a new array of (x,y) pairs which is a subsequence of the
# original sequence. (So, in particular, if the input was sorted by x
# then so will the output be.)
function winnow_extrema(extrema::Array{Tuple{BigFloat,BigFloat}}, n)
    # best[i,j] gives the best sequence so far of length i and with
    # sign j (where signs are coded as 1=positive, 2=negative), in the
    # form of a tuple (cost, actual array of x,y pairs).
    best = fill((BigFloat(0), array1d(Tuple{BigFloat,BigFloat}, 0)), n, 2)

    for (x,y) = extrema
        if y > 0
            sign = 1
        elseif y < 0
            sign = 2
        else
            # A zero-valued extremum cannot possibly contribute to any
            # optimal sequence, so we simply ignore it!
            continue
        end

        for i = 1:1:n
            # See if we can create a new entry for best[i,sign] by
            # appending our current (x,y) to some previous thing.
            if i == 1
                # Special case: we don't store a best zero-length
                # sequence :-)
                candidate = (abs(y), [(x,y)])
            else
                othersign = 3-sign # map 1->2 and 2->1
                oldscore, oldlist = best[i-1, othersign]
                newscore = min(abs(y), oldscore)
                newlist = vcat(oldlist, [(x,y)])
                candidate = (newscore, newlist)
            end
            # If our new candidate improves on the previous value of
            # best[i,sign], then replace it.
            if candidate[1] > best[i,sign][1]
                best[i,sign] = candidate
            end
        end
    end

    # Our ultimate return value has to be either best[n,1] or
    # best[n,2], but it could be either. See which one has the higher
    # score.
    if best[n,1][1] > best[n,2][1]
        ret = best[n,1][2]
    else
        ret = best[n,2][2]
    end
    # Make sure we did actually _find_ a good answer.
    @assert(length(ret) == n)
    return ret
end

# ----------------------------------------------------------------------
# Construct a rational-function approximation with equal and
# alternating weighted deviation at a specific set of x-coordinates.

# Arguments:
#    f         The function to be approximated. Maps BigFloat -> BigFloat.
#    coords    An array of BigFloats giving the x-coordinates. There should
#              be n+d+2 of them.
#    n, d      The degrees of the numerator and denominator of the desired
#              approximation.
#    prev_err  A plausible value for the alternating weighted deviation.
#              (Required to kickstart a binary search in the nonlinear case;
#              see comments below.)
#    w         Error-weighting function. Takes two BigFloat arguments x,y
#              and returns a scaling factor for the error at that location.
#              The returned approximation R should have the minimum possible
#              maximum value of abs((f(x)-R(x)) * w(x,f(x))). Optional
#              parameter, defaulting to the always-return-1 function.
#
# Return values: a pair of arrays of BigFloats (N,D) giving the
# coefficients of the returned rational function. N has size n+1; D
# has size d+1. Both start with the constant term, i.e. N[i] is the
# coefficient of x^(i-1) (because Julia arrays are 1-based). D[1] will
# be 1.
function ratfn_equal_deviation(f::Function, coords::Array{BigFloat},
                               n, d, prev_err::BigFloat,
                               w = (x,y)->BigFloat(1))
    @debug("equaldev", "n=", n, " d=", d, " coords=", repr(coords))
    @assert(length(coords) == n+d+2)

    if d == 0
        # Special case: we're after a polynomial. In this case, we
        # have the particularly easy job of just constructing and
        # solving a system of n+2 linear equations, to find the n+1
        # coefficients of the polynomial and also the amount of
        # deviation at the specified coordinates. Each equation is of
        # the form
        #
        #   p_0 x^0 + p_1 x^1 + ... + p_n x^n ± e/w(x) = f(x)
        #
        # in which the p_i and e are the variables, and the powers of
        # x and calls to w and f are the coefficients.

        matrix = array2d(BigFloat, n+2, n+2)
        vector = array1d(BigFloat, n+2)
        currsign = +1
        for i = 1:1:n+2
            x = coords[i]
            for j = 0:1:n
                matrix[i,1+j] = x^j
            end
            y = f(x)
            vector[i] = y
            matrix[i, n+2] = currsign / w(x,y)
            currsign = -currsign
        end

        @debug("equaldev", "matrix=", repr(matrix))
        @debug("equaldev", "vector=", repr(vector))

        outvector = matrix \ vector

        @debug("equaldev", "outvector=", repr(outvector))

        ncoeffs = outvector[1:n+1]
        dcoeffs = [BigFloat(1)]
        return ncoeffs, dcoeffs
    else
        # For a nontrivial rational function, the system of equations
        # we need to solve becomes nonlinear, because each equation
        # now takes the form
        #
        #   p_0 x^0 + p_1 x^1 + ... + p_n x^n
        #   --------------------------------- ± e/w(x) = f(x)
        #     x^0 + q_1 x^1 + ... + q_d x^d
        #
        # and multiplying up by the denominator gives you a lot of
        # terms containing e × q_i. So we can't do this the really
        # easy way using a matrix equation as above.
        #
        # Fortunately, this is a fairly easy kind of nonlinear system.
        # The equations all become linear if you switch to treating e
        # as a constant, so a reasonably sensible approach is to pick
        # a candidate value of e, solve all but one of the equations
        # for the remaining unknowns, and then see what the error
        # turns out to be in the final equation. The Chebyshev
        # alternation theorem guarantees that that error in the last
        # equation will be anti-monotonic in the input e, so we can
        # just binary-search until we get the two as close to equal as
        # we need them.

        function try_e(e)
            # Try a given value of e, derive the coefficients of the
            # resulting rational function by setting up equations
            # based on the first n+d+1 of the n+d+2 coordinates, and
            # see what the error turns out to be at the final
            # coordinate.
            matrix = array2d(BigFloat, n+d+1, n+d+1)
            vector = array1d(BigFloat, n+d+1)
            currsign = +1
            for i = 1:1:n+d+1
                x = coords[i]
                y = f(x)
                y_adj = y - currsign * e / w(x,y)
                for j = 0:1:n
                    matrix[i,1+j] = x^j
                end
                for j = 1:1:d
                    matrix[i,1+n+j] = -x^j * y_adj
                end
                vector[i] = y_adj
                currsign = -currsign
            end

            @debug("equaldev", "trying e=", e)
            @debug("equaldev", "matrix=", repr(matrix))
            @debug("equaldev", "vector=", repr(vector))

            outvector = matrix \ vector

            @debug("equaldev", "outvector=", repr(outvector))

            ncoeffs = outvector[1:n+1]
            dcoeffs = vcat([BigFloat(1)], outvector[n+2:n+d+1])

            x = coords[n+d+2]
            y = f(x)
            last_e = (ratfn_eval(ncoeffs, dcoeffs, x) - y) * w(x,y) * -currsign

            @debug("equaldev", "last e=", last_e)

            return ncoeffs, dcoeffs, last_e
        end

        threshold = 2^(-epsbits/2) # convergence threshold

        # Start by trying our previous iteration's error value. This
        # value (e0) will be one end of our binary-search interval,
        # and whatever it caused the last point's error to be, that
        # (e1) will be the other end.
        e0 = prev_err
        @debug("equaldev", "e0 = ", e0)
        nc, dc, e1 = try_e(e0)
        @debug("equaldev", "e1 = ", e1)
        if abs(e1-e0) <= threshold
            # If we're _really_ lucky, we hit the error right on the
            # nose just by doing that!
            return nc, dc
        end
        s = sign(e1-e0)
        @debug("equaldev", "s = ", s)

        # Verify by assertion that trying our other interval endpoint
        # e1 gives a value that's wrong in the other direction.
        # (Otherwise our binary search won't get a sensible answer at
        # all.)
        nc, dc, e2 = try_e(e1)
        @debug("equaldev", "e2 = ", e2)
        @assert(sign(e2-e1) == -s)

        # Now binary-search until our two endpoints narrow enough.
        local emid
        while abs(e1-e0) > threshold
            emid = (e1+e0)/2
            nc, dc, enew = try_e(emid)
            if sign(enew-emid) == s
                e0 = emid
            else
                e1 = emid
            end
        end

        @debug("equaldev", "final e=", emid)
        return nc, dc
    end
end

# ----------------------------------------------------------------------
# Top-level function to find a minimax rational-function approximation.

# Arguments:
#    f         The function to be approximated. Maps BigFloat -> BigFloat.
#    interval  A pair of BigFloats giving the endpoints of the interval
#              (in either order) on which to approximate f.
#    n, d      The degrees of the numerator and denominator of the desired
#              approximation.
#    w         Error-weighting function. Takes two BigFloat arguments x,y
#              and returns a scaling factor for the error at that location.
#              The returned approximation R should have the minimum possible
#              maximum value of abs((f(x)-R(x)) * w(x,f(x))). Optional
#              parameter, defaulting to the always-return-1 function.
#
# Return values: a tuple (N,D,E,X), where

#    N,D       A pair of arrays of BigFloats giving the coefficients
#              of the returned rational function. N has size n+1; D
#              has size d+1. Both start with the constant term, i.e.
#              N[i] is the coefficient of x^(i-1) (because Julia
#              arrays are 1-based). D[1] will be 1.
#    E         The maximum weighted error (BigFloat).
#    X         An array of pairs of BigFloats giving the locations of n+2
#              points and the weighted error at each of those points. The
#              weighted error values will have alternating signs, which
#              means that the Chebyshev alternation theorem guarantees
#              that any other function of the same degree must exceed
#              the error of this one at at least one of those points.
function ratfn_minimax(f::Function, interval::Tuple{BigFloat,BigFloat}, n, d,
                       w = (x,y)->BigFloat(1))
    # We start off by finding a least-squares approximation. This
    # doesn't need to be perfect, but if we can get it reasonably good
    # then it'll save iterations in the refining stage.
    #
    # Least-squares approximations tend to look nicer in a minimax
    # sense if you evaluate the function at a big pile of Chebyshev
    # nodes rather than uniformly spaced points. These values will
    # also make a good grid to use for the initial search for error
    # extrema, so we'll keep them around for that reason too.

    # Construct the grid.
    lo, hi = minimum(interval), maximum(interval)
    local grid
    let
        mid = (hi+lo)/2
        halfwid = (hi-lo)/2
        nnodes = 16 * (n+d+1)
        pi = 2*asin(BigFloat(1))
        grid = [ mid - halfwid * cos(pi*i/nnodes) for i=0:1:nnodes ]
    end

    # Find the initial least-squares approximation.
    (nc, dc) = ratfn_leastsquares(f, grid, n, d, w)
    @debug("minimax", "initial leastsquares approx = ",
           ratfn_to_string(nc, dc))

    # Threshold of convergence. We stop when the relative difference
    # between the min and max (winnowed) error extrema is less than
    # this.
    #
    # This is set to the cube root of machine epsilon on a more or
    # less empirical basis, because the rational-function case will
    # not converge reliably if you set it to only the square root.
    # (Repeatable by using the --test mode.) On the assumption that
    # input and output error in each iteration can be expected to be
    # related by a simple power law (because it'll just be down to how
    # many leading terms of a Taylor series are zero), the cube root
    # was the next thing to try.
    threshold = 2^(-epsbits/3)

    # Main loop.
    while true
        # Find all the error extrema we can.
        function compute_error(x)
            real_y = f(x)
            approx_y = ratfn_eval(nc, dc, x)
            return (approx_y - real_y) * w(x, real_y)
        end
        extrema = find_extrema(compute_error, grid)
        @debug("minimax", "all extrema = ", format_xylist(extrema))

        # Winnow the extrema down to the right number, and ensure they
        # have alternating sign.
        extrema = winnow_extrema(extrema, n+d+2)
        @debug("minimax", "winnowed extrema = ", format_xylist(extrema))

        # See if we've finished.
        min_err = minimum([abs(y) for (x,y) = extrema])
        max_err = maximum([abs(y) for (x,y) = extrema])
        variation = (max_err - min_err) / max_err
        @debug("minimax", "extremum variation = ", variation)
        if variation < threshold
            @debug("minimax", "done!")
            return nc, dc, max_err, extrema
        end

        # If not, refine our function by equalising the error at the
        # extrema points, and go round again.
        (nc, dc) = ratfn_equal_deviation(f, map(x->x[1], extrema),
                                         n, d, max_err, w)
        @debug("minimax", "refined approx = ", ratfn_to_string(nc, dc))
    end
end

# ----------------------------------------------------------------------
# Check if a polynomial is well-conditioned for accurate evaluation in
# a given interval by Horner's rule.
#
# This is true if at every step where Horner's rule computes
# (coefficient + x*value_so_far), the constant coefficient you're
# adding on is of larger magnitude than the x*value_so_far operand.
# And this has to be true for every x in the interval.
#
# Arguments:
#    coeffs    The coefficients of the polynomial under test. Starts with
#              the constant term, i.e. coeffs[i] is the coefficient of
#              x^(i-1) (because Julia arrays are 1-based).
#    lo, hi    The bounds of the interval.
#
# Return value: the largest ratio (x*value_so_far / coefficient), at
# any step of evaluation, for any x in the interval. If this is less
# than 1, the polynomial is at least somewhat well-conditioned;
# ideally you want it to be more like 1/8 or 1/16 or so, so that the
# relative rounding error accumulated at each step are reduced by
# several factors of 2 when the next coefficient is added on.

function wellcond(coeffs, lo, hi)
    x = max(abs(lo), abs(hi))
    worst = 0
    so_far = 0
    for i = length(coeffs):-1:1
        coeff = abs(coeffs[i])
        so_far *= x
        if coeff != 0
            thisval = so_far / coeff
            worst = max(worst, thisval)
            so_far += coeff
        end
    end
    return worst
end

# ----------------------------------------------------------------------
# Small set of unit tests.

function test()
    passes = 0
    fails = 0

    function approx_eq(x, y, limit=1e-6)
        return abs(x - y) < limit
    end

    function test(condition)
        if condition
            passes += 1
        else
            println("fail")
            fails += 1
        end
    end

    # Test Gaussian elimination.
    println("Gaussian test 1:")
    m = BigFloat[1 1 2; 3 5 8; 13 34 21]
    v = BigFloat[1, -1, 2]
    ret = m \ v
    println("  ",repr(ret))
    test(approx_eq(ret[1], 109/26))
    test(approx_eq(ret[2], -105/130))
    test(approx_eq(ret[3], -31/26))

    # Test leastsquares rational functions.
    println("Leastsquares test 1:")
    n = 10000
    a = array1d(BigFloat, n+1)
    for i = 0:1:n
        a[1+i] = i/BigFloat(n)
    end
    (nc, dc) = ratfn_leastsquares(x->exp(x), a, 2, 2)
    println("  ",ratfn_to_string(nc, dc))
    for x = a
        test(approx_eq(exp(x), ratfn_eval(nc, dc, x), 1e-4))
    end

    # Test golden section search.
    println("Golden section test 1:")
    x, y = goldensection(x->sin(x),
                              BigFloat(0), BigFloat(1)/10, BigFloat(4))
    println("  ", x, " -> ", y)
    test(approx_eq(x, asin(BigFloat(1))))
    test(approx_eq(y, 1))

    # Test extrema-winnowing algorithm.
    println("Winnow test 1:")
    extrema = [(x, sin(20*x)*sin(197*x))
               for x in BigFloat(0):BigFloat(1)/1000:BigFloat(1)]
    winnowed = winnow_extrema(extrema, 12)
    println("  ret = ", format_xylist(winnowed))
    prevx, prevy = -1, 0
    for (x,y) = winnowed
        test(x > prevx)
        test(y != 0)
        test(prevy * y <= 0) # tolerates initial prevx having no sign
        test(abs(y) > 0.9)
        prevx, prevy = x, y
    end

    # Test actual minimax approximation.
    println("Minimax test 1 (polynomial):")
    (nc, dc, e, x) = ratfn_minimax(x->exp(x), (BigFloat(0), BigFloat(1)), 4, 0)
    println("  ",e)
    println("  ",ratfn_to_string(nc, dc))
    test(0 < e < 1e-3)
    for x = 0:BigFloat(1)/1000:1
        test(abs(ratfn_eval(nc, dc, x) - exp(x)) <= e * 1.0000001)
    end

    println("Minimax test 2 (rational):")
    (nc, dc, e, x) = ratfn_minimax(x->exp(x), (BigFloat(0), BigFloat(1)), 2, 2)
    println("  ",e)
    println("  ",ratfn_to_string(nc, dc))
    test(0 < e < 1e-3)
    for x = 0:BigFloat(1)/1000:1
        test(abs(ratfn_eval(nc, dc, x) - exp(x)) <= e * 1.0000001)
    end

    println("Minimax test 3 (polynomial, weighted):")
    (nc, dc, e, x) = ratfn_minimax(x->exp(x), (BigFloat(0), BigFloat(1)), 4, 0,
                                   (x,y)->1/y)
    println("  ",e)
    println("  ",ratfn_to_string(nc, dc))
    test(0 < e < 1e-3)
    for x = 0:BigFloat(1)/1000:1
        test(abs(ratfn_eval(nc, dc, x) - exp(x))/exp(x) <= e * 1.0000001)
    end

    println("Minimax test 4 (rational, weighted):")
    (nc, dc, e, x) = ratfn_minimax(x->exp(x), (BigFloat(0), BigFloat(1)), 2, 2,
                                   (x,y)->1/y)
    println("  ",e)
    println("  ",ratfn_to_string(nc, dc))
    test(0 < e < 1e-3)
    for x = 0:BigFloat(1)/1000:1
        test(abs(ratfn_eval(nc, dc, x) - exp(x))/exp(x) <= e * 1.0000001)
    end

    println("Minimax test 5 (rational, weighted, odd degree):")
    (nc, dc, e, x) = ratfn_minimax(x->exp(x), (BigFloat(0), BigFloat(1)), 2, 1,
                                   (x,y)->1/y)
    println("  ",e)
    println("  ",ratfn_to_string(nc, dc))
    test(0 < e < 1e-3)
    for x = 0:BigFloat(1)/1000:1
        test(abs(ratfn_eval(nc, dc, x) - exp(x))/exp(x) <= e * 1.0000001)
    end

    total = passes + fails
    println(passes, " passes ", fails, " fails ", total, " total")
end

# ----------------------------------------------------------------------
# Online help.
function help()
    print("""
Usage:

    remez.jl [options] <lo> <hi> <n> <d> <expr> [<weight>]

Arguments:

    <lo>, <hi>

        Bounds of the interval on which to approximate the target
        function. These are parsed and evaluated as Julia expressions,
        so you can write things like '1/BigFloat(6)' to get an
        accurate representation of 1/6, or '4*atan(BigFloat(1))' to
        get pi. (Unfortunately, the obvious 'BigFloat(pi)' doesn't
        work in Julia.)

    <n>, <d>

        The desired degree of polynomial(s) you want for your
        approximation. These should be non-negative integers. If you
        want a rational function as output, set <n> to the degree of
        the numerator, and <d> the denominator. If you just want an
        ordinary polynomial, set <d> to 0, and <n> to the degree of
        the polynomial you want.

    <expr>

        A Julia expression giving the function to be approximated on
        the interval. The input value is predefined as 'x' when this
        expression is evaluated, so you should write something along
        the lines of 'sin(x)' or 'sqrt(1+tan(x)^2)' etc.

    <weight>

        If provided, a Julia expression giving the weighting factor
        for the approximation error. The output polynomial will
        minimise the largest absolute value of (P-f) * w at any point
        in the interval, where P is the value of the polynomial, f is
        the value of the target function given by <expr>, and w is the
        weight given by this function.

        When this expression is evaluated, the input value to P and f
        is predefined as 'x', and also the true output value f(x) is
        predefined as 'y'. So you can minimise the relative error by
        simply writing '1/y'.

        If the <weight> argument is not provided, the default
        weighting function always returns 1, so that the polynomial
        will minimise the maximum absolute error |P-f|.

Computation options:

    --pre=<predef_expr>

        Evaluate the Julia expression <predef_expr> before starting
        the computation. This permits you to pre-define variables or
        functions which the Julia expressions in your main arguments
        can refer to. All of <lo>, <hi>, <expr> and <weight> can make
        use of things defined by <predef_expr>.

        One internal remez.jl function that you might sometimes find
        useful in this expression is 'goldensection', which finds the
        location and value of a maximum of a function. For example,
        one implementation strategy for the gamma function involves
        translating it to put its unique local minimum at the origin,
        in which case you can write something like this

            --pre='(m,my) = goldensection(x -> -gamma(x),
                  BigFloat(1), BigFloat(1.5), BigFloat(2))'

        to predefine 'm' as the location of gamma's minimum, and 'my'
        as the (negated) value that gamma actually takes at that
        point, i.e. -gamma(m).

        (Since 'goldensection' always finds a maximum, we had to
        negate gamma in the input function to make it find a minimum
        instead. Consult the comments in the source for more details
        on the use of this function.)

        If you use this option more than once, all the expressions you
        provide will be run in sequence.

    --bits=<bits>

        Specify the accuracy to which you want the output polynomial,
        in bits. Default 256, which should be more than enough.

    --bigfloatbits=<bits>

        Turn up the precision used by Julia for its BigFloat
        evaluation. Default is Julia's default (also 256). You might
        want to try setting this higher than the --bits value if the
        algorithm is failing to converge for some reason.

Output options:

    --full

        Instead of just printing the approximation function itself,
        also print auxiliary information:
         - the locations of the error extrema, and the actual
           (weighted) error at each of those locations
         - the overall maximum error of the function
         - a 'well-conditioning quotient', giving the worst-case ratio
           between any polynomial coefficient and the largest possible
           value of the higher-order terms it will be added to.

        The well-conditioning quotient should be less than 1, ideally
        by several factors of two, for accurate evaluation in the
        target precision. If you request a rational function, a
        separate well-conditioning quotient will be printed for the
        numerator and denominator.

        Use this option when deciding how wide an interval to
        approximate your function on, and what degree of polynomial
        you need.

    --variable=<identifier>

        When writing the output polynomial or rational function in its
        usual form as an arithmetic expression, use <identifier> as
        the name of the input variable. Default is 'x'.

    --suffix=<suffix>

        When writing the output polynomial or rational function in its
        usual form as an arithmetic expression, write <suffix> after
        every floating-point literal. For example, '--suffix=F' will
        generate a C expression in which the coefficients are literals
        of type 'float' rather than 'double'.

    --array

        Instead of writing the output polynomial as an arithmetic
        expression in Horner's rule form, write out just its
        coefficients, one per line, each with a trailing comma.
        Suitable for pasting into a C array declaration.

        This option is not currently supported if the output is a
        rational function, because you'd need two separate arrays for
        the numerator and denominator coefficients and there's no
        obviously right way to provide both of those together.

Debug and test options:

    --debug=<facility>

        Enable debugging output from various parts of the Remez
        calculation. <facility> should be the name of one of the
        classes of diagnostic output implemented in the program.
        Useful values include 'gausselim', 'leastsquares',
        'goldensection', 'equaldev', 'minimax'. This is probably
        mostly useful to people debugging problems with the script, so
        consult the source code for more information about what the
        diagnostic output for each of those facilities will be.

        If you want diagnostics from more than one facility, specify
        this option multiple times with different arguments.

    --test

        Run remez.jl's internal test suite. No arguments needed.

Miscellaneous options:

    --help

        Display this text and exit. No arguments needed.

""")
end

# ----------------------------------------------------------------------
# Main program.

function main()
    nargs = length(argwords)
    if nargs != 5 && nargs != 6
        error("usage: remez.jl <lo> <hi> <n> <d> <expr> [<weight>]\n" *
              "       run 'remez.jl --help' for more help")
    end

    for preliminary_command in preliminary_commands
        eval(Meta.parse(preliminary_command))
    end

    lo = BigFloat(eval(Meta.parse(argwords[1])))
    hi = BigFloat(eval(Meta.parse(argwords[2])))
    n = parse(Int,argwords[3])
    d = parse(Int,argwords[4])
    f = eval(Meta.parse("x -> " * argwords[5]))

    # Wrap the user-provided function with a function of our own. This
    # arranges to detect silly FP values (inf,nan) early and diagnose
    # them sensibly, and also lets us log all evaluations of the
    # function in case you suspect it's doing the wrong thing at some
    # special-case point.
    function func(x)
        y = run(f,x)
        @debug("f", x, " -> ", y)
        if !isfinite(y)
            error("f(" * string(x) * ") returned non-finite value " * string(y))
        end
        return y
    end

    if nargs == 6
        # Wrap the user-provided weight function similarly.
        w = eval(Meta.parse("(x,y) -> " * argwords[6]))
        function wrapped_weight(x,y)
            ww = run(w,x,y)
            if !isfinite(ww)
                error("w(" * string(x) * "," * string(y) *
                      ") returned non-finite value " * string(ww))
            end
            return ww
        end
        weight = wrapped_weight
    else
        weight = (x,y)->BigFloat(1)
    end

    (nc, dc, e, extrema) = ratfn_minimax(func, (lo, hi), n, d, weight)
    if array_format
        if d == 0
            functext = join([string(x)*",\n" for x=nc],"")
        else
            # It's unclear how you should best format an array of
            # coefficients for a rational function, so I'll leave
            # implementing this option until I have a use case.
            error("--array unsupported for rational functions")
        end
    else
        functext = ratfn_to_string(nc, dc) * "\n"
    end
    if full_output
        # Print everything you might want to know about the function
        println("extrema = ", format_xylist(extrema))
        println("maxerror = ", string(e))
        if length(dc) > 1
            println("wellconditioning_numerator = ",
                    string(wellcond(nc, lo, hi)))
            println("wellconditioning_denominator = ",
                    string(wellcond(dc, lo, hi)))
        else
            println("wellconditioning = ", string(wellcond(nc, lo, hi)))
        end
        print("function = ", functext)
    else
        # Just print the text people will want to paste into their code
        print(functext)
    end
end

# ----------------------------------------------------------------------
# Top-level code: parse the argument list and decide what to do.

what_to_do = main

doing_opts = true
argwords = array1d(String, 0)
for arg = ARGS
    global doing_opts, what_to_do, argwords
    global full_output, array_format, xvarname, floatsuffix, epsbits
    if doing_opts && startswith(arg, "-")
        if arg == "--"
            doing_opts = false
        elseif arg == "--help"
            what_to_do = help
        elseif arg == "--test"
            what_to_do = test
        elseif arg == "--full"
            full_output = true
        elseif arg == "--array"
            array_format = true
        elseif startswith(arg, "--debug=")
            enable_debug(arg[length("--debug=")+1:end])
        elseif startswith(arg, "--variable=")
            xvarname = arg[length("--variable=")+1:end]
        elseif startswith(arg, "--suffix=")
            floatsuffix = arg[length("--suffix=")+1:end]
        elseif startswith(arg, "--bits=")
            epsbits = parse(Int,arg[length("--bits=")+1:end])
        elseif startswith(arg, "--bigfloatbits=")
            set_bigfloat_precision(
                parse(Int,arg[length("--bigfloatbits=")+1:end]))
        elseif startswith(arg, "--pre=")
            push!(preliminary_commands, arg[length("--pre=")+1:end])
        else
            error("unrecognised option: ", arg)
        end
    else
        push!(argwords, arg)
    end
end

what_to_do()

max_stars_repo_name: mkinsner/llvm

max_issues_repo_name: mkinsner/llvm

max_forks_repo_name: mkinsner/llvm


text:
using Dates
using SHA, UUIDs, Random
using Genie, Genie.Router, Genie.Requests
using JSON, HTTP
using DataStructures
using URIs

mutable struct Blockchain
    chain::Array
    current_transactions::Array
    nodes::Set
end

function generate_genesis_block(bc::Blockchain)
    println("[BLOCKCHAIN] > ", "Initializing chain")
    generate_block(bc, 10, "1")
    println("[BLOCKCHAIN] > ", "Genesis block has been generated")
    JSON.print(stdout, bc.chain[end], 4)
    println()
end

function generate_block(bc::Blockchain, nonce::Int, prev_hash::String)
    #=
    nonce - PoW's
    prev_hash - Previous block's hash
    =#

    block = Dict(
    "index" => size(bc.chain)[1] + 1,
    "timestamp" => get_timestamp(),
    "transactions" => bc.current_transactions,
    "nonce" => nonce,
    "previous_hash" => !(isnothing(prev_hash)) ? prev_hash : hash_block(bc.chain[end])
    )

    bc.current_transactions = []
    println("[BLOCKCHAIN] > ", "Cleared current transactions")

    push!(bc.chain, block)
    println("[BLOCKCHAIN] > ", "Added new block to the chain")
    JSON.print(stdout, bc.chain[end], 4)
    println()

    return block
end

function generate_transaction(bc::Blockchain, sender::String, recipient::String, amount::Int)
    #=
    sender - Alice
    recipient - Bob
    amount - e.g. 0.01 btc
    =#

    transaction = Dict(
    "sender" => sender,
    "recipient" => recipient,
    "amount" => amount
    )
    push!(bc.current_transactions, transaction)
    println("[BLOCKCHAIN] > ", "Added new transaction to current transactions ")
    JSON.print(stdout, transaction, 4)
    println()

    # Get this address to identify the block
    return get_end_block()["index"] + 1
end

function hash_block(block::Dict)
    #= SHA-256 Hashed block
       Mmm... Yummy! =#
    block_str = JSON.json(SortedDict(block))
    return bytes2hex(sha256(block_str))
end

function get_end_block()
    return bc.chain[end]
end

function pow(bc::Blockchain, end_block::Dict)

    prev_hash = hash_block(end_block)
    end_nonce = end_block["nonce"]
    nonce = 0

    start = get_timestamp()
    hashrate = 0
    secs = 10
    while validate_nonce(end_nonce, nonce, prev_hash) != true
        if (elapsed_time = get_timestamp() - start >= secs)
            hashrate_sec = round(Int64, hashrate / secs)
            if (hashrate_sec >= 1000) println("[MINING] > ", hashrate_sec / 1000, " KH/s") else println("[MINING] > ", hashrate_sec, " H/s") end
            println()
            start = get_timestamp()
            hashrate = 0
        end
        nonce += 1
        hashrate += 1
    end

    return nonce
end

function validate_nonce(end_nonce::Int, nonce::Int, prev_hash::String)
    # n * n prime * previous hash
    nnp = string(end_nonce) * string(nonce) * prev_hash
    nnp_hash = bytes2hex(sha256(nnp))

    if (first(nnp_hash, 6) == "2021ab")
        println("[MINING] > ", "Found correct nonce => $nonce => ", nnp_hash)
        println()
    end

    # Valid if first n letters are correct as keys, it used for mining difficulty
    return first(nnp_hash, 6) == "2021ab"
end

function validate_chain(chain::Array)
    end_block = chain[1]
    current_index = 2

    while current_index < length(chain)
        block = chain[current_index]

        end_block_hash = hash_block(end_block)
        if block["previous_hash"] != end_block_hash
            println("[BLOCKCHAIN] > ", "Invalid block hash")
            println()
            return false
        end

        if !(validate_nonce(end_block["nonce"], block["nonce"], end_block_hash))
            println("[BLOCKCHAIN] > ", "Invalid PoW")
            println()
            return false
        end

        end_block = block
        current_index += 1
    end

    return true
end

function register_node(bc::Blockchain, address::String)
    #=
    address - e.g. http://192.168.1.2:12345/
    =#

    network = !isnothing(URI(address).port) ? URI(address).host * ":" * URI(address).port : URI(address).host
    push!(bc.nodes, network)
end

function resolve_conflicts(bc::Blockchain)
    networks = bc.nodes
    next_chain = nothing

    max_len = length(bc.chain)

    for node in networks
        resp = HTTP.request("GET", "http://$node/fullchain")
        if resp.status == 200
            resp_json = JSON.parse(String(resp.body))
            len = resp_json["length"]
            chain = resp_json["chain"]

            # The King Must Be Oh Long Johnson
            if len > max_len && validate_chain(chain)
                max_len = len
                next_chain = chain
            end
        end
    end

    # Replace chain if valid
    if !isnothing(next_chain)
        bc.chain = next_chain
        println("[BLOCKCHAIN] > ", "Chain has been updated")
        println()
        return true
    end

    return false
end

@async function resolve_dead_node()
    networks = bc.nodes

    for node in networks

        # You must do try-catch DNSError for dead node
        resp = HTTP.request("GET", "http://$node/nodes/ping")
        if resp.status != 200
            delete!(bc.nodes, node)
            println("[NODES] > ", "Removed dead node from nodes")
            println()
        end
    end
end

function get_timestamp()
    return floor(Int64,(Dates.datetime2unix(Dates.now())))
end

println("...")

bc = Blockchain([], [], Set())

generate_genesis_block(bc)

# Unique Id
rng = MersenneTwister(2021);
unencrypted_address = replace(string(uuid4(rng)), "-" => "")

println("[BLOCKCHAIN] > ", "Unencrypted Address => $unencrypted_address")
println()

# API
route("/transactions/new", method = POST) do
    keys = jsonpayload()

    if (isnothing(keys))
        resp = Dict(
        "status_code" => "500",
        "message" => "Invalid JSON"
        )

        return (resp) |> json
    end

    idx = generate_transaction(bc, keys["sender"], keys["recipient"], keys["amount"])
    resp = Dict(
    "status_code" => "201",
    "message" => "The Transaction has been added to block #$idx"
    )

    return (resp) |> json
end

route("/mine", method = GET) do
    # PoW
    end_block = get_end_block()
    end_nonce = end_block["nonce"]
    prev_hash = hash_block(end_block)

    println("[MINING] > ", "Lets get some golden K*C nuggets...")
    println()

    nonce = pow(bc, end_block)

    # Mining Reward
    generate_transaction(bc, "REWARD", unencrypted_address, 1)

    println("[MINING] > ", "Mining Reward has been added to the transactions")
    println

    block = generate_block(bc, nonce, prev_hash)

    resp = JSON.json(Dict(
    "index" => block["index"],
    "timestamp" => block["timestamp"],
    "transactions" => block["transactions"],
    "nonce" => block["nonce"],
    "previous_hash" => block["previous_hash"]
    ))

    return resp
end

route("/fullchain", method = GET) do
    resp = JSON.json(Dict(
    "chain" => bc.chain,
    "length" => length(bc.chain)
    ))

    return resp
end

route("/nodes/register", method = POST) do
    keys = jsonpayload()

    if (isnothing(keys))
        resp = Dict(
        "status_code" => "500",
        "message" => "Invalid JSON"
        )

        return (resp) |> json
    end

    function fill_node_keys!(node)
        for node in keys["nodes"]
            register_node(bc, node)
        end
    end

    node = ""
    fill_node_keys!(node)

    resp = JSON.json(Dict(
    "status_code" => "201",
    "message" => "New node has been added",
    "numbers_of_node" => length(bc.nodes),
    "nodes" => collect(bc.nodes)
    ))

    return resp
end

route("/nodes/resolve_consensus", method = GET) do
    replaced = resolve_conflicts(bc)

    if replaced
        resp = JSON.json(Dict(
        "status_code" => "200",
        "message" => "The chain has been replaced",
        "next_chain" => bc.chain
        ))
        return resp

    else
        resp = JSON.json(Dict(
        "status_code" => "200",
        "message" => "The chain has been confirmed",
        "chain" => bc.chain
        ))
        return resp
    end
end

route("/nodes/ping", method = GET) do
    resp = JSON.json(Dict(
    "pong" => "Hempel's ravens",
    ))

    return resp
end

Genie.startup(8000, "127.0.0.1", async = false)

ext: jl

max_stars_repo_name: Lutwidse/Blockchain-PoW

max_issues_repo_name: Lutwidse/Blockchain-PoW

max_forks_repo_name: Lutwidse/Blockchain-PoW


text:
abstract type BusCategory end
struct PVBus <: BusCategory end
struct PQBus <: BusCategory end
struct SLACKBus <: BusCategory end

const BUS_MAP = Dict(
    PSY.BusTypes.REF => SLACKBus,
    PSY.BusTypes.PV => PVBus,
    PSY.BusTypes.SLACK => SLACKBus,
    PSY.BusTypes.PQ => PQBus,
)


text:
#' ---
#' title: Sensitivity analysis on Hill Model
#' author: Shao-Ting Chiu (r07945001@ntu.edu.tw)
#' date: 2020/08/27
#' ---

#' # Introduction
#' We are going to explore the

using PyCall
using Plots
using Parameters

include("../src/Sens.jl")
include("../src/Model.jl")
sp = pyimport("sympy")

#' Model: Hill Formula

s = sp.symbols("s", nonnegative=true) # Output / input
k, n = sp.symbols("k n", nonnegative=true) # dissociation coefficient constant and Hill coefficient

model = Model.hill(k=k, n=n)
X = model(s)

# Local Sensitivity
Sens.localSens(X, s)

rs = Sens.responseCoef(X, s)

frac = Sens.actFrac(X, X.subs(s,0), X.subs(s,1) )

rs
sp.solve(rs-n,frac)


text:
# module Ecto.Repo

module Schema

import ....Ecto
import ....Ecto: Changeset, InvalidChangesetError

## insert!
function insert!(repo::Base.Random.UUID, adapter, struct_or_changeset::Union{Ecto.Schema.t,Changeset.t}, opts::Dict)::Ecto.Schema.t
    (isok, schema_or_changeset) = insert(repo, adapter, struct_or_changeset, opts)
    :ok==isok ? schema_or_changeset : throw(Ecto.InvalidChangesetError(:insert, schema_or_changeset))
end

## update!
function update!(repo::Base.Random.UUID, adapter, struct_or_changeset::Union{Ecto.Schema.t,Changeset.t}, opts::Dict)
    (isok, schema_or_changeset) = update(repo, adapter, struct_or_changeset, opts)
    :ok==isok ? schema_or_changeset : throw(Ecto.InvalidChangesetError(:update, schema_or_changeset))
end

## insert_or_update!
function insert_or_update!(repo::Base.Random.UUID, adapter, changeset::Union{Ecto.Schema.t,Changeset.t}, opts::Dict)
    state = get_state(changeset)
    if :built == state
        insert!(repo, adapter, changeset, opts)
    elseif :loaded == state
        update!(repo, adapter, changeset, opts)
    else
        throw(ArgumentError("the changeset has an invalid state for Repo.insert_or_update!: $state"))
    end
end

## delete!
function delete!(repo::Base.Random.UUID, adapter, struct_or_changeset::Union{Ecto.Schema.t,Changeset.t}, opts::Dict)
    (isok, schema_or_changeset) = delete(repo, adapter, struct_or_changeset, opts)
    :ok==isok ? schema_or_changeset : throw(Ecto.InvalidChangesetError(:delete, schema_or_changeset))
end

function insert(repo::Base.Random.UUID, adapter, changeset::Changeset.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    do_insert(repo, adapter, changeset, opts)
end

function insert(repo::Base.Random.UUID, adapter, struct::Ecto.Schema.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    changeset = Ecto.Changeset.change(struct)
    do_insert(repo, adapter, changeset, opts)
end

function update(repo::Base.Random.UUID, adapter, changeset::Changeset.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    do_update(repo, adapter, changeset, opts)
end

function insert_or_update(repo::Base.Random.UUID, adapter, changeset::Changeset.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    if changeset.valid
        (:ok, changeset.data)
    else
        (:error, changeset)
    end
end

function delete(repo::Base.Random.UUID, adapter, changeset::Changeset.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    do_delete(repo, adapter, changeset, opts)
end

function delete(repo::Base.Random.UUID, adapter, struct::Ecto.Schema.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    changeset = Ecto.Changeset.change(struct)
    do_delete(repo, adapter, changeset, opts)
end

function do_insert(repo::Base.Random.UUID, adapter, changeset::Changeset.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    do_action(:insert, repo, adapter, changeset, opts)
end

function do_update(repo::Base.Random.UUID, adapter, changeset::Changeset.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    do_action(:update, repo, adapter, changeset, opts)
end

function do_delete(repo::Base.Random.UUID, adapter, changeset::Changeset.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    do_action(:delete, repo, adapter, changeset, opts)
end

function do_action(action::Symbol, repo::Base.Random.UUID, adapter, changeset::Changeset.t, opts::Dict)::Tuple{Symbol,Union{Changeset.t,Ecto.Schema.t}}
    !(changeset.action in [nothing, :insert, :update, :delete, :replace]) && throw(ArgumentError("a changeset with action $(changeset.action) was given to $action"))
    prepare = changeset.prepare
    struct = struct_from_changeset!(action, changeset)
    schema = struct
    fields = schema[:fields]
    assocs = schema[:associations]
    retur = schema[:read_after_writes]
    changeset = put_repo_and_action(changeset, action, repo)
    if changeset.valid
        metadata = schema.metadata
        changes = changeset.changes
        (changes, extra) = autogenerate_id(metadata, changeset.changes, retur, adapter)
        dump_changes!(action, changes, schema, extra, changeset.types, adapter)
        if :insert != action
            filters = add_pk_filter!(changeset.filters, struct)
        end
        values = []
        extra = []
        autogen = []
        changeset = load_changes(changeset, :delete==action ? :deleted : :loaded, vcat(values, extra), autogen, adapter)
        (:ok, changeset.data)
    else
        (:error, changeset)
    end
end

function load_changes(changeset, state, values, autogen, adapter)::Changeset.t
    types = changeset.types
    changes = changeset.changes
    schema = changeset.data
    changeset.data = schema
    changeset
end

function put_repo_and_action(changeset::Changeset.t, action::Symbol, repo::Base.Random.UUID)::Changeset.t
     changeset.action = action
     changeset.repo = repo
     changeset.types = changeset.data[:types]
     changeset.changes = changeset.data.struct
     changeset
end

function struct_from_changeset!(action, changeset::Changeset.t)::Ecto.Schema.t
    isa(changeset.data, Void) && throw(ArgumentError("cannot $action a changeset without :data"))
    changeset.data
end

function dump_field!(action::Symbol, schema::Ecto.Schema.t, field::Symbol, typ, value, adapter)
    (isok, value) = Ecto.Typ.adapter_dump(adapter, typ, value)
    if :ok == isok
        (field, value)
    else
        throw(Ecto.ChangeError("value $value for $field in $action does not match type $typ"))
    end
end

function dump_fields!(action::Symbol, schema::Ecto.Schema.t, kw::Ecto.Assoc, types, adapter)
    typedict = Dict(types)
    for (field, value) in kw
        typ = typedict[field]
        dump_field!(action, schema, field, typ, value, adapter)
    end
end

function dump_changes!(action, changes, schema, extra, types, adapter)
    dumped = []
    autogen = []
    dump_fields!(action, schema, changes, types, adapter)
    (dumped, autogen)
end

function autogenerate_id(metadata, changes, retur, adapter)
    (changes, [], retur)
end

get_state(changeset::Changeset.t)::Symbol = changeset.data.metadata.state

function add_pk_filter!(filters, schema::Ecto.Schema.t)
    pks = Changeset.Relation.primary_keys!(schema)
    !issubset(pks, keys(schema.struct)) && throw(Ecto.NoPrimaryKeyValueError(""))
end

end # module Ecto.Repo.Schema


text:
abstract AbstractEvent
abstract PositionalEvent <: AbstractEvent

immutable HitEvent <: AbstractEvent
  bot_id::Int
  source::Int
end

immutable DeathEvent <: AbstractEvent
  bot_id::Int
end

immutable SightEvent <: PositionalEvent
  bot_id::Int
  source::Int
  pos::Position
end

immutable RadarEvent <: PositionalEvent
  pos::Position
end
botid(event::RadarEvent) = error("Radar event is not bound to specific bot.")

immutable DetectionEvent <: AbstractEvent
  bot_id::Int
end

immutable DamageEvent <: AbstractEvent
  bot_id::Int
  damage::Int
end

immutable MoveEvent <: PositionalEvent
  bot_id::Int
  pos::Position
end

immutable NoActionEvent <: AbstractEvent
  bot_id::Int
end

const EventTypeMap = Dict("hit" => HitEvent,
                      "die" => DeathEvent,
                      "see" => SightEvent,
                      "radarEcho" => RadarEvent,
                      "detected" => DetectionEvent,
                      "damaged" => DamageEvent,
                      "move" => MoveEvent,
                      "noaction" => NoActionEvent)

const EventNameMap = Dict(zip(values(EventTypeMap), keys(EventTypeMap)))

const EventMemberToID  = Dict(:bot_id => "botId", :source => "source", :damage => "damage", :pos => "pos")
const EventMemberTypes = Dict(:bot_id => Int, :source => Int, :damage => Int, :pos => Position)

# event functions
name(event::AbstractEvent) = EventNameMap[typeof(event)]
position(event::PositionalEvent) = event.pos
botid(event::AbstractEvent) = event.bot_id

function make_event(d::Dict)
  # get the event type
  etype = EventTypeMap[d["event"]]

  # find members and member types of the corresponding type
  member_symbols = fieldnames(etype)
  keys = [EventMemberToID[f] for f in member_symbols]
  types = [EventMemberTypes[f] for f in member_symbols]

  # and call the constructor with these dynamical arguments
  return etype( [t(d[k]) for (k, t) in zip(keys, types)]... )
end

max_stars_repo_name: Condimentum/spacetyckiting

max_issues_repo_name: Condimentum/spacetyckiting

max_forks_repo_name: Condimentum/spacetyckiting


text:
using NeidSolarScripts

using Statistics
# Test model/dataset
f_line(x;λo::Real, σ::Real, d::Real) = 1-d*exp(-0.5*((x-λo)/σ)^2)
 function f_model(x; fwhm::Real)
  speed_of_light_mks = 3e8 # m/s
  λcs = [5001, 5002.5, 5003,5004,5008,5008.3]
  ds = [0.25, 0.75, 0.5, 0.5, 0.5, 0.5]
  σs = λcs.*(fwhm/speed_of_light_mks)/sqrt(8(log(2)))
  f = prod(map(i->f_line(x,λo=λcs[i],σ=σs[i],d=ds[i]),1:length(λcs)))
  f *= 1.1-0.1*((x-mean(λcs))/(maximum(λcs)-minimum(λcs)))^2
end

λlo = 5000.0
 λhi = λlo*(5010/5000)
 fwhm_sol = 7.9e3 # m/s
 speed_of_light_mks = 3e8 # m/s
 R = 120000
 snr_per_res = 300
 oversample = 4
 n_res_elements = log(λhi/λlo)*R
 n_pixels = floor(Int64,n_res_elements*oversample/2)*2
 snr_per_pixel = snr_per_res/sqrt(n_pixels/n_res_elements)

 lambda = collect(range(λlo,stop=λhi,length=n_pixels))
 f_true = f_model.(lambda; fwhm=fwhm_sol)
 f_obs = f_true .+ (1/snr_per_pixel).*randn(length(f_true))

#using
(anchors, continuum, f_filtered) = Continuum.calc_continuum(lambda,f_obs)

using Plots
scatter(lambda,f_obs, color=:black, ms=2, legend=:none)
  plot!(lambda,f_filtered,color=:cyan)
  plot!(lambda,continuum,color=:magenta)
  scatter!(lambda[anchors], f_filtered[anchors], color=:blue, ms=4)
  ylims!(0.95,1.15)

true
true

#=
  #plot!(lambda,f_clean,ms=1.5, color=:green)
  #plot!(lambda,f_clip_threshold,color=:blue)
  #ylims!(0.9,1.2)
  #plot!(lambda,f_median_filtered.-f_clean)

 #plot!(lambda,rollingpin_radius./rollingpin_R_max)
 #plot(lambda,f_obs, legend=:none)
 #plot(lambda,f_obs, legend=:none)
 #plot!(lambda,f_interp)
 anchor_vals = f_median_filtered[anch]
 #scatter!(lambda[anch],anchor_vals, color=:blue)
 scatter!(lambda[anch],anchor_vals, color=:red)
 scatter!(lambda[anch[anch_mask]],anchor_vals[anch_mask], color=:blue)
 #interp_cubic = CubicSpline(f_median_filtered[anch],anchor_vals )
 #plot!(lambda,interp_cubic.(lambda), color=:green)
 ylims!(0.9,1.2)
 #xlims!(5006.5,5008)

  scatter!(lambda[anchors_merged],f_median_filtered[anchors_merged], color=:magenta)
 plot!(lambda,calc_continuum_from_anchors(lambda,f_median_filtered,anchors_merged),color=:red)

 #=
 plot!(λ_med_filtered,f_median_filtered)
 plot!(λ_med_filtered,f_median_filtered.+iqr)
 plot!(λ_med_filtered,f_median_filtered.-iqr)
 plot!(λ_med_filtered,f_interp, ms=2.0)
 scatter!(λ_med_filtered[anch],f_median_filtered[anch], ms=4.0)
 =#
 #ylims!(0.9,1.03)

#interp_bsp = BSplineApprox(lambda, f_obs,3,4,:ArcLen,:Average)
=#


text:
server = LanguageServerInstance(IOBuffer(), IOBuffer(), false, dirname(Pkg.Types.Context().env.project_file), first(Base.DEPOT_PATH))
server.runlinter = true

LanguageServer.process(LanguageServer.parse(LanguageServer.JSONRPC.Request, Dict("jsonrpc"=>"2.0","id"=>0,"method"=>"initialize","params"=>init_request)), server)

testtext = """
module testmodule
struct testtype
    a
    b::Float64
    c::Vector{Float64}
end
function testfunction(a, b::Float64, c::testtype)
    return c
end
end
testmodule
"""
LanguageServer.process(LanguageServer.JSONRPC.Request{Val{Symbol("textDocument/didOpen")},LanguageServer.DidOpenTextDocumentParams}(0, LanguageServer.DidOpenTextDocumentParams(LanguageServer.TextDocumentItem("testdoc", "julia", 0, testtext))), server)

doc = LanguageServer.getdocument(server, LanguageServer.URI2("testdoc"))
LanguageServer.parse_all(doc, server)

res = LanguageServer.process(LanguageServer.parse(LanguageServer.JSONRPC.Request, JSON.parse("""{"jsonrpc":"2.0","id":1,"method":"textDocument/hover","params":{"textDocument":{"uri":"testdoc"},"position":{"line":3,"character":11}}}""")), server)
@test res.contents.value == LanguageServer.sanitize_docstring(StaticLint.CoreTypes.Float64.doc)

res = LanguageServer.process(LanguageServer.parse(LanguageServer.JSONRPC.Request, JSON.parse("""{"jsonrpc":"2.0","id":1,"method":"textDocument/hover","params":{"textDocument":{"uri":"testdoc"},"position":{"line":7,"character":12}}}""")), server)
@test occursin(r"c::testtype", res.contents.value)

res = LanguageServer.process(LanguageServer.parse(LanguageServer.JSONRPC.Request, JSON.parse("""{"jsonrpc":"2.0","id":1,"method":"textDocument/hover","params":{"textDocument":{"uri":"testdoc"},"position":{"line":9,"character":1}}}""")), server)
@test res.contents.value == "Closes `ModuleH` expression."


text:
using Test, StorageColorTypes
using Colors, FixedPointNumbers

@testset "reinterpret" begin
    @testset "reinterpret RGB/ARGB" begin
        @test reinterpret(UInt16, RGB565LE(1, 0, 1)) === ltoh(0b11111000_00011111)
        @test reinterpret(UInt16, RGB565BE(1, 0, 1)) === ntoh(0b11111000_00011111)
        @test reinterpret(UInt16, RGB555LE(1, 0, 1)) === ltoh(0b01111100_00011111)
        @test reinterpret(UInt16, RGB555BE(1, 0, 1)) === ntoh(0b01111100_00011111)
        @test reinterpret(UInt16, XRGB444LE(1, 1, 0)) === ltoh(0b00001111_11110000)
        @test reinterpret(UInt16, XRGB444BE(1, 1, 0)) === ntoh(0b00001111_11110000)
        @test reinterpret(UInt16, RGBX444LE(0, 1, 1)) === ltoh(0b00001111_11110000)
        @test reinterpret(UInt16, RGBX444BE(0, 1, 1)) === ntoh(0b00001111_11110000)

        @test reinterpret(RGB565LE, ltoh(0b11111000_00011111)) === RGB565LE(1, 0, 1)
        @test reinterpret(RGB565BE, ntoh(0b11111000_00011111)) === RGB565BE(1, 0, 1)
        @test reinterpret(RGB555LE, ltoh(0b01111100_00011111)) === RGB555LE(1, 0, 1)
        @test reinterpret(RGB555BE, ntoh(0b01111100_00011111)) === RGB555BE(1, 0, 1)
        @test reinterpret(XRGB444LE, ltoh(0b00001111_11110000)) === XRGB444LE(1, 1, 0)
        @test reinterpret(XRGB444BE, ntoh(0b00001111_11110000)) === XRGB444BE(1, 1, 0)
        @test reinterpret(RGBX444LE, ltoh(0b00001111_11110000)) === RGBX444LE(0, 1, 1)
        @test reinterpret(RGBX444BE, ntoh(0b00001111_11110000)) === RGBX444BE(0, 1, 1)
    end

    @testset "reinterpret HSV/HSL" begin
        @test reinterpret(UInt8, [HSV24(100, 1.0, 0.5)]) == UInt8[ 50, 0xFF, 0x80]
        @test reinterpret(UInt8, [HSL24(200, 0.0, 0.6)]) == UInt8[100, 0x00, 0x99]
        @test reinterpret(UInt8, [HLS24(300, 0.0, 0.4)]) == UInt8[150, 0x66, 0x00]

        @test reinterpret(HSV24, UInt8[ 50, 0xFF, 0x80]) == [HSV24(100, 1.0, 0.5)]
        @test reinterpret(HSL24, UInt8[100, 0x00, 0x99]) == [HSL24(200, 0.0, 0.6)]
        @test reinterpret(HLS24, UInt8[150, 0x66, 0x00]) == [HLS24(300, 0.0, 0.4)]

        @test reinterpret(HLS{Float32}, [HSL{Float32}(200, 0.0, 0.6)]) ==
            [HLS{Float32}(200, 0.6, 0.0)]
    end

    @testset "reinterpret Lab/Luv" begin
        @test reinterpret(UInt8, [Lab24(60, 100, -100)]) == UInt8[0x99, 228, 28]
        @test reinterpret(UInt8, [Luv24(60, 100, -100)]) == UInt8[0x99, 169, 39]

        @test reinterpret(Lab24, UInt8[0x99, 228, 28]) == [Lab24(60, 100, -100)]
        @test reinterpret(Luv24, UInt8[0x99, 169, 39]) == [Luv24(60, 100, -100)]
    end
end


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

using Markdown
using InteractiveUtils

# ╔═╡ 4210f3a2-f61c-11eb-322f-c388a2ebc1ad
begin
    using Pkg
    Pkg.activate(joinpath(Pkg.devdir(), "MLCourse"))
    include(joinpath(Pkg.devdir(), "MLCourse", "src", "notebooks.jl"))
    list_notebooks(@__FILE__, "notebooks")
end

# ╔═╡ bd586b9b-2701-42ce-a56c-bdadf2576212
md"# Welcome!

On the following pages you find interactive animations, code examples (in the [Julia programming language](https://www.julialang.org)) and conceptual and applied exercises to learn more about machine learning.
"

# ╔═╡ 4744c137-8183-49a4-9a4a-4d86b96ae280
Markdown.parse(
(haskey(ENV, "html_export") && ENV["html_export"] == "true") ?
"!!! note

    To change the code in the notebooks used to generate these pages go to
    [https://github.com/jbrea/MLCourse](https://github.com/jbrea/MLCourse) and follow the instructions.
" :
"
Loading these pages takes quite a moment, because each page consists of cells
with code that is evaluated when you load the page or change its content
(you can see on the left border of a cell whether it is still computing or not).
Once the pages are loaded, changing some cells updates all the rest of the
notebook rather quickly.
"
)

# ╔═╡ 97134307-c909-4010-a0a9-72bf632182bf
footer()

# ╔═╡ Cell order:
# ╟─bd586b9b-2701-42ce-a56c-bdadf2576212
# ╟─4744c137-8183-49a4-9a4a-4d86b96ae280
# ╟─4210f3a2-f61c-11eb-322f-c388a2ebc1ad
# ╟─97134307-c909-4010-a0a9-72bf632182bf

max_stars_repo_name: baltisberger/MLCourse

max_issues_repo_name: baltisberger/MLCourse

max_forks_repo_name: baltisberger/MLCourse


text:
# Reload J4PR just in case ;)
module socket_servers

export start_sync_sock_server, start_async_sock_server

# Function that simply listens to a socket, takes the message and returns it
function start_sync_sock_server(socketpath, readyc=RemoteChannel(()->Channel(1)))
	@sync begin
		println("[PRE-listen]")
		issocket(socketpath) && rm(socketpath)
		server = listen(socketpath)
		println("[POST-listen]")

		println("Listening...")
		msg = ""
		while msg != "END"
			sock = accept(server)
			msg = readline(sock);
			println("Nope, $(msg) is not it")
		end
		println("yes, thats it")
		put!(readyc,1)
	end
	return 0
end

# Function that spawns an asynchronous task that performs stuff
# and returns the processed data to the calling routine.
# Like the main server which can be stopped by "END", the async
# task can be stopped by "TERMINATE"
function start_async_sock_server(socketpath, readyc=RemoteChannel(()->Channel(1)))

	# A small processing function
	f(x) = begin
		waittime=10*rand()
		println("\t[f] Processing... (wait time $(waittime)[s])")
		sleep(waittime)
		maximum(x)
	end

	#Function that reads a matrix from an input channel and returns the output of function f on an output channel
	my_processing(chi::Channel, cho::Channel, f::Function, ready::Condition) = begin
		while (true)
			msg = take!(chi)
			println("[MY_PROCESSING] Received $(msg) from channel, processing...")

			if replace(msg,"\n","") == "TERMINATE"
				println("[MY_PROCESSING] Terminating async process ...")
				notify(ready)
				break
			end

			try
				iv=[eval(parse(msg))...]
				ov = Float64(f(iv))
				print("[MY_PROCESSING] Putting output value on channel ...")
				put!(cho, ov)
				notify(ready)
				println("OK.")

			catch
				println("[MY_PROCESSING] Error, vector conversion failed. Waiting for new data...")
				put!(cho,nothing)
				notify(ready)
			end
		end
	end

	# Define channels
	chi = Channel{String}(1024)
	cho = Channel{Any}(10)
	asyncready = Condition()

	# Start asynchronous task
	@async my_processing(chi, cho, f, asyncready)
	asyncrunning = true

	# Start the server
	@sync begin
		# Check for and remove any unix socket if present
		issocket(socketpath) && rm(socketpath)

		# Start listening
		server = listen(socketpath)
		while (true)
			println("[MAIN] Listening...")
			sock = accept(server)
			msg = readline(sock);

			if (replace(msg,"\n","") != "END" )														# Check for "END" message, if so terminate server

				# Part run only when asynchronous task is running
				################################################
				if (asyncrunning)																	# If asynchronous task is running,
					put!(chi, msg) 																	# Send message to asynchronous task
					wait(asyncready)																# wait for the ready condition then
					if isready(cho)																	# check if the channel has data
						println("[MAIN] Output is: $(take!(cho))")									# and if it has print it
					else
						# Condition was triggered however channel is not ready, process exited
						asyncrunning = false														# mark the task as not running anymore
					end
				end
				################################################
			else
				println("[MAIN] Terminating main process ...")
				put!(readyc,1)
				exit(0)
			end #if
		end #while
	end # @sync block
end

end # end module


text:
using GeometryBasics: Triangle, Tetrahedron, Mesh, Polytope

"""
    Mesh{Tetrahedron}(result::JLTetGenIO)

Extracts the *tetrahedral* mesh from `tetgenio`.
Can also be called with extra information, e.g.:
```julia
    Mesh{Tetrahedron{Float32}}(tetio)
    NDim = 3; T = Float64; PointType = MyPoint{3, Float64}; Edges = 4
    Mesh{Simplex{NDim, T, Edges, PointType}}(tetio)
```

    Mesh{Triangle}(result::JLTetGenIO)

Extracts the triangular *surface* mesh from `tetgenio`.
Can also be called with extra information, e.g.:
```julia
    Mesh{Triangle3d{Float32}}(tetio)
    NDim = 3; T = Float64; PointType = MyPoint{3, Float64}; Edges = 3
    Mesh{Ngon{NDim, T, 3, PointType}}(tetio)
```
"""
function GeometryBasics.Mesh{P}(x::JLTetGenIO{T}) where {P <: Polytope{N, T} where {N, T}, T}
    Mesh{Polytope(P, Point{3, T})}(x)
end

function GeometryBasics.Mesh{TetrahedronP{ET, P}}(x::JLTetGenIO) where {ET, P}
    Mesh(convert(Vector{P}, x.points), x.tetrahedra)
end

function GeometryBasics.Mesh{TriangleP{3, ET, P}}(x::JLTetGenIO) where {ET, P}
    Mesh(convert(Vector{P}, x.points), x.trifaces)
end


text:
"""
    proj(v)

Returns a projector onto subspace spanned by `v`.
"""
function proj(v::SparseVector{T}) where T<:Number
   SparseMatrixCSC{T}(v*v')
end

function proj(v::AbstractVector{<:Number})
   v*v'
end

"""
    szegedy_walk_operators(szegedy)

Return pair of Szegedy walk operators based on `sqrtstochastic` from `szegedy`.
Definition of those can be found in https://arxiv.org/abs/1611.02238 on page 4.
The operators should be applied in given order.
"""

function szegedy_walk_operators(szegedy::AbstractSzegedy)
   order = nv(szegedy.graph)
   projectors = map(x->2. * proj(szegedy.sqrtstochastic[:,x]), 1:order)

   r1 = cat(projectors..., dims=(1, 2))

   r2 = spzeros(eltype(szegedy.sqrtstochastic), order^2, order^2)
   for x=1:order
      r2[(1:order:order^2) .+ (x-1),(1:order:order^2) .+ (x-1)] = projectors[x]
   end

   r1 -= I
   r2 -= I

   (r1, r2)
end

"""
    szegedy_oracle_operators(szegedy, marked)

Return a Szegedy oracle operators based on `sqrtstochastic` from `szegedy` and
collection of `marked` vertices. Definition of those can be found in
https://arxiv.org/abs/1611.02238 on page 6. The operators should be applied in
given order.
"""
function szegedy_oracle_operators(szegedy::AbstractSzegedy,
                                marked::Vector{Int})
   order = nv(szegedy.graph)

   markedidentity = SparseMatrixCSC{eltype(szegedy.sqrtstochastic)}(I, order, order)
   for v=marked
      markedidentity[v,v] = -1.
   end

   q1 = kron(markedidentity, SparseMatrixCSC{eltype(szegedy.sqrtstochastic)}(I, order, order))
   q2 = kron(SparseMatrixCSC{eltype(szegedy.sqrtstochastic)}(I, order, order), markedidentity)

   (q1, q2)
end


text:
module Storage

include("types.jl")
include("table.jl")

export FileResource
export exists

export load_numerical_table

end  # module Storage


text:
using DataDrivenDiffEq
using ModelingToolkit
using OrdinaryDiffEq

using Dierckx
using Statistics
using LinearAlgebra
using Plots
gr()

# Create a test problem
function lorenz(u,p,t)
    x, y, z = u

    ẋ = 10.0*(y - x)
    ẏ = x*(28.0-z) - y
    ż = x*y - (8/3)*z
    return [ẋ, ẏ, ż]
end

u0 = [-8.;8.;27.]
tspan = (0.0,200.0)
dt = 0.001
prob = ODEProblem(lorenz,u0,tspan)
sol = solve(prob, Tsit5(), reltol = 1e-12, abstol = 1e-12,  saveat = dt)

plot(sol,vars=(1,2,3))

# Differential data from equations
X = Array(sol)

# Time delay coordinates
stackmax = 100

H = zeros(eltype(x), stackmax, size(X,2)-stackmax)
for i in 1:stackmax
    H[i, :] = X[1, i:end-stackmax+i-1]
end

m,n = minimum(size(H)), maximum(size(H))
U, S, V = svd(H, full = false)
τ = DataDrivenDiffEq.optimal_svht(m,n)
r = length(S[S .> τ*median(S)])
r = minimum([15, r])

z = Array(V[:, 1:r]')
dz = similar(z)

for (i, vi) in enumerate(eachrow(z))
    x_int = Spline1D(sol.t[1:length(vi)], vi)
    dz[i, :] = derivative(x_int, sol.t[1:length(vi)])
end

plot(plot(z[1, :]),plot(z[end, :].^2),  layout = (2, 1))

@variables u[1:r]

basis = Basis(u, u)
opt = SR3(1e-1)
b = SInDy(z[:, 1:end], dz[1:end-1, 1:end], basis, maxiter = 1000, opt = opt, normalize = true)

# Coincides with the paper results
println(b)


text:
using Gnuplot, ColorSchemes
#first plot
ψ1 = ψ2 = LinRange(0, 4π, 100)
function tα_qubit(β, ψ1, ψ2, fα, f)
    term1 = 2 .+ 2 .*β .- cos.(ψ1) .- cos.(ψ2)
    term2 = 2*β*cos.(π*fα) .* cos.(2*π*f .+ π*fα .- ψ1 .- ψ2)
    term1 .- term2
end
tα_qubitarr = [tα_qubit(0.61, i, j, 0.2, 0.1) for i in ψ1, j in ψ2]
#second plot
x = y = -15:0.33:15
fz(x,y) = sin.(sqrt.(x.^2 + y.^2))./sqrt.(x.^2+y.^2)
fxy = [fz(x,y) for x in x, y in y]
@gsp xlabel = "ψ1" ylabel = "ψ2" title = "tunnel α_{q}" :-
@gsp :- ψ1 ψ2 tα_qubitarr "w pm3d" "set view map" palette(:viridis)
@gsp :- "set size square" "set auto fix" :-
@gsp :- "set multiplot layout 1,2 title 'multiplot layout'" :-
@gsp :- 2 xlab="x" ylab="y" title = "Mexican hat" :-
@gsp :- x y fxy "w l lc palette" "unset view" "set key off"
@gsp :- "set view 65,30" palette(:lajolla) "set size square"
@gsp :- "set auto fix"
save(term="pngcairo size 1200,800", output="./code/pltf_ex1.png") #hide

max_stars_repo_name: lazarusA/gnuplot-examples

max_issues_repo_name: lazarusA/gnuplot-examples

max_forks_repo_name: lazarusA/gnuplot-examples


text:
# AUTO GENERATED FILE - DO NOT EDIT

export dcc_loading

"""
    dcc_loading(;kwargs...)
    dcc_loading(children::Any;kwargs...)
    dcc_loading(children_maker::Function;kwargs...)

A Loading component.
A Loading component that wraps any other component and displays a spinner until the wrapped component has rendered.
Keyword arguments:
- `children` (Array of a list of or a singular dash component, string or numbers | a list of or a singular dash component, string or number; optional): Array that holds components to render
- `id` (String; optional): The ID of this component, used to identify dash components
in callbacks. The ID needs to be unique across all of the
components in an app.
- `type` (a value equal to: 'graph', 'cube', 'circle', 'dot', 'default'; optional): Property that determines which spinner to show
one of 'graph', 'cube', 'circle', 'dot', or 'default'.
- `fullscreen` (Bool; optional): Boolean that makes the spinner display full-screen
- `debug` (Bool; optional): If true, the spinner will display the component_name and prop_name
while loading
- `className` (String; optional): Additional CSS class for the spinner root DOM node
- `parent_className` (String; optional): Additional CSS class for the outermost dcc.Loading parent div DOM node
- `style` (Dict; optional): Additional CSS styling for the spinner root DOM node
- `parent_style` (Dict; optional): Additional CSS styling for the outermost dcc.Loading parent div DOM node
- `color` (String; optional): Primary colour used for the loading spinners
- `loading_state` (optional): Object that holds the loading state object coming from dash-renderer. loading_state has the following type: lists containing elements 'is_loading', 'prop_name', 'component_name'.
Those elements have the following types:
  - `is_loading` (Bool; optional): Determines if the component is loading or not
  - `prop_name` (String; optional): Holds which property is loading
  - `component_name` (String; optional): Holds the name of the component that is loading
"""
function dcc_loading(; kwargs...)
        available_props = Symbol[:children, :id, :type, :fullscreen, :debug, :className, :parent_className, :style, :parent_style, :color, :loading_state]
        wild_props = Symbol[]
        return Component("dcc_loading", "Loading", "dash_core_components", available_props, wild_props; kwargs...)
end

dcc_loading(children::Any; kwargs...) = dcc_loading(;kwargs..., children = children)
dcc_loading(children_maker::Function; kwargs...) = dcc_loading(children_maker(); kwargs...)

max_stars_repo_name: asc-csa/dash-core-components

max_issues_repo_name: asc-csa/dash-core-components

max_forks_repo_name: asc-csa/dash-core-components


text:
# This example was inspired by this great blog post:
# https://cre8math.com/2015/10/04/creating-fractals/

using GLVisualize, GLAbstraction, Reactive, GeometryTypes, Colors, GLWindow
import GLVisualize: slider, mm, button, labeled_slider

if !isdefined(:runtests)
    window = glscreen()
end

description = """
Demonstrating a UI for exploring the Koch snowflake.
"""

function spin(dir, α, len)
    x, y = dir
    Point(x*cos(α) - y*sin(α), x*sin(α) + y*cos(α)) * len
end
function fractal_step!(
        a, b, depth, angles,
        result = Point2f0[a], levels = Float32[depth] # tmp too not allocate
    )
    depth == 0 && return result, levels, b
    N = length(angles)
    diff = (b - a)
    len = norm(diff) / (N - 1)
    nth_segment = normalize(diff)
    for n = 1:N
        b = a + spin(nth_segment * len, angles[n]...) # rotate with current angle
        _, _, b = fractal_step!(a, b, depth-1, angles, result, levels) # recursion step
        if n < N
            push!(result, b)
            push!(levels, depth)
        end
        nth_segment = normalize(b - a)
        a = b
    end
    result, levels, b
end

const T = Float64
const P = Point{2, T}

function generate_fractal(angles, depth = 5)
    tmp = zeros(P, length(angles))
    angles = map(x-> (deg2rad(T(x[1])), T(x[2])), angles)
    result, levels, b = fractal_step!(P(0,0), P(300,0), round(Int, depth), angles)
    push!(result, b)
    push!(levels, depth)
    mini, maxi = extrema(result)
    w = 1 ./ maximum(maxi - mini)
    map!(result, result) do p
        1000 * (p - mini) .* w
    end
    # invert
    result, levels
end

iconsize = 5mm
textsize = 5mm

editarea, viewarea = x_partition_abs(window.area, round(Int, 12 * iconsize))
edit_screen = Screen(
    window, area = editarea,
    color = RGBA{Float32}(0.0f0, 0.0f0, 0.0f0, 1f0),
    stroke = (1f0, RGBA{Float32}(0.13f0, 0.13f0, 0.13f0, 1f0))
)
viewscreen = Screen(
    window, area = viewarea,
    color = RGBA(0.0f0, 0.0f0, 0.0f0, 1f0)
)

angles = ntuple(4) do i
    labeled_slider(0.0:1.0:360.0, edit_screen, text_scale = textsize, icon_size = iconsize, knob_scale = 3mm)
end

iterations_v, iterations_s = labeled_slider(1:11, edit_screen, text_scale = textsize, icon_size = iconsize, knob_scale = 3mm)

cmap_v, cmap_s = widget(
    map(RGBA{Float32}, colormap("Blues", 5)),
    edit_screen;
    area = (12 * iconsize, iconsize/3),
    knob_scale = 1.3mm,
)

thickness_v, thickness_s = widget(
    Signal(0.4f0), edit_screen,
    text_scale = textsize,
    range = 0f0:0.05f0:20f0
)

segments = Point2f0[
    (0.0, 0.0),
    (2 * iconsize, 0.0),
    (4 * iconsize, iconsize /  2),
    (6 * iconsize, iconsize / -2),
    (7 * iconsize, 0.0)
]

# we could restrict the movement of the points with the kw_arg clampto
# But I don't really feel like restricting the user here ;)
line_v, line_s = widget(segments, edit_screen, knob_scale = 1.5mm)

center_v, center_s = button("⛶", relative_scale = iconsize, edit_screen)

controls = Pair[
    "angle 1" => angles[1][1],
    "angle 2" => angles[2][1],
    "angle 3" => angles[3][1],
    "angle 4" => angles[4][1],
    "iterations" => iterations_v,
    "colormap" => cmap_v,
    "thickness" => thickness_v,
    "segment" => line_v,
    "center cam" => center_v
]

_view(visualize(
    controls,
    text_scale = textsize,
    width = 12iconsize
), edit_screen, camera = :fixed_pixel)

function to_anglelengths(angles, line)
    diff0 = Point2f0(1, 0)
    v1 = first(line)
    maxlen = 0
    for (i, v2) in enumerate(line[2:end])
        diff1 = v2 - v1
        len = norm(diff1)
        diff1 = normalize(diff1)
        maxlen = max(len, maxlen)

        d = dot(diff0, diff1)
        det = cross(diff0, diff1)

        angles[i] = (atan2(det, d), len)
        v1 = v2; diff0 = diff1
    end
    for (i, al) in enumerate(angles)
        angles[i] = (rad2deg(al[1]), al[2] / maxlen)
    end
    angles
end
v0 = to_anglelengths(Array{Tuple{Float32, Float32}}(4), value(line_s))

angle_vec1 = foldp(to_anglelengths, v0, line_s)

angle_s = map(last, angles)
anglevec2 = foldp(Array{Tuple{Float32, Float32}}(4), angle_s...) do angles, s...
    for i=1:4
        angles[i] = s[i], 1.0
    end
    angles
end
anglevec = merge(angle_vec1, anglevec2)

it1_points = map(anglevec) do angles
    generate_fractal(angles, 1)[1] ./ 100f0
end

line_level = map(anglevec, iterations_s) do angles, iter
    generate_fractal(angles, iter)
end
line_pos = map(first, line_level)
_view(visualize(
    line_pos, :lines,
    thickness = thickness_s,
    color_map = cmap_s,
    color_norm = map(i-> Vec2f0(0, i), iterations_s),
    intensity = map(last, line_level),
    boundingbox = nothing
), viewscreen, camera = :orthographic_pixel)

_view(visualize(
    it1_points, :lines, model = translationmatrix(Vec3f0(20, 20, 0)),
    thickness = 2f0, color = RGBA(1f0, 1f0, 1f0, 1f0)
), viewscreen, camera = :fixed_pixel)

const cam = viewscreen.cameras[:orthographic_pixel]

s = preserve(map(center_s) do clicked
    clicked && center!(cam, AABB(value(line_pos)))
    nothing
end)

# center won't get executed before the first time the center button is clicked.
# we still want to start centered ;)
center!(cam, AABB(value(line_pos)))

if !isdefined(:runtests)
    renderloop(window)
    # clean up signals
    for (v, s) in angles
        close(s, false)
    end
    close(center_s, false)
    close(thickness_s, false)
    close(iterations_s, false)
    close(iterations_s, false)
end

# you can change angles directly like this:
# you need to start the renderloop asynchronously then though: @async renderloop(window)
# And then of course, don't clean up the signals before you are done
#push!(angles[3][2], 220f0)


text:
@testset "pointer" begin

# inner constructors

voidptr_a = Ptr{Cvoid}(Int(0xDEADBEEF))
generic_voidptr_a = CUDAnative.DevicePtr{Cvoid,AS.Generic}(voidptr_a)
global_voidptr_a = CUDAnative.DevicePtr{Cvoid,AS.Global}(voidptr_a)
local_voidptr_a = CUDAnative.DevicePtr{Cvoid,AS.Local}(voidptr_a)

voidptr_b = Ptr{Cvoid}(Int(0xCAFEBABE))
generic_voidptr_b = CUDAnative.DevicePtr{Cvoid,AS.Generic}(voidptr_b)
global_voidptr_b = CUDAnative.DevicePtr{Cvoid,AS.Global}(voidptr_b)
local_voidptr_b = CUDAnative.DevicePtr{Cvoid,AS.Local}(voidptr_b)

intptr_b = convert(Ptr{Int}, voidptr_b)
generic_intptr_b = CUDAnative.DevicePtr{Int,AS.Generic}(intptr_b)
global_intptr_b = CUDAnative.DevicePtr{Int,AS.Global}(intptr_b)
local_intptr_b = CUDAnative.DevicePtr{Int,AS.Local}(intptr_b)

# outer constructors
@test CUDAnative.DevicePtr{Cvoid}(voidptr_a) == generic_voidptr_a
@test CUDAnative.DevicePtr(voidptr_a) == generic_voidptr_a

# getters
@test eltype(generic_voidptr_a) == Cvoid
@test eltype(global_intptr_b) == Int
@test addrspace(generic_voidptr_a) == AS.Generic
@test addrspace(global_voidptr_a) == AS.Global
@test addrspace(local_voidptr_a) == AS.Local

# comparisons
@test generic_voidptr_a != global_voidptr_a
@test generic_voidptr_a != generic_intptr_b

@testset "conversions" begin

# between regular and device pointers

@test_throws InexactError convert(Ptr{Cvoid}, generic_voidptr_a)
@test_throws InexactError convert(CUDAnative.DevicePtr{Cvoid}, voidptr_a)

@test Base.unsafe_convert(Ptr{Cvoid}, generic_voidptr_a) == voidptr_a

# between device pointers

@test_throws InexactError convert(typeof(local_voidptr_a), global_voidptr_a)
@test convert(typeof(generic_voidptr_a), generic_voidptr_a) == generic_voidptr_a
@test convert(typeof(global_voidptr_a), global_voidptr_a) == global_voidptr_a
@test Base.unsafe_convert(typeof(local_voidptr_a), global_voidptr_a) == local_voidptr_a

@test convert(typeof(global_voidptr_a), global_intptr_b) == global_voidptr_b
@test convert(typeof(generic_voidptr_a), global_intptr_b) == generic_voidptr_b
@test convert(typeof(global_voidptr_a), generic_intptr_b) == global_voidptr_b

@test convert(CUDAnative.DevicePtr{Cvoid}, global_intptr_b) == global_voidptr_b

end

end


text:
module Codify

using FieldMetadata, Requires

import FieldMetadata: flattenable, @flattenable

export codify

# Optionally load Unitful
function __init__()
    @require Unitful="1986cc42-f94f-5a68-af5c-568840ba703d" begin
        using .Unitful
        codify(x::Unitful.Quantity, spaces) = begin
            io = IOBuffer()
            print(IOContext(io, :showoperators => true), x)
            str = String(take!(io))
            # Replace space before units with u"" string macro
            occursin(" ", str) ? (replace(str, " " => "u\"") * "\"",) : (str,)
        end
    end
end

linebreak(exps) = length(exps) > 0 ? :("\n", spaces) : :("",)

codify_inner(T) =
    codify_combiner(T, [Expr(:..., codify_builder(T, fn)) for fn in fieldnames(T)])
codify_combiner(T, exps) =
    :(string($T.name.name, "(", $(exps...), $(linebreak(exps))..., ")"))
codify_combiner(T::Type{<:Tuple}, exps) =
    :(string("(", $(exps...), $(linebreak(exps))..., ")"))
codify_builder(T::Type{<:Tuple}, fname) = quote
    fieldcode = codify(getfield(t, $(QuoteNode(fname))), spaces * "    ")
    string.("\n    ", spaces, fieldcode, ",")
end
codify_builder(T, fname) = quote
    if flattenable($T, Val{$(QuoteNode(fname))})
        string.("\n    ", spaces, $(QuoteNode(fname)), " = ",
                codify(getfield(t, $(QuoteNode(fname))), spaces * "    "), ",")
    else
        ()
    end
end

codify(x::Nothing, args...) = ("nothing",)
codify(x::Number, args...) = ("$x",)
codify(x::Symbol, args...) = (":$x",)
codify(t) = codify(t, "")
@generated codify(t, spaces) = codify_inner(t)

end # module


text:
using Test
import ArchGDAL; const AG = ArchGDAL

@testset "Testing Displays for different objects" begin
    AG.read("data/point.geojson") do dataset
        @test sprint(print, dataset) == """
        GDAL Dataset (Driver: GeoJSON/GeoJSON)
        File(s):
          data/point.geojson

        Number of feature layers: 1
          Layer 0: point (wkbPoint)
        """

        layer = AG.getlayer(dataset, 0)
        @test sprint(print, layer) == """
        Layer: point
          Geometry 0 (): [wkbPoint], POINT (100 0), POINT (100.2785 0.0893), ...
             Field 0 (FID): [OFTReal], 2.0, 3.0, 0.0, 3.0
             Field 1 (pointname): [OFTString], point-a, point-b, a, b
        """
        @test sprint(print, AG.nextnamedtuple(layer), context=:compact => true) ==
        "(FID = 2.0, pointname = \"point-a\",  = Geometry: wkbPoint)"
        @test sprint(print, AG.layerdefn(layer)) == """
          Geometry (index 0):  (wkbPoint)
             Field (index 0): FID (OFTReal)
             Field (index 1): pointname (OFTString)
        """
        @test sprint(print, AG.getspatialref(layer)) ==
            "Spatial Reference System: +proj=longlat +datum=WGS84 +no_defs"

        AG.getfeature(layer, 2) do feature
            @test sprint(print, feature) == """
            Feature
              (index 0) geom => POINT
              (index 0) FID => 0.0
              (index 1) pointname => a
            """
            @test sprint(print, AG.getfielddefn(feature, 1)) ==
                "pointname (OFTString)"
            @test sprint(print, AG.getgeomdefn(feature, 0)) ==
                " (wkbPoint)"
        end
    end

    AG.read("gdalworkshop/world.tif") do dataset
        @test sprint(print, dataset) == """
        GDAL Dataset (Driver: GTiff/GeoTIFF)
        File(s):
          gdalworkshop/world.tif

        Dataset (width x height): 2048 x 1024 (pixels)
        Number of raster bands: 3
          [GA_ReadOnly] Band 1 (Red): 2048 x 1024 (UInt8)
          [GA_ReadOnly] Band 2 (Green): 2048 x 1024 (UInt8)
          [GA_ReadOnly] Band 3 (Blue): 2048 x 1024 (UInt8)
        """

        @test sprint(print, AG.getband(dataset, 1)) == """
        [GA_ReadOnly] Band 1 (Red): 2048 x 1024 (UInt8)
            blocksize: 256×256, nodata: -1.0e10, units: 1.0px + 0.0
            overviews: (0) 1024x512 (1) 512x256 (2) 256x128
                       (3) 128x64 (4) 64x32 (5) 32x16
                       (6) 16x8 """
    end
end

# untested
# Geometry with length(toWKT(geom)) > 60 # should be able to see ...
# Dataset with nlayer(dataset) > 5