text:
# check for gaps in channel i of struct S
function check_for_gap!(S::GphysData, i::Integer, t0::Int64, nx::Integer, v::Int64)
  Δ = round(Int64, sμ / getindex(getfield(S, :fs), i))
  t = getindex(getfield(S, :t), i)
  nt = size(t,1)
  lxi = t[nt,1]
  te = endtime(t, Δ)
  τ = t0 - te - Δ
  if abs(τ) > div(Δ, 2)
    v > 1 && println(stdout, S.id[i], ": gap = ", τ, " μs (old end = ",
    te, ", New start = ", τ + te + Δ)
    setindex!(t, getindex(t, nt)+1, nt)
    setindex!(t, getindex(t, 2*nt)+τ, 2*nt)
    setindex!(getfield(S, :t), vcat(t, [lxi+nx zero(Int64)]), i)
  else
    setindex!(t, lxi+nx, nt)
  end
  return nothing
end


text:
using Test
using Logging
using ClickHouse

global_logger(SimpleLogger(stdout, Logging.Debug))

@testset "Client" begin
    client = ClickHouseClient("http://localhost:8123")
    query(client, "CREATE TABLE clickhouse_jl_test (a UInt32, b Float64) ENGINE MergeTree() ORDER BY a")
    query(client, "INSERT INTO clickhouse_jl_test (a, b) VALUES (1, 1.0) (2, 2.0)")
    df = query(client, "SELECT * FROM clickhouse_jl_test")
    @test size(df) == (2, 2)
    query(client, "DROP TABLE clickhouse_jl_test")
end

ext: jl


text:
using .CuArrays
using Serialization
import Serialization: serialize

const CuFlatS0{P,T,M<:CuArray} = FlatS0{P,T,M}

### broadcasting
preprocess(dest::F, bc::Broadcasted) where {F<:CuFlatS0} =
    Broadcasted{Nothing}(CuArrays.cufunc(bc.f), preprocess_args(dest, bc.args), map(OneTo,size_2d(F)))
preprocess(dest::F, arg) where {M,F<:CuFlatS0{<:Any,<:Any,M}} =
    adapt(M,broadcastable(F, arg))
function copyto!(dest::F, bc::Broadcasted{Nothing}) where {F<:CuFlatS0}
    bc′ = preprocess(dest, bc)
    copyto!(firstfield(dest), bc′)
    return dest
end
BroadcastStyle(::FlatS0Style{F,Array}, ::FlatS0Style{F,CuArray}) where {P,F<:FlatS0{P}} =
    FlatS0Style{basetype(F){P},CuArray}()

# always adapt to Array storage when serializing since we may deserialize in an
# environment that does not have CuArrays loaded
serialize(s::AbstractSerializer, f::CuFlatS0) = serialize(s, adapt(Array,f))

### misc
# the generic versions of these trigger scalar indexing of CuArrays, so provide
# specialized versions:

function copyto!(dst::F, src::F) where {F<:CuFlatS0}
    copyto!(firstfield(dst),firstfield(src))
    dst
end
pinv(D::Diagonal{T,<:CuFlatS0}) where {T} = Diagonal(@. ifelse(isfinite(inv(D.diag)), inv(D.diag), $zero(T)))
inv(D::Diagonal{T,<:CuFlatS0}) where {T} = any(Array((D.diag.==0)[:])) ? throw(SingularException(-1)) : Diagonal(inv.(D.diag))
fill!(f::CuFlatS0, x) = (fill!(firstfield(f),x); f)
dot(a::CuFlatS0, b::CuFlatS0) = sum_kbn(Array(Map(a).Ix .* Map(b).Ix)) * fieldinfo(a).Δx^2
≈(a::CuFlatS0, b::CuFlatS0) = (firstfield(a) ≈ firstfield(b))

# some pretty low-level hacks to get a few thing broadcasting correctly for
# Complex arguments that don't currently work in CuArrays
CuArrays.CUDAnative.isfinite(x::Complex) = Base.isfinite(x)
CuArrays.CUDAnative.sqrt(x::Complex) = CuArrays.CUDAnative.sqrt(CuArrays.CUDAnative.abs(x)) * CuArrays.CUDAnative.exp(im*CuArrays.CUDAnative.angle(x)/2)
CuArrays.culiteral_pow(::typeof(^), x::Complex, ::Val{2}) = x * x


text:
# ScatteringLayerState
immutable ScatteringLayerState{B<:ScatteredBlob} <: AbstractScatteredLayerState
    blobs::Vector{B}
    layer::ScatteringLayer
end

function ScatteringLayerState(
        backend::Mocha.Backend,
        layer::ScatteringLayer,
        inputs::Vector{Mocha.Blob},
        diffs::Vector{Mocha.Blob})
    innodes = inputs[1].nodes
    firstpath = collect(keys(innodes))[1]
    pathkey = layer.bank.behavior.pathkey
    order = scattering_order(firstpath, pathkey)
    assert(order > 0)
    j1key = prepend((:j, order), pathkey)
    previous_bank = layer.previous_bank
    previous_ψmetas = previous_bank.spec.ψmetas
    previous_bandwidths = map(get_bandwidth, previous_ψmetas)
    previous_log2_samplings = previous_bank.behavior.ψ_log2_samplings
    ψmetas = layer.bank.spec.ψmetas
    centerfrequencies = map(get_centerfrequency, ψmetas)
    n_octaves = size(centerfrequencies, 3)
    first_j1 = layer.previous_bank.behavior.j_range.start
    paths = collect(keys(innodes))
    chromakey = prepend((:χ, 1+order), pathkey)
    n_filters_per_octave = layer.bank.spec.n_filters_per_octave
    chromarange = chromakey => 0:1:(n_filters_per_octave-1)
    octavekey = prepend((:j, 1+order), pathkey)
    bandwidths = layer.sibling_mask_factor * previous_bandwidths[1, 1, :]
    outnodes = DataStructures.SortedDict{Path,AbstractNode,
        Base.Order.ForwardOrdering}()
    for j2 in layer.bank.behavior.j_range
        centerfrequency = centerfrequencies[1, end, 1+j2]
        last_j1 = findlast(bandwidths .>= centerfrequency) - 1
        last_j1 = min(last_j1, previous_bank.behavior.j_range.stop)
        log2_sampling = layer.bank.behavior.ψ_log2_samplings[1+j2]
        for inpath in keys(innodes)
            innode = innodes[inpath]
            j1 = inpath.sdict[j1key]
            (j1 < first_j1) && continue
            (j1 > last_j1) && continue
            inranges = innode.ranges
            inpathkeys = [ pair.first for pair in collect(inranges) ]
            subscripts = find(pathkey .== inpathkeys)
            insizes = collect(size(innode.data))
            if isa(innode, RealFourierNode)
                insizes[subscripts] = 2 * (insizes[subscripts] - 1)
            end
            outranges = [inranges..., chromarange]
            outsizes = [insizes ; layer.bank.spec.n_filters_per_octave]
            previous_log2_sampling = previous_log2_samplings[1+j1]
            log2_resampling = log2_sampling - previous_log2_sampling
            for subscript in subscripts
                outsizes[subscript] = insizes[subscript] >> (-log2_resampling)
                inrange = inranges[subscript].second
                outranges[subscript] = outranges[subscript].first =>
                    (inrange.start):(1<<-log2_resampling):(inrange.stop)
            end
            outdata = zeros(eltype(innode.data), tuple(outsizes...))
            inds = [fill(Colon(), ndims(innode.data)) ; 0]
            for χ2 in 0:(layer.bank.spec.n_filters_per_octave-1)
                ψ = layer.bank.ψs[1, 1+χ2, 1+j2]
                inds[end] = 1 + χ2
                transform!(view(outdata, inds...), ψ, innode, subscripts...)
            end
            outpath = Path(inpath.sdict..., octavekey => j2)
            outnodes[outpath] = Node(outdata, tuple(outranges...))
        end
    end
    ScatteringLayerState([ScatteredBlob(outnodes)], layer)
end

function Mocha.setup(
        backend::Mocha.Backend,
        layer::ScatteringLayer,
        inputs::Vector{Mocha.Blob},
        diffs::Vector{Mocha.Blob})
    return ScatteringLayerState(backend, layer, inputs, diffs)
end


text:
export relaxationMap

"""
  Calculates the relaxationMap based on the pixel values of the image

  ...
  # Arguments
  * `image::Matrix` : Image whose values determine the relaxationrate at each pixel.
  * `minRelaxation::Float64=5.0` : minimum relaxationrate measured in [Hz]
  * `maxRelaxation::Float64=125.0` : maximum relaxationrate measured in [Hz]
  ...
"""
function relaxationMap(image::Matrix,minRelaxation::Float64=5.0,maxRelaxation::Float64=125.0)
  # consistency check
  if minRelaxation > maxRelaxation
    warning("Minimal frequency > Maximalfrequency! Both will be swapped now")
    minRelaxation,maxRelaxation = maxRelaxation,minRelaxation
  end

  relaxMap = zeros(size(image))
  # normalize first
  minVal = minimum(image)
  maxVal = maximum(image)
  z = image .- minVal ./ (maxVal-minVal)

  # now denormalize
  relaxMap = z .* (maxRelaxation - minRelaxation) .+ minRelaxation

  return relaxMap

end


text:
module PrettyMacroExpand

using MacroTools: prettify
using JuliaFormatter: format_text
using Markdown: Markdown

export @prettyexpand
export @prettyexpand1
export @prettyexpand_md
export @prettyexpand1_md

const alias = Ref(true)
const margin = Ref(80)

macro prettyexpand(exp)
    quote
        print($(prettyexpand(exp)))
    end
end

macro prettyexpand1(exp)
    quote
        print($(prettyexpand1(exp)))
    end
end

function prettyexpand(exp)
    quote
        format_text(
            string(
                prettify(
                    @macroexpand($exp),
                    alias = alias[],
                )
            );
            margin = margin[]
        )
    end
end

function prettyexpand1(exp)
    quote
        format_text(
            string(
                prettify(
                    @macroexpand1($exp),
                    alias = alias[],
                )
            );
            margin = margin[]
        )
    end
end

macro prettyexpand_md(exp)
    quote
        Markdown.parse(
            """
            ```julia
            $($(prettyexpand(exp)))
            ```
            """
        )
    end
end

macro prettyexpand1_md(exp)
    quote
        Markdown.parse(
            """
            ```julia
            $($(prettyexpand1(exp)))
            ```
            """
        )
    end
end

end


text:
#=
Takes a smooth janelia traced whisker, and generateds a set of discrete points
along the whisker of equal spacing
=#
function make_discrete(p_array::Array{Float32,2},ind,w::Whisker1,spacing)

    p_array[1,ind] = w.x[end]
    p_array[2,ind] = w.y[end]

    num_points=div(size(p_array,1),2)

    for i=2:num_points

        id=culm_dist(w.x,w.y,spacing*(i-1))
        if id != 1
            p_array[(i*2) - 1,ind] = w.x[id]
            p_array[(i*2),ind] = w.y[id]
        else
            break
        end
    end

    nothing
end

function make_woi_discrete(woi,num_points,spacing)

    d_points = zeros(Float32,num_points,2,length(woi))

    for i=1:length(woi)
        for j=1:num_points
            id=culm_dist(woi[i].x,woi[i].y,spacing*(j-1))
            if id != 1
                d_points[j,1,i] = woi[i].x[id]
                d_points[j,2,i] = woi[i].y[id]
            end
        end
    end

    d_points
end

#=
Go through all loaded frames and discretize the whisker of interest
=#

function make_discrete_woi(wt,woi,tracked,spacing)

    for i=1:length(woi)

        if tracked[i]
            #make_discrete(wt.w_p,i,woi[i],spacing)
        end
    end

    nothing
end

function make_discrete_all_whiskers(han::Tracker_Handles,spacing=15.0)
    woi=get_woi_array(han)
    make_discrete_all_whiskers(woi,han.wt.pad_pos,spacing)
end

function make_discrete_all_whiskers(woi,pad_pos,spacing=15.0)

    #Make sure that whiskers are ordered with follicle at base
    WT_reorder_whisker(woi,pad_pos)

    #Find longest whisker
    (d_longest,dl_i)=longest_whisker(woi)

    num_points = round(Int,div(d_longest, spacing))

    #Divide into x points
    d_points=make_woi_discrete(woi,num_points,spacing)
end

function longest_whisker(woi)

    d_longest=0.0
    dl_i=1;
    for i=1:length(woi)
        d=0.0
        w=woi[i]
        for j=2:length(w.x)
            d += sqrt((w.x[j]-w.x[j-1])^2 + (w.y[j]-w.y[j-1])^2)
        end

        if d > d_longest
            d_longest = d
            dl_i = i
        end
    end
    (d_longest, dl_i)
end

function draw_discrete(han::Tracker_Handles)

#=
    circ_rad=5.0

    ctx=Gtk.getgc(han.c)
    set_source_rgb(ctx,0,1,0)
    num_points = div(size(han.wt.w_p,1),2)

    for i=1:num_points
        arc(ctx, han.wt.w_p[i*2-1,han.frame],han.wt.w_p[i*2,han.frame], circ_rad, 0, 2*pi);
        stroke(ctx);
    end
=#
    nothing
end


text:
module GenCurveSegmentation

using Random, Distributions
using Gen, GenParticleFilters
using Plots, StringDistances

include("utils.jl")
include("data.jl")
include("analysis.jl")
include("render.jl")
include("model.jl")
include("inference.jl")

export render_trace, render_trace!, render_obs, render_obs!, render_traces, render_cb!
export stroke_rmse, stroke_edit_dist, log_ml
export parse_strokes, load_strokes, load_dataset
export curve_model, particle_filter

end


text:
module NMEA

export NMEAData, parse_msg!, GGA,
       RMC, GSA, GSV, SVData,
       GBS, VTG, GLL, ZDA,
       DTM, parse

@static if VERSION < v"0.7.0-DEV.2005"
    occursin = ismatch
end

"""
    parse(line::AbstractString)

Parses an NMEA sentence, returning a corresponding type.
"""
function parse(line::AbstractString)

    message = split(line, '*')[1]
    items = split(message, ',')

    system = get_system(items[1])

    if (occursin(r"DTM$", items[1]))
        return parse_DTM(items, system)
    elseif (occursin(r"GBS$", items[1]))
        return parse_GBS(items, system)
    elseif (occursin(r"GGA$", items[1]))
        return parse_GGA(items, system)
    elseif (occursin(r"GLL$", items[1]))
        return parse_GLL(items, system)
    elseif (occursin(r"GSA$", items[1]))
        return parse_GSA(items, system)
    elseif (occursin(r"GSV$", items[1]))
        return parse_GSV(items, system)
    elseif (occursin(r"RMC$", items[1]))
        return parse_RMC(items, system)
    elseif (occursin(r"VTG$", items[1]))
        return parse_VTG(items, system)
    elseif (occursin(r"ZDA$", items[1]))
        return parse_ZDA(items, system)
    end

    throw(ArgumentError("NMEA string not supported"))

end

#----------
# type for GGA message - Global Positioning System Fix Data
#----------
mutable struct GGA
    system # GPS, GLONASS, GALILEO, or Combined
    time # in seconds
    latitude # decimal degrees
    longitude # decimal degrees
    fix_quality
    num_sats
    HDOP
    altitude # MSL in meters
    geoidal_seperation # meters
    age_of_differential # seconds since last SC104
    diff_reference_id # differential reference station id
    valid

    function GGA(sys::AbstractString)
        system              = sys
        time                = 0.0
        latitude            = 0.0
        longitude           = 0.0
        fix_quality         = "UNKNOWN"
        num_sats            = 0
        HDOP                = 0.0
        altitude            = 0.0
        geoidal_seperation  = 0.0
        age_of_differential = 0.0
        diff_reference_id   = 0
        valid               = false
        new(system, time, latitude,
            longitude, fix_quality, num_sats,
            HDOP, altitude, geoidal_seperation,
            age_of_differential, diff_reference_id,
            valid)
    end # constructor GGA

end # type GGA

#----------
# GSA message type - GNSS DOP and Active Satellites
#----------
mutable struct GSA
    system
    mode
    current_mode
    sat_ids
    PDOP
    HDOP
    VDOP
    valid

    function GSA(sys::AbstractString)
        system       = sys
        mode         = 'M'
        current_mode = 0
        sat_ids      = []
        PDOP         = 0.0
        HDOP         = 0.0
        VDOP         = 0.0
        valid        = false
        new(system, mode, current_mode,
            sat_ids, PDOP, HDOP,
            VDOP, valid)
    end # constructor GSA
end # type GSA

#----------
# ZDA message type - Time and Date
#----------
mutable struct ZDA
    system
    time
    day
    month
    year
    zone_hrs
    zone_mins
    valid

    function ZDA(sys::AbstractString)
        system    = sys
        time      = 0.0
        day       = 0
        month     = 0
        year      = 0
        zone_hrs  = 0
        zone_mins = 0
        valid     = false
        new(system, time, day,
            month, year, zone_hrs,
            zone_mins, valid)
    end # constructor ZDA

end # type ZDA

#----------
# GBS message type - RAIM GNSS Satellite Fault Detection
#----------
mutable struct GBS
    system
    time
    lat_error
    long_error
    alt_error
    failed_PRN
    prob_of_missed
    excluded_meas_err
    standard_deviation
    valid

    function GBS(sys::AbstractString)
        system             = sys
        time               = 0.0
        lat_error          = 0.0
        long_error         = 0.0
        alt_error          = 0.0
        failed_PRN         = 0
        prob_of_missed     = 0.0
        excluded_meas_err  = 0.0
        standard_deviation = 0.0
        valid              = false
        new(system, time, lat_error,
            long_error, alt_error, failed_PRN,
            prob_of_missed, excluded_meas_err, standard_deviation,
            valid)
    end # constructor GBS
end # type GBS

#----------
# GLL message type - Geographic Position –
# Latitude/Longitude
#----------
mutable struct GLL
    system
    latitude
    longitude
    time
    status
    mode
    valid

    function GLL(sys::AbstractString)
        system    = sys
        latitude  = 0.0
        longitude = 0.0
        time      = 0.0
        status    = false
        mode      = 'N'
        valid     = false
        new(system, latitude, longitude,
            time, status, mode,
            valid)
    end # constructor GLL
end # type GLL

#----------
# type to store SV data fields in GSV
#----------
mutable struct SVData
    PRN
    elevation
    azimuth
    SNR

    function SVData()
        PRN       = 0
        elevation = 0
        azimuth   = 0
        SNR       = 0
        new(PRN, elevation, azimuth,
            SNR)
    end # constructor SVData
end # type SVData

#-----------
# type for GSV messages - GNSS Satellites In View
#-----------
mutable struct GSV
    system
    msg_total
    msg_num
    sat_total
    SV_data
    valid

    function GSV(sys::AbstractString)
        system    = sys
        msg_total = 0
        msg_num   = 0
        sat_total = 0
        SV_data   = []
        valid     = false
        new(system, msg_total, msg_num,
            sat_total, SV_data, valid)
    end # constructor GSV
end # type GSV

#----------
# RMC message type - Recommended Minimum Specific GNSS Data
#----------
mutable struct RMC
    system
    time
    status
    latitude
    longitude
    sog
    cog
    date
    magvar
    mode
    valid

    function RMC(sys::AbstractString)
        system    = sys
        time      = 0.0
        status    = false
        latitude  = 0.0
        longitude = 0.0
        sog       = 0.0
        cog       = 0.0
        date      = ""
        magvar    = 0.0
        mode      = 'N'
        valid     = false
        new(system, time, status,
            latitude, longitude, sog,
            cog, date, magvar,
            mode, valid)
    end # constructor RMC
end # type RMC

#----------
# VTG message type - Course over Ground & Ground Speed
#----------
mutable struct VTG
    CoG_true
    CoG_mag
    SoG_knots
    SoG_kmhr
    mode
    valid

    function VTG(sys::AbstractString)
        CoG_true  = 0.0
        CoG_mag   = 0.0
        SoG_knots = 0.0
        SoG_kmhr  = 0.0
        mode      = 'N'
        valid     = false
        new(CoG_true, CoG_mag, SoG_knots,
            SoG_kmhr, mode, valid)
    end # constructor VTG

end # type VTG

#----------
# DTM message type - Datum
#----------
mutable struct DTM
    system
    local_datum_code
    local_datum_subcode
    lat_offset
    long_offset
    alt_offset
    ref_datum
    valid

    function DTM(sys::AbstractString)
        system              = sys
        local_datum_code    = ""
        local_datum_subcode = ""
        lat_offset          = 0.0
        long_offset         = 0.0
        alt_offset          = 0.0
        ref_datum           = ""
        valid               = false

        new(system, local_datum_code, local_datum_subcode,
            lat_offset, long_offset, alt_offset,
            ref_datum, valid)
    end # constructor DTM
end # type DTM

#----------
# module handler
#----------
mutable struct NMEAData
    last_GGA::GGA
    last_RMC::RMC
    last_GSA::GSA
    last_GSV::GSV
    last_GBS::GBS
    last_VTG::VTG
    last_GLL::GLL
    last_ZDA::ZDA
    last_DTM::DTM

    function NMEAData()
        last_GGA = GGA("UNKNOWN")
        last_RMC = RMC("UNKNOWN")
        last_GSA = GSA("UNKNOWN")
        last_GSV = GSV("UNKNOWN")
        last_GBS = GBS("UNKNOWN")
        last_VTG = VTG("UNKNOWN")
        last_GLL = GLL("UNKNOWN")
        last_ZDA = ZDA("UNKNOWN")
        last_DTM = DTM("UNKNOWN")
        new(last_GGA, last_RMC, last_GSA,
            last_GSV, last_GBS, last_VTG,
            last_GLL, last_ZDA, last_DTM)
    end # constructor NMEAData
end # type NMEAData

#----------
# open serial port and start reading NMEAData messages
#----------
function parse_msg!(s::NMEAData, line::AbstractString)
    message = split(line, '*')[1]
    items = split(message, ',')

    # get system name
    system = get_system(items[1])

    mtype = ""
    if (occursin(r"DTM$", items[1]))
        s.last_DTM = parse_DTM(items, system)
        mtype = "DTM"

    elseif (occursin(r"GBS$", items[1]))
        s.last_GBS = parse_GBS(items, system)
        mtype = "GBS"

    elseif (occursin(r"GGA$", items[1]))
        s.last_GGA = parse_GGA(items, system)
        mtype = "GGA"

    elseif (occursin(r"GLL$", items[1]))
        s.last_GLL = parse_GLL(items, system)
        mtype = "GLL"

    elseif (occursin(r"GNS$", items[1]))
        mtype = "GNS"

    elseif (occursin(r"GSA$", items[1]))
        s.last_GSA = parse_GSA(items, system)
        mtype = "GSA"

    elseif (occursin(r"GSV$", items[1]))
        s.last_GSV = parse_GSV(items, system)
        mtype = "GSV"

    elseif (occursin(r"RMC$", items[1]))
        s.last_RMC = parse_RMC(items, system)
        mtype = "RMC"

    elseif (occursin(r"VTG$", items[1]))
        s.last_VTG = parse_VTG(items, system)
        mtype = "VTG"

    elseif (occursin(r"ZDA$", items[1]))
        s.last_ZDA = parse_ZDA(items, system)
        mtype = "ZDA"
    else
        mtype = "PROPRIETARY"
    end
    mtype
end # function parse_msg!

#----------
# determines system from message type string
#----------
function get_system(mtype::SubString)
    system = ""

    # GPS
    if (occursin(r"^\$GP", mtype))
        system = "GPS"

    # GLONASS
    elseif (occursin(r"^\$GL", mtype))
        system = "GLONASS"

    # GALILEO
    elseif (occursin(r"^\$GA", mtype))
        system = "GALILEO"

    # Combined
    elseif (occursin(r"^\$GN", mtype))
        system = "COMBINED"

    # Proprietary (non-NMEA standard) message
    else
        system = "UNKNOWN"
    end

    system
end # function get_system

#----------
# parses GGA messages and returns populated GGA type
#----------
function parse_GGA(items::Array{T}, system::AbstractString) where T <: SubString
    GGA_data = GGA(system)
    GGA_data.time = _hms_to_secs(items[2])
    GGA_data.latitude = _dms_to_dd(items[3], items[4])
    GGA_data.longitude = _dms_to_dd(items[5], items[6])

    fix_flag = tryparse(Int, items[7])
    if (fix_flag == 0)
        GGA_data.fix_quality = "INVALID"
    elseif (fix_flag == 1)
        GGA_data.fix_quality = "GPS (SPS)"
    elseif (fix_flag == 2)
        GGA_data.fix_quality = "DGPS"
    elseif (fix_flag == 3)
        GGA_data.fix_quality = "PPS"
    elseif (fix_flag == 4)
        GGA_data.fix_quality = "REAL TIME KINEMATIC"
    elseif (fix_flag == 5)
        GGA_data.fix_quality = "FLOAT RTK"
    elseif (fix_flag == 6)
        GGA_data.fix_quality = "DEAD RECKONING"
    elseif (fix_flag == 7)
        GGA_data.fix_quality = "MANUAL INPUT"
    elseif (fix_flag == 8)
        GGA_data.fix_quality = "SIMULATION"
    else
        GGA_data.fix_quality = "UNKNOWN"
    end

    GGA_data.num_sats            = tryparse(Int, items[8])
    GGA_data.HDOP                = tryparse(Float64, items[9])
    GGA_data.altitude            = tryparse(Float64, items[10])
    GGA_data.geoidal_seperation  = tryparse(Float64, items[12])
    GGA_data.age_of_differential = tryparse(Float64, items[14])
    GGA_data.diff_reference_id   = tryparse(Int, items[15])
    GGA_data.valid               = true
    GGA_data
end # function parse_GGA

#----------
# parse GSA messages
#----------
function parse_GSA(items::Array{T}, system::AbstractString)  where T <: SubString
    GSA_data = GSA(system)
    GSA_data.mode = items[2][1]
    GSA_data.current_mode = tryparse(Int, items[3])

    for i = 4:length(items) - 3
        if (items[i] == "")
            break
        end
        push!(GSA_data.sat_ids, tryparse(Int, items[i]))
    end

    GSA_data.PDOP  = tryparse(Float64, items[end - 2])
    GSA_data.HDOP  = tryparse(Float64, items[end - 1])
    GSA_data.VDOP  = tryparse(Float64, items[end])
    GSA_data.valid = true
    GSA_data
end # function parse_GSA

#----------
# parse ZDA message
#----------
function parse_ZDA(items::Array{T}, system::AbstractString) where T <: SubString
    ZDA_data = ZDA(system)
    ZDA_data.time      = _hms_to_secs(items[2])
    ZDA_data.day       = tryparse(Int, items[3])
    ZDA_data.month     = tryparse(Int, items[4])
    ZDA_data.year      = tryparse(Int, items[5])
    ZDA_data.zone_hrs  = tryparse(Int, items[6])
    ZDA_data.zone_mins = tryparse(Int, items[7])
    ZDA_data.valid     = true
    ZDA_data
end # function parse_ZDA

#----------
# parse GBS messages
#----------
function parse_GBS(items::Array{T}, system::AbstractString) where T <: SubString
    GBS_data                    = GBS(system)
    GBS_data.time               = _hms_to_secs(items[2])
    GBS_data.lat_error          = tryparse(Float64, items[3])
    GBS_data.long_error         = tryparse(Float64, items[4])
    GBS_data.alt_error          = tryparse(Float64, items[5])
    GBS_data.failed_PRN         = tryparse(Int, items[6])
    GBS_data.prob_of_missed     = tryparse(Float64, items[7])
    GBS_data.excluded_meas_err  = tryparse(Float64, items[8])
    GBS_data.standard_deviation = tryparse(Float64, items[9])
    GBS_data.valid              = true
    GBS_data
end # function parse_GBS

#----------
# parse GLL message
#----------
function parse_GLL(items::Array{T}, system::AbstractString) where T <: SubString
    GLL_data           = GLL(system)
    GLL_data.latitude  = _dms_to_dd(items[2], items[3])
    GLL_data.longitude = _dms_to_dd(items[4], items[5])
    GLL_data.time      = _hms_to_secs(items[6])

    if (items[7] == "A")
        GLL_data.status = true
    else
        GLL_data.status = false
    end

    if (items[8] != "")
        GLL_data.mode = items[8][1]
    end

    GLL_data.valid = true
    GLL_data
end # function parse_GLL

#----------
# parse GSV messages
#----------
function parse_GSV(items::Array{T}, system::AbstractString) where T <: SubString
    GSV_data           = GSV(system)
    GSV_data.msg_total = tryparse(Int, items[2])
    GSV_data.msg_num   = tryparse(Int, items[3])
    GSV_data.sat_total = tryparse(Int, items[4])

    i = 5
    while i < length(items)
        svd           = SVData()
        svd.PRN       = tryparse(Int, items[i])
        svd.elevation = tryparse(Int, items[i + 1])
        svd.azimuth   = tryparse(Int, items[i + 2])
        svd.SNR       = tryparse(Int, items[i + 3])
        push!(GSV_data.SV_data, svd)
        i += 4
    end

    GSV_data.valid = true
    GSV_data
end # function parse_GSV

#----------
# parse RMC messages
#----------
function parse_RMC(items::Array{T}, system::AbstractString) where T <: SubString
    RMC_data = RMC(system)
    RMC_data.time = _hms_to_secs(items[2])

    if (items[3] == "A")
        RMC_data.status = true
    else
        RMC_data.status = false
    end

    RMC_data.latitude  = _dms_to_dd(items[4], items[5])
    RMC_data.longitude = _dms_to_dd(items[6], items[7])
    RMC_data.sog       = tryparse(Float64, items[8])
    RMC_data.cog       = tryparse(Float64, items[9])
    RMC_data.date      = string(items[10][3:4], '/', items[10][1:2], '/', items[10][5:6])

    if (items[12] == "W" || items[12] == "S")
        RMC_data.magvar = tryparse(Float64, items[11]) * -1
    else
        RMC_data.magvar = tryparse(Float64, items[11])
    end
    RMC_data.mode = items[13][1]
    RMC_data.valid = true
    RMC_data
end # function parse_RMC

#----------
# parses VTG messages
#----------
function parse_VTG(items::Array{T}, system::AbstractString) where T <: SubString
    VTG_data = VTG(system)
    VTG_data.CoG_true  = tryparse(Float64, items[2])
    VTG_data.CoG_mag   = tryparse(Float64, items[4])
    VTG_data.SoG_knots = tryparse(Float64, items[6])
    VTG_data.SoG_kmhr  = tryparse(Float64, items[8])
    VTG_data.mode      = items[10][1]
    VTG_data.valid     = true
    VTG_data
end # function parse_VTG

#----------
# parse DTM messages
#----------
function parse_DTM(items::Array{T}, system::AbstractString) where T <: SubString
    DTM_data = DTM(system)
    DTM_data.local_datum_code = items[2]
    DTM_data.local_datum_subcode = items[3]
    lat_offset = tryparse(Float64, items[4])
    if (items[5] == "S")
        DTM_data.lat_offset = lat_offset * -1
    else
        DTM_data.lat_offset = lat_offset
    end

    long_offset = tryparse(Float64, items[6])
    if (items[7] == "W")
        DTM_data.long_offset = long_offset * -1
    else
        DTM_data.long_offset = long_offset
    end

    DTM_data.alt_offset = tryparse(Float64, items[8])
    DTM_data.ref_datum  = items[9]
    DTM_data.valid      = true
    DTM_data
end # function parse_DTM

#----------
# convert degrees minutes seconds to decimal degrees
#----------
function _dms_to_dd(dms::SubString, hemi::SubString)
    if (dms[1:1] == "0")
        dms = dms[2:end]
    end

    degrees = Base.parse(Float64, dms[1:2])
    minutes = Base.parse(Float64, dms[3:end])
    dec_degrees = degrees + (minutes / 60)

    if (hemi == "S" || hemi == "W")
        dec_degrees *= -1
    end

    dec_degrees
end # function _dms_to_dd

#----------
# hhmmss.s-s to time of day in seconds
#----------
function _hms_to_secs(hms::SubString)
    hours   = Base.parse(Float64, hms[1:2])
    minutes = Base.parse(Float64, hms[3:4])
    seconds = Base.parse(Float64, hms[5:end])
    (hours * 3600) + (minutes * 60) + seconds
end # function _hms_to_secs

end # module NMEA


text:
using DABenchmarks

ls_scaling = load_results("ls_scaling_1.json", Val{:scaling}())
ls_scaling.results["2"] = load_results("ls_scaling_2.json", Val{:scaling}()).results["2"]
ls_scaling.results["4"] = load_results("ls_scaling_4.json", Val{:scaling}()).results["4"]
ls_scaling.results["8"] = load_results("ls_scaling_8.json", Val{:scaling}()).results["8"]
ls_scaling.results["16"] = load_results("ls_scaling_16.json", Val{:scaling}()).results["16"]
save_results!(ls_scaling, "ls_scaling.json")

max_stars_repo_name: martinbiel/mpc-reproducibility

max_issues_repo_name: martinbiel/mpc-reproducibility

max_forks_repo_name: martinbiel/mpc-reproducibility


text:
function mydeleteat!(A,a)
    for i in a:length(A)-1
        A[i] = A[i+1]
    end
    A[length(A)] = Nothing
end

function myinsert!(A,a,c)
    b = A[end]
    for i in length(A)-1:a
        A[i+1] = A[i]
    end
    A[a] = c
    A=vcat(A,b)
    return A
end


text:
include("GeometricCenter.jl")
include("MinDistance.jl")
include("PrincipalAxes.jl")
include(joinpath("RotationAngle","all.jl"))


text:
module KaTeX

const assetsdir = joinpath(@__DIR__, "..", "assets")
const assets = ["auto-render.min.js", "katex.min.css", "katex.min.js"]
const fontsdir = joinpath(assetsdir, "fonts")

using WebIO: Scope, onimport, onjs, node
using JSExpr: @js
using AssetRegistry: register
using Observables: AbstractObservable, Observable

const katex_min_css = joinpath(KaTeX.assetsdir, "katex.min.css")
const katex_min_js = joinpath(KaTeX.assetsdir, "katex.min.js")

"""
`latex(txt)`

Render `txt` in LaTeX using KaTeX. Backslashes need to be escaped:
`latex("\\\\sum_{i=1}^{\\\\infty} e^i")`
"""
function latex(txt)
    (txt isa AbstractObservable) || (txt = Observable(txt))
    register(assetsdir)
    w = Scope(imports=[
        katex_min_js,
        katex_min_css
    ])

    w["value"] = txt

    onimport(w, @js function (k)
        this.k = k
        this.container = this.dom.childNodes[0]
        k.render($(txt[]), this.container)
    end)

    onjs(w["value"], @js (txt) -> this.k.render(txt, this.container))

    w.dom = node(:div)
    w
end

end # module