text:
export BrickletGPSV2Coordinates
struct BrickletGPSV2Coordinates
    latitude::Integer
    ns::Char
    longitude::Integer
    ew::Char
end

export BrickletGPSV2Status
struct BrickletGPSV2Status
    has_fix::Bool
    satellites_view::Integer
end

export BrickletGPSV2Altitude
struct BrickletGPSV2Altitude
    altitude::Integer
    geoidal_separation::Integer
end

export BrickletGPSV2Motion
struct BrickletGPSV2Motion
    course::Integer
    speed::Integer
end

export BrickletGPSV2DateTime
struct BrickletGPSV2DateTime
    date::Integer
    time::Integer
end

export BrickletGPSV2SatelliteSystemStatusLowLevel
struct BrickletGPSV2SatelliteSystemStatusLowLevel
    satellite_numbers_length::Integer
    satellite_numbers_data::Vector{Integer}
    fix::Integer
    pdop::Integer
    hdop::Integer
    vdop::Integer
end

export BrickletGPSV2SatelliteStatus
struct BrickletGPSV2SatelliteStatus
    elevation::Integer
    azimuth::Integer
    snr::Integer
end

export BrickletGPSV2SPITFPErrorCount
struct BrickletGPSV2SPITFPErrorCount
    error_count_ack_checksum::Integer
    error_count_message_checksum::Integer
    error_count_frame::Integer
    error_count_overflow::Integer
end

export BrickletGPSV2Identity
struct BrickletGPSV2Identity
    uid::String
    connected_uid::String
    position::Char
    hardware_version::Vector{Integer}
    firmware_version::Vector{Integer}
    device_identifier::Integer
end

export BrickletGPSV2SatelliteSystemStatus
struct BrickletGPSV2SatelliteSystemStatus
    satellite_numbers::Vector{Integer}
    fix::Integer
    pdop::Integer
    hdop::Integer
    vdop::Integer
end

export BrickletGPSV2
"""
Determine position, velocity and altitude using GPS
"""
mutable struct BrickletGPSV2 <: TinkerforgeDevice
    ipcon::IPConnection
    deviceInternal::PyObject

    """
    Creates an object with the unique device ID *uid* and adds it to
    the IP Connection *ipcon*.
    """
    function BrickletGPSV2(uid::String, ipcon::IPConnection)
        package = pyimport("tinkerforge.bricklet_gps_v2")
        deviceInternal = package.BrickletGPSV2(uid, ipcon.ipconInternal)

        return new(ipcon, deviceInternal)
    end
end

export get_coordinates
"""
    $(SIGNATURES)

Returns the GPS coordinates. Latitude and longitude are given in the
``DD.dddddd°`` format, the value 57123468 means 57.123468°.
The parameter ``ns`` and ``ew`` are the cardinal directions for
latitude and longitude. Possible values for ``ns`` and ``ew`` are 'N', 'S', 'E'
and 'W' (north, south, east and west).

This data is only valid if there is currently a fix as indicated by
:func:`Get Status`.
"""
function get_coordinates(device::BrickletGPSV2)
    return device.deviceInternal.get_coordinates()
end

export get_status
"""
    $(SIGNATURES)

Returns if a fix is currently available as well as the, the number of
satellites that are in view.

There is also a :ref:`green LED <gps_v2_bricklet_fix_led>` on the Bricklet that
indicates the fix status.
"""
function get_status(device::BrickletGPSV2)
    return device.deviceInternal.get_status()
end

export get_altitude
"""
    $(SIGNATURES)

Returns the current altitude and corresponding geoidal separation.

This data is only valid if there is currently a fix as indicated by
:func:`Get Status`.
"""
function get_altitude(device::BrickletGPSV2)
    return device.deviceInternal.get_altitude()
end

export get_motion
"""
    $(SIGNATURES)

Returns the current course and speed. A course of 0° means the Bricklet is
traveling north bound and 90° means it is traveling east bound.

Please note that this only returns useful values if an actual movement
is present.

This data is only valid if there is currently a fix as indicated by
:func:`Get Status`.
"""
function get_motion(device::BrickletGPSV2)
    return device.deviceInternal.get_motion()
end

export get_date_time
"""
    $(SIGNATURES)

Returns the current date and time. The date is
given in the format ``ddmmyy`` and the time is given
in the format ``hhmmss.sss``. For example, 140713 means
14.07.13 as date and 195923568 means 19:59:23.568 as time.
"""
function get_date_time(device::BrickletGPSV2)
    return device.deviceInternal.get_date_time()
end

export restart
"""
    $(SIGNATURES)

Restarts the GPS Bricklet, the following restart types are available:

.. csv-table::
 :header: "Value", "Description"
 :widths: 10, 100

 "0", "Hot start (use all available data in the NV store)"
 "1", "Warm start (don't use ephemeris at restart)"
 "2", "Cold start (don't use time, position, almanacs and ephemeris at restart)"
 "3", "Factory reset (clear all system/user configurations at restart)"
"""
function restart(device::BrickletGPSV2, restart_type)
    device.deviceInternal.restart(restart_type)
end

export get_satellite_system_status_low_level
"""
    $(SIGNATURES)

Returns the

* satellite numbers list (up to 12 items)
* fix value,
* PDOP value,
* HDOP value and
* VDOP value

for a given satellite system. Currently GPS and GLONASS are supported, Galileo
is not yet supported.

The GPS and GLONASS satellites have unique numbers and the satellite list gives
the numbers of the satellites that are currently utilized. The number 0 is not
a valid satellite number and can be ignored in the list.
"""
function get_satellite_system_status_low_level(device::BrickletGPSV2, satellite_system)
    return device.deviceInternal.get_satellite_system_status_low_level(satellite_system)
end

export get_satellite_status
"""
    $(SIGNATURES)

Returns the current elevation, azimuth and SNR
for a given satellite and satellite system.

The satellite number here always goes from 1 to 32. For GLONASS it corresponds to
the satellites 65-96.

Galileo is not yet supported.
"""
function get_satellite_status(device::BrickletGPSV2, satellite_system, satellite_number)
    return device.deviceInternal.get_satellite_status(satellite_system, satellite_number)
end

export set_fix_led_config
"""
    $(SIGNATURES)

Sets the fix LED configuration. By default the LED shows if
the Bricklet got a GPS fix yet. If a fix is established the LED turns on.
If there is no fix then the LED is turned off.

You can also turn the LED permanently on/off, show a heartbeat or let it blink
in sync with the PPS (pulse per second) output of the GPS module.

If the Bricklet is in bootloader mode, the LED is off.
"""
function set_fix_led_config(device::BrickletGPSV2, config)
    device.deviceInternal.set_fix_led_config(config)
end

export get_fix_led_config
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Fix LED Config`
"""
function get_fix_led_config(device::BrickletGPSV2)
    return device.deviceInternal.get_fix_led_config()
end

export set_coordinates_callback_period
"""
    $(SIGNATURES)

Sets the period with which the :cb:`Coordinates` callback is triggered
periodically. A value of 0 turns the callback off.

The :cb:`Coordinates` callback is only triggered if the coordinates changed
since the last triggering.
"""
function set_coordinates_callback_period(device::BrickletGPSV2, period)
    device.deviceInternal.set_coordinates_callback_period(period)
end

export get_coordinates_callback_period
"""
    $(SIGNATURES)

Returns the period as set by :func:`Set Coordinates Callback Period`.
"""
function get_coordinates_callback_period(device::BrickletGPSV2)
    return device.deviceInternal.get_coordinates_callback_period()
end

export set_status_callback_period
"""
    $(SIGNATURES)

Sets the period with which the :cb:`Status` callback is triggered
periodically. A value of 0 turns the callback off.

The :cb:`Status` callback is only triggered if the status changed since the
last triggering.
"""
function set_status_callback_period(device::BrickletGPSV2, period)
    device.deviceInternal.set_status_callback_period(period)
end

export get_status_callback_period
"""
    $(SIGNATURES)

Returns the period as set by :func:`Set Status Callback Period`.
"""
function get_status_callback_period(device::BrickletGPSV2)
    return device.deviceInternal.get_status_callback_period()
end

export set_altitude_callback_period
"""
    $(SIGNATURES)

Sets the period with which the :cb:`Altitude` callback is triggered
periodically. A value of 0 turns the callback off.

The :cb:`Altitude` callback is only triggered if the altitude changed since the
last triggering.
"""
function set_altitude_callback_period(device::BrickletGPSV2, period)
    device.deviceInternal.set_altitude_callback_period(period)
end

export get_altitude_callback_period
"""
    $(SIGNATURES)

Returns the period as set by :func:`Set Altitude Callback Period`.
"""
function get_altitude_callback_period(device::BrickletGPSV2)
    return device.deviceInternal.get_altitude_callback_period()
end

export set_motion_callback_period
"""
    $(SIGNATURES)

Sets the period with which the :cb:`Motion` callback is triggered
periodically. A value of 0 turns the callback off.

The :cb:`Motion` callback is only triggered if the motion changed since the
last triggering.
"""
function set_motion_callback_period(device::BrickletGPSV2, period)
    device.deviceInternal.set_motion_callback_period(period)
end

export get_motion_callback_period
"""
    $(SIGNATURES)

Returns the period as set by :func:`Set Motion Callback Period`.
"""
function get_motion_callback_period(device::BrickletGPSV2)
    return device.deviceInternal.get_motion_callback_period()
end

export set_date_time_callback_period
"""
    $(SIGNATURES)

Sets the period with which the :cb:`Date Time` callback is triggered
periodically. A value of 0 turns the callback off.

The :cb:`Date Time` callback is only triggered if the date or time changed
since the last triggering.
"""
function set_date_time_callback_period(device::BrickletGPSV2, period)
    device.deviceInternal.set_date_time_callback_period(period)
end

export get_date_time_callback_period
"""
    $(SIGNATURES)

Returns the period as set by :func:`Set Date Time Callback Period`.
"""
function get_date_time_callback_period(device::BrickletGPSV2)
    return device.deviceInternal.get_date_time_callback_period()
end

export set_sbas_config
"""
    $(SIGNATURES)

If `SBAS <https://en.wikipedia.org/wiki/GNSS_augmentation#Satellite-based_augmentation_system>`__ is enabled,
the position accuracy increases (if SBAS satellites are in view),
but the update rate is limited to 5Hz. With SBAS disabled the update rate is increased to 10Hz.

.. versionadded:: 2.0.2\$nbsp;(Plugin)
"""
function set_sbas_config(device::BrickletGPSV2, sbas_config)
    device.deviceInternal.set_sbas_config(sbas_config)
end

export get_sbas_config
"""
    $(SIGNATURES)

Returns the SBAS configuration as set by :func:`Set SBAS Config`

.. versionadded:: 2.0.2\$nbsp;(Plugin)
"""
function get_sbas_config(device::BrickletGPSV2)
    return device.deviceInternal.get_sbas_config()
end

export get_spitfp_error_count
"""
    $(SIGNATURES)

Returns the error count for the communication between Brick and Bricklet.

The errors are divided into

* ACK checksum errors,
* message checksum errors,
* framing errors and
* overflow errors.

The errors counts are for errors that occur on the Bricklet side. All
Bricks have a similar function that returns the errors on the Brick side.
"""
function get_spitfp_error_count(device::BrickletGPSV2)
    return device.deviceInternal.get_spitfp_error_count()
end

export set_bootloader_mode
"""
    $(SIGNATURES)

Sets the bootloader mode and returns the status after the requested
mode change was instigated.

You can change from bootloader mode to firmware mode and vice versa. A change
from bootloader mode to firmware mode will only take place if the entry function,
device identifier and CRC are present and correct.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function set_bootloader_mode(device::BrickletGPSV2, mode)
    return device.deviceInternal.set_bootloader_mode(mode)
end

export get_bootloader_mode
"""
    $(SIGNATURES)

Returns the current bootloader mode, see :func:`Set Bootloader Mode`.
"""
function get_bootloader_mode(device::BrickletGPSV2)
    return device.deviceInternal.get_bootloader_mode()
end

export set_write_firmware_pointer
"""
    $(SIGNATURES)

Sets the firmware pointer for :func:`Write Firmware`. The pointer has
to be increased by chunks of size 64. The data is written to flash
every 4 chunks (which equals to one page of size 256).

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function set_write_firmware_pointer(device::BrickletGPSV2, pointer)
    device.deviceInternal.set_write_firmware_pointer(pointer)
end

export write_firmware
"""
    $(SIGNATURES)

Writes 64 Bytes of firmware at the position as written by
:func:`Set Write Firmware Pointer` before. The firmware is written
to flash every 4 chunks.

You can only write firmware in bootloader mode.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function write_firmware(device::BrickletGPSV2, data)
    return device.deviceInternal.write_firmware(data)
end

export set_status_led_config
"""
    $(SIGNATURES)

Sets the status LED configuration. By default the LED shows
communication traffic between Brick and Bricklet, it flickers once
for every 10 received data packets.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is will show heartbeat by default.
"""
function set_status_led_config(device::BrickletGPSV2, config)
    device.deviceInternal.set_status_led_config(config)
end

export get_status_led_config
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Status LED Config`
"""
function get_status_led_config(device::BrickletGPSV2)
    return device.deviceInternal.get_status_led_config()
end

export get_chip_temperature
"""
    $(SIGNATURES)

Returns the temperature as measured inside the microcontroller. The
value returned is not the ambient temperature!

The temperature is only proportional to the real temperature and it has bad
accuracy. Practically it is only useful as an indicator for
temperature changes.
"""
function get_chip_temperature(device::BrickletGPSV2)
    return device.deviceInternal.get_chip_temperature()
end

export reset
"""
    $(SIGNATURES)

Calling this function will reset the Bricklet. All configurations
will be lost.

After a reset you have to create new device objects,
calling functions on the existing ones will result in
undefined behavior!
"""
function reset(device::BrickletGPSV2)
    device.deviceInternal.reset()
end

export write_uid
"""
    $(SIGNATURES)

Writes a new UID into flash. If you want to set a new UID
you have to decode the Base58 encoded UID string into an
integer first.

We recommend that you use Brick Viewer to change the UID.
"""
function write_uid(device::BrickletGPSV2, uid)
    device.deviceInternal.write_uid(uid)
end

export read_uid
"""
    $(SIGNATURES)

Returns the current UID as an integer. Encode as
Base58 to get the usual string version.
"""
function read_uid(device::BrickletGPSV2)
    return device.deviceInternal.read_uid()
end

export get_identity
"""
    $(SIGNATURES)

Returns the UID, the UID where the Bricklet is connected to,
the position, the hardware and firmware version as well as the
device identifier.

The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
A Bricklet connected to an :ref:`Isolator Bricklet <isolator_bricklet>` is always at
position 'z'.

The device identifier numbers can be found :ref:`here <device_identifier>`.
|device_identifier_constant|
"""
function get_identity(device::BrickletGPSV2)
    return device.deviceInternal.get_identity()
end

export get_satellite_system_status
"""
Returns the

* satellite numbers list (up to 12 items)
* fix value,
* PDOP value,
* HDOP value and
* VDOP value

for a given satellite system. Currently GPS and GLONASS are supported, Galileo
is not yet supported.

The GPS and GLONASS satellites have unique numbers and the satellite list gives
the numbers of the satellites that are currently utilized. The number 0 is not
a valid satellite number and can be ignored in the list.
"""
function get_satellite_system_status(device::BrickletGPSV2, satellite_system)

        satellite_system = UInt8(satellite_system)

    ret = get_satellite_system_status_low_level(device, satellite_system)

        return GetSatelliteSystemStatus(ret.satellite_numbers_data[:ret.satellite_numbers_length], ret.fix, ret.pdop, ret.hdop, ret.vdop)
end

export register_callback
"""
Registers the given *function* with the given *callback_id*.
"""
function register_callback(device::BrickletGPSV2, callback_id, function_)
    if isnothing(function_)
        device.registered_callbacks.pop(callback_id, None)
    else
        device.registered_callbacks[callback_id] = function_
    end
end


text:
struct StaticUnitRange{R,T} <: AbstractUnitRange{T} end
Base.@pure StaticUnitRange(R::UnitRange{T}) where {T} = StaticUnitRange{R,T}()
@generated function Base.getindex(::StaticUnitRange{R}, i::Integer) where {R}
    quote
        $(Expr(:meta,:inline))
        @boundscheck ((i < $(first(R))) || (i > $(last(R)))) && ThrowBoundsError()
        i + $(first(R)-1)
    end
end
@generated Base.first(::StaticUnitRange{R}) where {R} = first(R)
@generated Base.last(::StaticUnitRange{R}) where {R} = last(R)
@generated Base.length(::StaticUnitRange{R}) where {R} = length(R)
@generated Base.size(::StaticUnitRange{R}) where {R} = size(R)

ext: jl


text:
@testset "Drawing boxes" begin
    # Testing that boxes are drawn as expected

    ### square model
    yolomod = YOLO.v3_tiny_COCO(w=416, h=416, silent=true)
    #Nonsquare low aspect ratio image
    img = fill(Gray(1), 200, 100)
    batch = emptybatch(yolomod)
    batch[:,:,:,1], padding = prepareImage(img, yolomod)
    res = collect([ padding[1] padding[2] 1.0-padding[3] 1.0-padding[4] 0.0 0.0;]') #note the transpose!
    imgboxes = drawBoxes(img, yolomod, padding, res)
    @test all(imgboxes[1,:] .== Gray(0))
    @test all(imgboxes[:,1] .== Gray(0))
    @test all(imgboxes[end,:] .== Gray(0))
    @test all(imgboxes[:,end] .== Gray(0))

    #Nonsquare high aspect ratio image
    img = fill(Gray(1), 100, 200)
    batch = emptybatch(yolomod)
    batch[:,:,:,1], padding = prepareImage(img, yolomod)
    res = collect([ padding[1] padding[2] 1.0-padding[3] 1.0-padding[4] 0.0 0.0;]') #note the transpose!
    imgboxes = drawBoxes(img, yolomod, padding, res)
    @test all(imgboxes[1,:] .== Gray(0))
    @test all(imgboxes[:,1] .== Gray(0))
    @test all(imgboxes[end,:] .== Gray(0))
    @test all(imgboxes[:,end] .== Gray(0))

    #Square image, square model
    img = fill(Gray(1), 100, 100)
    batch = emptybatch(yolomod)
    batch[:,:,:,1], padding = prepareImage(img, yolomod)
    res = collect([ padding[1] padding[2] 1.0-padding[3] 1.0-padding[4] 0.0 0.0;]') #note the transpose!
    imgboxes = drawBoxes(img, yolomod, padding, res)
    @test all(imgboxes[1,:] .== Gray(0))
    @test all(imgboxes[:,1] .== Gray(0))
    @test all(imgboxes[end,:] .== Gray(0))
    @test all(imgboxes[:,end] .== Gray(0))

    ### nonsquare low aspect ratio model
    yolomod = YOLO.v3_tiny_COCO(w=512, h=416, silent=true)
    #Square image
    img = fill(Gray(1), 100, 100)
    batch = emptybatch(yolomod)
    batch[:,:,:,1], padding = prepareImage(img, yolomod)
    res = collect([ padding[1] padding[2] 1.0-padding[3] 1.0-padding[4] 0.0 0.0;]') #note the transpose!
    imgboxes = drawBoxes(img, yolomod, padding, res)
    @test all(imgboxes[1,:] .== Gray(0))
    @test all(imgboxes[:,1] .== Gray(0))
    @test all(imgboxes[end,:] .== Gray(0))
    @test all(imgboxes[:,end] .== Gray(0))

    #nonsquare low aspect ratio image
    img = fill(Gray(1), 200, 100)
    batch = emptybatch(yolomod)
    batch[:,:,:,1], padding = prepareImage(img, yolomod)
    res = collect([ padding[1] padding[2] 1.0-padding[3] 1.0-padding[4] 0.0 0.0;]') #note the transpose!
    imgboxes = drawBoxes(img, yolomod, padding, res)
    @test all(imgboxes[1,:] .== Gray(0))
    @test all(imgboxes[:,1] .== Gray(0))
    @test all(imgboxes[end,:] .== Gray(0))
    @test all(imgboxes[:,end] .== Gray(0))

    ### nonsquare high aspect ratio model
    yolomod = YOLO.v3_tiny_COCO(w=416, h=512, silent=true)
    #Square image
    img = fill(Gray(1), 100, 100)
    batch = emptybatch(yolomod)
    batch[:,:,:,1], padding = prepareImage(img, yolomod)
    res = collect([ padding[1] padding[2] 1.0-padding[3] 1.0-padding[4] 0.0 0.0;]') #note the transpose!
    imgboxes = drawBoxes(img, yolomod, padding, res)
    @test all(imgboxes[1,:] .== Gray(0))
    @test all(imgboxes[:,1] .== Gray(0))
    @test all(imgboxes[end,:] .== Gray(0))
    @test all(imgboxes[:,end] .== Gray(0))

    #nonsquare low aspect ratio image
    img = fill(Gray(1), 100, 200)
    batch = emptybatch(yolomod)
    batch[:,:,:,1], padding = prepareImage(img, yolomod)
    res = collect([ padding[1] padding[2] 1.0-padding[3] 1.0-padding[4] 0.0 0.0;]') #note the transpose!
    imgboxes = drawBoxes(img, yolomod, padding, res)
    @test all(imgboxes[1,:] .== Gray(0))
    @test all(imgboxes[:,1] .== Gray(0))
    @test all(imgboxes[end,:] .== Gray(0))
    @test all(imgboxes[:,end] .== Gray(0))

    ## Non-transposed
    imgboxes = drawBoxes(collect(img'), yolomod, padding, res, transpose=false)
    @test all(imgboxes[1,:] .== Gray(0))
    @test all(imgboxes[:,1] .== Gray(0))
    @test all(imgboxes[end,:] .== Gray(0))
    @test all(imgboxes[:,end] .== Gray(0))

end


text:
module Blobs

using MacroTools

macro splice(iterator, body)
  @assert iterator.head == :call
  @assert iterator.args[1] == :in
  Expr(:..., :(($(esc(body)) for $(esc(iterator.args[2])) in $(esc(iterator.args[3])))))
end

include("blob.jl")
include("vector.jl")
include("bit_vector.jl")
include("string.jl")
include("layout.jl")

export Blob, BlobVector, BlobBitVector, BlobString, @v, @a

end


text:
@forwardfun compare
@forwardfun hdi
@forwardfun loo
@forwardfun loo_pit
@forwardfun r2_score
@forwardfun waic

for f in (:loo, :waic)
    @eval begin
        function convert_arguments(::typeof($(f)), data, args...; kwargs...)
            idata = convert_to_inference_data(data)
            return tuple(idata, args...), kwargs
        end
    end
end
function convert_arguments(::typeof(compare), data, args...; kwargs...)
    dict = Dict(k => try
        topandas(Val(:ELPDData), v)
    catch
        convert_to_inference_data(v)
    end for (k, v) in pairs(data))
    return tuple(dict, args...), kwargs
end

convert_result(::typeof(loo), result) = todataframes(result)
convert_result(::typeof(waic), result) = todataframes(result)
convert_result(::typeof(r2_score), result) = todataframes(result)
function convert_result(::typeof(compare), result)
    return todataframes(result; index_name=:name)
end

"""
    psislw(log_weights, reff=1.0) -> (lw_out, kss)

Pareto smoothed importance sampling (PSIS).

!!! note

    This function is deprecated and is just a thin wrapper around [`psis`](@ref).

# Arguments

  - `log_weights`: Array of size `(nobs, ndraws)`
  - `reff`: relative MCMC efficiency, `ess / n`

# Returns

  - `lw_out`: Smoothed log weights
  - `kss`: Pareto tail indices
"""
function psislw(logw, reff=1)
    @warn "`psislw(logw[, reff])` is deprecated, use `psis(logw[, reff])`" maxlog = 1
    result = psis(logw, reff)
    log_weights = result.log_weights
    d = ndims(log_weights)
    dims = d == 1 ? Colon() : ntuple(Base.Fix1(+, 1), d - 1)
    log_norm_exp = logsumexp(log_weights; dims)
    log_weights .-= log_norm_exp
    return log_weights, result.pareto_shape
end

@doc doc"""
    summarystats(
        data::InferenceData;
        group = :posterior,
        kwargs...,
    ) -> Union{Dataset,DataFrames.DataFrame}
    summarystats(data::Dataset; kwargs...) -> Union{Dataset,DataFrames.DataFrame}

Compute summary statistics on `data`.

# Arguments

- `data::Union{Dataset,InferenceData}`: The data on which to compute summary statistics. If
    `data` is an [`InferenceData`](@ref), only the dataset corresponding to `group` is used.

# Keywords

- `var_names::Vector{String}=nothing`: Names of variables to include in summary
- `include_circ::Bool=false`: Whether to include circular statistics
- `fmt::String="wide"`: Return format is either `DataFrames.DataFrame` ("wide", "long") or
    [`Dataset`](@ref) ("xarray").
- `round_to::Int=nothing`: Number of decimals used to round results. Use `nothing` to return
    raw numbers.
- `stat_funcs::Union{Dict{String,Function},Vector{Function}}=nothing`: A vector of functions
    or a dict of functions with function names as keys used to calculate statistics. By
    default, the mean, standard deviation, simulation standard error, and highest posterior
    density intervals are included.
    The functions will be given one argument, the samples for a variable as an array, The
    functions should operate on an array, returning a single number. For example,
    `Statistics.mean`, or `Statistics.var` would both work.
- `extend::Bool=true`: If `true`, use the statistics returned by `stat_funcs` in addition
    to, rather than in place of, the default statistics. This is only meaningful when
    `stat_funcs` is not `nothing`.
- `hdi_prob::Real=0.94`: HDI interval to compute. This is only meaningful when `stat_funcs`
    is `nothing`.
- `order::String="C"`: If `fmt` is "wide", use either "C" or "F" unpacking order.
- `skipna::Bool=false`: If `true`, ignores `NaN` values when computing the summary
    statistics. It does not affect the behaviour of the functions passed to `stat_funcs`.
- `coords::Dict{String,Vector}=Dict()`: Coordinates specification to be used if the `fmt`
    is `"xarray"`.
- `dims::Dict{String,Vector}=Dict()`: Dimensions specification for the variables to be used
    if the `fmt` is `"xarray"`.

# Returns

- `Union{Dataset,DataFrames.DataFrame}`: Return type dicated by `fmt` argument. Return value
    will contain summary statistics for each variable. Default statistics are:
    + `mean`
    + `sd`
    + `hdi_3%`
    + `hdi_97%`
    + `mcse_mean`
    + `mcse_sd`
    + `ess_bulk`
    + `ess_tail`
    + `r_hat` (only computed for traces with 2 or more chains)

# Examples

```@example summarystats
using ArviZ
idata = load_arviz_data("centered_eight")
summarystats(idata; var_names=["mu", "tau"])
```

Other statistics can be calculated by passing a list of functions or a dictionary with key,
function pairs:

```@example summarystats
using StatsBase, Statistics
function median_sd(x)
    med = median(x)
    sd = sqrt(mean((x .- med).^2))
    return sd
end

func_dict = Dict(
    "std" => x -> std(x; corrected = false),
    "median_std" => median_sd,
    "5%" => x -> percentile(x, 5),
    "median" => median,
    "95%" => x -> percentile(x, 95),
)

summarystats(idata; var_names = ["mu", "tau"], stat_funcs = func_dict, extend = false)
```
"""
function StatsBase.summarystats(data::InferenceData; group=:posterior, kwargs...)
    dataset = getproperty(data, Symbol(group))
    return summarystats(dataset; kwargs...)
end
function StatsBase.summarystats(data::Dataset; fmt=:wide, kwargs...)
    s = arviz.summary(data; fmt, kwargs...)
    s isa Dataset && return s
    index_name = Symbol(fmt) == :long ? :statistic : :variable
    return todataframes(s; index_name)
end

"""
    summary(
        data;
        group = :posterior,
        coords = nothing,
        dims = nothing,
        kwargs...,
    ) -> Union{Dataset,DataFrames.DataFrame}

Compute summary statistics on any object that can be passed to [`convert_to_dataset`](@ref).

# Keywords

  - `coords::Dict{String,Vector}=nothing`: Map from named dimension to named indices.
  - `dims::Dict{String,Vector{String}}=nothing`: Map from variable name to names of its
    dimensions.
  - `kwargs`: Keyword arguments passed to [`summarystats`](@ref).
"""
function summary(data; group=:posterior, coords=nothing, dims=nothing, kwargs...)
    dataset = convert_to_dataset(data; group, coords, dims)
    return summarystats(dataset; kwargs...)
end


text:
# Copyright(c) Rafael Dias
# MIT Licensed

include("analise-estruturas.jl")

# Ordem deve ser horária
# coordenadas = [
#     PropriedadesSecoes.Coordenada(53f0, 0f0)
#     PropriedadesSecoes.Coordenada(53f0, 43f0)
#     PropriedadesSecoes.Coordenada(0f0, 43f0)
#     PropriedadesSecoes.Coordenada(0f0, 60f0)
#     PropriedadesSecoes.Coordenada(70f0, 60f0)
#     PropriedadesSecoes.Coordenada(70f0, 0f0)
# ]

coordenadas = [
    PropriedadesSecoes.Coordenada(0f0, 0f0)
    PropriedadesSecoes.Coordenada(0f0, 2f0)
    PropriedadesSecoes.Coordenada(5f0, 2f0)
    PropriedadesSecoes.Coordenada(5f0, 12f0)
    PropriedadesSecoes.Coordenada(0f0, 12f0)
    PropriedadesSecoes.Coordenada(0f0, 14f0)
    PropriedadesSecoes.Coordenada(12f0, 14f0)
    PropriedadesSecoes.Coordenada(12f0, 12f0)
    PropriedadesSecoes.Coordenada(7f0, 12f0)
    PropriedadesSecoes.Coordenada(7f0, 2f0)
    PropriedadesSecoes.Coordenada(12f0, 2f0)
    PropriedadesSecoes.Coordenada(12f0, 0f0)
]

@show PropriedadesSecoes.areaPoligono(coordenadas)

@show PropriedadesSecoes.centroGravidadePoligonoX(coordenadas)

@show PropriedadesSecoes.centroGravidadePoligonoY(coordenadas)

@show PropriedadesSecoes.perimetroPoligono(coordenadas)

@show PropriedadesSecoes.comprimentoEntrePontos(coordenadas)

max_stars_repo_name: rsd-consultoria/scripts-engenharia

max_issues_repo_name: rsd-consultoria/scripts-engenharia

max_forks_repo_name: rsd-consultoria/scripts-engenharia


text:
using MakieLayout
using Makie
using KernelDensity

function kdepoly!(la::LAxis, vec, reverse=false; kwargs...)
    kderesult = kde(vec; npoints=32)

    x = kderesult.x
    y = kderesult.density

    if reverse
        poly!(la, Point2.(y, x); kwargs...)
    else
        poly!(la, Point2.(x, y); kwargs...)
    end
end

begin
    scene = Scene(resolution = (1000, 1000));
    screen = display(scene)
    campixel!(scene);

    la1 = LAxis(scene)
    la2 = LAxis(scene)
    la3 = LAxis(scene)
    la4 = LAxis(scene)
    la5 = LAxis(scene)

    linkxaxes!(la3, la4)
    linkyaxes!(la3, la5)

    fakeaudiox = LinRange(0f0, 1000f0, 100_000)
    fakeaudioy = (rand(Float32, 100_000) .- 0.5f0) .+ 2 .* sin.(fakeaudiox .* 10)
    lines!(la1, fakeaudiox, fakeaudioy, show_axis=false)
    la1.attributes.title[] = "A fake audio signal"
    la1.attributes.ypanlock[] = true
    la1.attributes.yzoomlock[] = true

    linkeddata = randn(200, 2) .* 15 .+ 50
    green = RGBAf0(0.05, 0.8, 0.3, 0.6)
    scatter!(la3, linkeddata, markersize=3, color=green, show_axis=false)
    kdepoly!(la4, linkeddata[:, 1], false, color=green, linewidth=2, show_axis=false)
    kdepoly!(la5, linkeddata[:, 2], true, color=green, linewidth=2, show_axis=false)

    linkeddata2 = randn(200, 2) .* 20 .+ 70
    red = RGBAf0(0.9, 0.1, 0.05, 0.6)
    scatter!(la3, linkeddata2, markersize=3, color=red, show_axis=false)
    kdepoly!(la4, linkeddata2[:, 1], false, color=red, linewidth=2, show_axis=false)
    kdepoly!(la5, linkeddata2[:, 2], true, color=red, linewidth=2, show_axis=false)

    maingl = GridLayout(scene, 2, 1, alignmode=Outside(40)) #makie error in the tutorial #scene rendering  function

    sledg = maingl[2, 1] = LSlider(scene, range = LinRange(0.0, 150.0, 200))

    gl = maingl[1, 1] = GridLayout(
        2, 2;
        rowsizes = [Aspect(1, 1.0), Auto()], #Comment:Aspect Ratio is not a Golden Ratio
        colsizes = [Relative(0.5), Auto()],
        addedrowgaps = Fixed(20),
        addedcolgaps = Fixed(20),
        alignmode = Outside(0))

    on(slalign.value) do v
        with_updates_suspended(maingl) do
            gl.addedrowgaps = MakieLayout.GapSize[Fixed(v)]
            gl.addedcolgaps = MakieLayout.GapSize[Fixed(v)]
        end
    end

    gl_slider = gl[1, 2] = GridLayout(
        3, 1;
        rowsizes = [Auto(), Auto(), Auto()],
        colsizes = [Relative(1)],
        addedrowgaps = [Fixed(15), Fixed(15)])

    gl_colorbar = gl_slider[1, 1] = GridLayout(1, 2; colsizes=[Auto(), Relative(0.1)])

    gl_colorbar[1, 1] = la2
    # gl_colorbar[1, 2] = LColorbar(scene)

    sl1 = gl_slider[2, 1] = LSlider(scene, range = 1:0.01:10)
    sl2 = gl_slider[3, 1] = LSlider(scene, range = 0.1:0.01:1)

    xrange = LinRange(0, 2pi, 500)
    lines!(
        la2,
        xrange ./ 2pi .* 100,
        lift((x, y)->sin.(xrange .* x) .* 40 .* y .+ 50, sl1.value, sl2.value),
        color=:blue, linewidth=2, show_axis=false)

    gl[2, :] = la1

    gl2 = gl[1, 1] = GridLayout(
        2, 2,
        rowsizes = [Auto(), Relative(0.8)],
        colsizes = [Aspect(2, 1.0), Auto()],
        addedrowgaps = [Fixed(10)],
        addedcolgaps = [Fixed(10)])

    gl2[2, 1] = la3
    la3.titlevisible[] = false

    gl2[1, 1] = la4
    la4.xlabelvisible[] = false
    la4.xticklabelsvisible[] = false
    la4.xticksvisible[] = false
    la4.titlevisible[] = false
    la4.ypanlock[] = true
    la4.yzoomlock[] = true

    gl2[2, 2] = la5
    la5.ylabelvisible[] = false
    la5.yticklabelsvisible[] = false
    la5.yticksvisible[] = false
    la5.titlevisible[] = false
    la5.xpanlock[] = true
    la5.xzoomlock[] = true
end

max_stars_repo_name: adamwillisMastery/DeepLearner

max_issues_repo_name: adamwillisMastery/DeepLearner

max_forks_repo_name: adamwillisXanax/DeepLearner


text:
@reexport using RoME
@reexport using IncrementalInference
@reexport using KernelDensityEstimate
@reexport using Distributions

export
  GenericInSituSystem,  # insitu components
  makeGenericInSituSys,
  InSituSystem,
  makeInSituSys,
  triggerPose,
  poseTrigAndAdd!,
  processTreeTrackersUpdates!,
  advOdoByRules,
  SLAMWrapper,

  # servers
  tcpStringSLAMServer,
  tcpStringBRTrackingServer,

  # user functions
  identitypose6fg,
  projectrbe,
  hasval,

  # Robot Utils
  getRangeKDEMax2D,

  # sas-slam
  CBFFilterConfig,
  CZTFilter,
  prepCZTFilter,
  getCBFFilter2Dsize,
  constructCBFFilter2D!,
  CBF2D_DelaySum!,
  MatchedFilter,
  SASBearing2D,
  PackedSASBearing2D,
  compare,
  SASDebug,
  reset!,
  prepMF,
  loadConfigFile,
  prepareSAS2DFactor,
  wrapRad,
  phaseShiftSingle!,
  liebf!,
  SASDebug


text:
using GLM, DataFrames

function sdt_glm(hit::Int, fa::Int; miss::Int, cr::Int)

    # Initialize empty vectors
    response = zeros(hit+fa+miss+cr)
    signal = zeros(hit+fa+miss+cr)

    # Add ones where needed
    response[1:hit] = repeat([1], hit)
    signal[1:hit] = repeat([1], hit)

    response[hit+1:hit+fa] = repeat([1], fa)

    signal[hit+fa+1:hit+fa+miss] = repeat([1], miss)

    # Transform to dataframe
    data = DataFrame(signal=signal, response=response)

    # Fit GLM
    model = glm(@formula(response ~ signal), data, Bernoulli(), ProbitLink())
    coefs = GLM.coef(model)

    # Extract coefs
    indices_glm = Dict("dprime_glm" => coefs[2],
                       "Xc_glm" => -1*coefs[1])
    return indices_glm
end


text:
"""
    point_source(medium::Acoustic, source_position, amplitude=1)::Source

Create 2D [`Acoustic`](@ref) point [`Source`](@ref) (zeroth Hankel function of first type)
"""
function point_source(medium::Acoustic{T,2}, source_position::AbstractVector, amplitude::Union{T,Complex{T},Function} = one(T))::Source{T,Acoustic{T,2}} where T <: AbstractFloat

    # Convert to SVector for efficiency and consistency
    source_position = SVector{2,T}(source_position)

    if typeof(amplitude) <: Number
        amp(ω) = amplitude
    else
        amp = amplitude
    end
    source_field(x,ω) = (amp(ω)*im)/4 * hankelh1(0,ω/medium.c * norm(x-source_position))

    function source_coef(order,centre,ω)
        k = ω/medium.c
        r, θ = cartesian_to_radial_coordinates(centre - source_position)

        # using Graf's addition theorem
        return (amp(ω)*im)/4 * [hankelh1(-n,k*r) * exp(-im*n*θ) for n = -order:order]
    end

    return Source{T,Acoustic{T,2}}(medium, source_field, source_coef)
end

function point_source(medium::Acoustic{T,3}, source_position, amplitude::Union{T,Complex{T},Function} = one(T))::Source{T,Acoustic{T,3}} where T <: AbstractFloat

    # Convert to SVector for efficiency and consistency
    source_position = SVector{3,T}(source_position)

    if typeof(amplitude) <: Number
        amp(ω) = amplitude
    else
        amp = amplitude
    end

    source_field(x,ω) = amp(ω) / (T(4π) * norm(x-source_position)) * exp(im * ω/medium.c * norm(x-source_position))

    @error "not yet implemented"
    # function source_coef(order,centre,ω)
    #     # plane-wave expansion for complex vectors
    #     k = ω/medium.c
    #     r, θ, φ  = cartesian_to_radial_coordinates(centre - source_position)
    #     Ys = spherical_harmonics(order, θ, φ)
    #     lm_to_n = lm_to_spherical_harmonic_index
    #
    #     return T(4pi) * source_field(centre,ω) .*
    #     [
    #         Complex{T}(im)^l * (-one(T))^m * Ys[lm_to_n(l,-m)]
    #     for l = 0:order for m = -l:l]
    # end
    #
    # function source_coef(order,centre,ω)
    #     k = ω/medium.c
    #     r, θ = cartesian_to_radial_coordinates(centre - source_position)
    #
    #     # using Graf's addition theorem
    #     return (amp(ω)*im)/4 * [hankelh1(-n,k*r) * exp(-im*n*θ) for n = -order:order]
    # end

    return Source{T,Acoustic{T,3}}(medium, source_field, source_coef)
end

function plane_source(medium::Acoustic{T,Dim}; position::AbstractArray{T} = SVector(zeros(T,Dim)...),
        direction = SVector(one(T), zeros(T,Dim-1)...),
        amplitude::Union{T,Complex{T},Function} = one(T))::Source{T,Acoustic{T,Dim}} where {T, Dim}

    plane_source(medium, position, direction, amplitude)
end

"""
    plane_source(medium::Acoustic, source_position, source_direction=[1,0], amplitude=1)::Source

Create an [`Acoustic`](@ref) planar wave [`Source`](@ref)
"""
function plane_source(medium::Acoustic{T,2}, position::AbstractArray{T}, direction::AbstractArray{T} = SVector(one(T),zero(T)), amplitude::Union{T,Complex{T}} = one(T))::Source{T,Acoustic{T,2}} where {T}

    # Convert to SVector for efficiency and consistency
    position = SVector(position...)
    direction = SVector((direction ./ norm(direction))...) # unit direction

    # This pseudo-constructor is rarely called, so do some checks and conversions
    if iszero(norm(direction))
        throw(DomainError("Source direction must not have zero magnitude."))
    end

    if typeof(amplitude) <: Number
        amp(ω) = amplitude
    else
        amp = amplitude
    end

    source_field(x,ω) = amp(ω)*exp(im*ω/medium.c*dot(x-position, direction))

    function source_coef(order,centre,ω)
        # Jacobi-Anger expansion
        θ = atan(direction[2],direction[1])
        source_field(centre,ω) * [exp(im * n *(T(pi)/2 -  θ)) for n = -order:order]
    end

    return Source{T,Acoustic{T,2}}(medium, source_field, source_coef)
end

function plane_source(medium::Acoustic{T,3}, position::AbstractArray{T}, direction::AbstractArray{T} = SVector(zero(T),zero(T),one(T)), amplitude::Union{T,Complex{T}} = one(T)) where {T}

    # Convert to SVector for efficiency and consistency
    position = SVector(position...)
    direction = SVector( (direction ./ norm(direction))...) # unit direction

    # This pseudo-constructor is rarely called, so do some checks and conversions
    if iszero(norm(direction))
        throw(DomainError("Source direction must not have zero magnitude."))
    end

    if typeof(amplitude) <: Number
        amp(ω) = amplitude
    else
        amp = amplitude
    end

    source_field(x,ω) = amp(ω) * exp(im * ω/medium.c * dot(x-position, direction))

    function source_coef(order,centre,ω)
        # plane-wave expansion for complex vectors
        r, θ, φ  = cartesian_to_radial_coordinates(direction)
        Ys = spherical_harmonics(order, θ, φ)
        lm_to_n = lm_to_spherical_harmonic_index

        return T(4pi) * source_field(centre,ω) .*
        [
            Complex{T}(im)^l * (-one(T))^m * Ys[lm_to_n(l,-m)]
        for l = 0:order for m = -l:l]
    end

    return Source{T,Acoustic{T,3}}(medium, source_field, source_coef)
end

function regular_spherical_coefficients(psource::PlaneSource{T,Dim,1,Acoustic{T,Dim}}) where {T,Dim}
    source = plane_source(psource.medium;
        amplitude = psource.amplitude[1],
        position = psource.position,
        direction = psource.direction
    )

    source.coefficients
end


text:
using GLPlot, GLAbstraction

window = createdisplay()

##########################################################
# Image

# Using ImmutableArrays for colors (Vec4 --> Vector4{Float32):
a = Texture(Vec4[Vec4(i/512,j/512,0,1)for i=1:512, j=1:512])
# Without ImmutableArays, the color dimension is not known and you need to supply it
b = Texture(Float32[(i*j)/512^2 for i=1:512, j=1:512])
c = Texture("../docs/julia.png")

# default usage will just bring the texture on your screen with zooming and panning enabled:
glplot(c)
# these are the keyword arguments:
# ; camera = OrthographicCamera(window.inputs), normrange=Vec2(0,1), kernel=1f0, filternorm=1f0)
# The kernel should be a Matrix{Float32} or Matrix{Vec1}.
# Matrix{Vec2/3/4} is currently not supported, but quite easy to implement
# normrange normalizes the values from normrange[1] to normrange[2] to 0->1

renderloop(window)


text:
__precompile__()

module SymbolicIntegration

include("general.jl")
include("rational_functions.jl")
include("differential_fields.jl")
include("complex_fields.jl")
include("transcendental_functions.jl")
include("risch_diffeq.jl")
include("parametric_problems.jl")
include("coupled_differential_systems.jl")
include("algebraic_functions.jl")
include("frontend.jl")

end # module


text:
using Base.Test
using RobotOS
using Compat
RobotOS.debug(true)

#Generally, later tests rely on things defined in previous tests, so the order
#is important
include("rospy.jl")
include("time.jl")
include("typegeneration.jl")
include("pubsub.jl")
include("services.jl")


text:
push!(LOAD_PATH,"../src/")
using Documenter,OpenSAFT

makedocs(sitename = "OpenSAFT.jl",
format = Documenter.HTML(
    # Use clean URLs, unless built as a "local" build
    canonical = "https://juliadocs.github.io/OpenSAFT.jl/dev/",
    assets = ["assets/logo.ico"],
),
    authors = "Pierre J. Walker and Hon Wa Yew.",
    pages = [
        "Home" => "index.md",
        "User guide" => Any["System"=>"user_guide/system.md",
                            "Bulk properties"=>"user_guide/bulk_props.md",
                            "VLE properties"=>"user_guide/vle_props.md"],
        "To-do list" => "to-do_list.md",
        "Theory"=>Any["Methods"=>"theory/methods.md",
                      "Models"=>"theory/models.md"]])


text:
@cdef :PySlice_New PyPtr (PyPtr, PyPtr, PyPtr)

const PySlice_Type__ref = Ref(PyNULL)
PySlice_Type() = pyglobal(PySlice_Type__ref, :PySlice_Type)

PySlice_Check(o) = Py_TypeCheck(o, PySlice_Type())

PySlice_CheckExact(o) = Py_TypeCheckExact(o, PySlice_Type())

### ELLIPSIS

const Py_Ellipsis__ref = Ref(PyNULL)
Py_Ellipsis() = pyglobal(Py_Ellipsis__ref, :_Py_EllipsisObject)

PyEllipsis_Check(o) = Py_Is(o, Py_Ellipsis())

PyEllipsis_New() = (o = Py_Ellipsis(); Py_IncRef(o); o)


text:
using LinearAlgebra: I

# Unit 2D square
A = [[1 0];
     [0 1];
     [-1 0];
     [0 -1]]
b = [0, 0, -1, -1]
points, rays, bidrays = find_generators(A,b)
P = Polytope(points, rays, bidrays)
mins, maxs = min_max_projections(P)
t_mins, t_maxs = Rational{Int}[0//1, 0//1], Rational{Int}[1//1, 1//1]
@test t_mins == mins
@test t_maxs == maxs

# Single point
A = [[1 1];
     [-1 -1];
     [1 -1];
     [-1 1]]
b = [1, -1, 0, 0]
points, rays, bidrays = find_generators(A,b)
P = Polytope(points, rays, bidrays)
mins, maxs = min_max_projections(P)
t_mins, t_maxs = Rational{Int}[1//2, 1//2], Rational{Int}[1//2, 1//2]
@test t_mins == mins
@test t_maxs == maxs

# The Fathomless Toblerone
A = [[1 0 0];
     [0 1 0];
     [-1 -1 0];
     [0 0 -1]]
b = [0, 0, -2, 0]
points, rays, bidrays = find_generators(A,b)
P = Polytope(points, rays, bidrays)
mins, maxs = min_max_projections(P, [Array{Rational{Int}}(I, 3, 3) [1, 1, 0]])
t_mins, t_maxs = Rational{Int}[0//1, 0//1, -1//0, 0//1], Rational{Int}[2//1, 2//1, 0//1, 2//1]
@test t_mins == mins
@test t_maxs == maxs

# Half-space {(x,y,z): z ≥ 1}
A = [0 0 1]
b = [1]
points, rays, bidrays = find_generators(A,b)
P = Polytope(points, rays, bidrays)
mins, maxs = min_max_projections(P)
t_mins, t_maxs = Rational{Int64}[-1//0,-1//0,1//1],Rational{Int64}[1//0,1//0,1//0]
@test t_mins == mins
@test t_maxs == maxs


text:
# general Schur decomposition with reordering
# adataped from ./base/linalg/lapack.jl

include("exceptions.jl")

const criterium = 1 + 1e-6

function mycompare(alphar_::Ptr{T}, alphai_::Ptr{T}, beta_::Ptr{T})::Cint where {T}
    alphar = unsafe_load(alphar_)
    alphai = unsafe_load(alphai_)
    beta = unsafe_load(beta_)
    return convert(
        Cint,
        ((alphar * alphar + alphai * alphai) < criterium * beta * beta) ? 1 : 0,
    )
end

struct DgeesWs
    jobvs::Ref{UInt8}
    sdim::Ref{BlasInt}
    wr::Vector{Float64}
    wi::Vector{Float64}
    ldvs::Ref{BlasInt}
    vs::Matrix{Float64}
    work::Vector{Float64}
    lwork::Ref{BlasInt}
    bwork::Vector{Int64}
    eigen_values::Vector{Complex{Float64}}
    info::Ref{BlasInt}

    function DgeesWs(
        jobvs::Ref{UInt8},
        A::StridedMatrix{Float64},
        sdim::Ref{BlasInt},
        wr::Vector{Float64},
        wi::Vector{Float64},
        ldvs::Ref{BlasInt},
        vs::Matrix{Float64},
        work::Vector{Float64},
        lwork::Ref{BlasInt},
        bwork::Vector{Int64},
        eigen_values::Vector{Complex{Float64}},
        info::Ref{BlasInt},
    )
        n = Ref{BlasInt}(size(A, 1))
        RldA = Ref{BlasInt}(max(1, stride(A, 2)))
        Rsort = Ref{UInt8}('N')
        ccall(
            (@blasfunc(dgees_), liblapack),
            Nothing,
            (
                Ref{UInt8},
                Ref{UInt8},
                Ptr{Nothing},
                Ref{BlasInt},
                Ptr{Float64},
                Ref{BlasInt},
                Ptr{BlasInt},
                Ptr{Float64},
                Ptr{Float64},
                Ptr{Float64},
                Ref{BlasInt},
                Ptr{Float64},
                Ref{BlasInt},
                Ptr{BlasInt},
                Ptr{BlasInt},
            ),
            jobvs,
            'N',
            C_NULL,
            n,
            A,
            RldA,
            sdim,
            wr,
            wi,
            vs,
            ldvs,
            work,
            lwork,
            bwork,
            info,
        )
        chklapackerror(info[])
        lwork = Ref{BlasInt}(real(work[1]))
        work = Vector{Float64}(undef, lwork[])
        new(jobvs, sdim, wr, wi, ldvs, vs, work, lwork, bwork, eigen_values, info)
    end

end

function DgeesWs(A::StridedMatrix{Float64})
    chkstride1(A)
    n, = checksquare(A)
    jobvs = Ref{UInt8}('V')
    sdim = Ref{BlasInt}(0)
    wr = Vector{Float64}(undef, n)
    wi = Vector{Float64}(undef, n)
    ldvs = Ref{BlasInt}(jobvs[] == UInt32('V') ? n : 1)
    vs = Matrix{Float64}(undef, ldvs[], n)
    work = Vector{Float64}(undef, 1)
    lwork = Ref{BlasInt}(-1)
    bwork = Vector{Int64}(undef, n)
    eigen_values = Vector{Complex{Float64}}(undef, n)
    info = Ref{BlasInt}(0)
    DgeesWs(jobvs, A, sdim, wr, wi, ldvs, vs, work, lwork, bwork, eigen_values, info)

end

function DgeesWs(n::Int64)
    A = zeros(n, n)
    DgeesWs(A)
end

function dgees!(ws::DgeesWs, A::StridedMatrix{Float64})
    n = Ref{BlasInt}(size(A, 1))
    RldA = Ref{BlasInt}(max(1, stride(A, 2)))
    myfunc::Function = make_select_function(>=, 1.0)
    ccall(
        (@blasfunc(dgees_), liblapack),
        Cvoid,
        (
            Ref{UInt8},
            Ref{UInt8},
            Ptr{Cvoid},
            Ref{BlasInt},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{BlasInt},
            Ptr{Float64},
            Ptr{Float64},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{BlasInt},
            Ptr{BlasInt},
        ),
        ws.jobvs,
        'N',
        C_NULL,
        n,
        A,
        RldA,
        ws.sdim,
        ws.wr,
        ws.wi,
        ws.vs,
        ws.ldvs,
        ws.work,
        ws.lwork,
        ws.bwork,
        ws.info,
    )
    copyto!(ws.eigen_values, complex.(ws.wr, ws.wi))
    chklapackerror(ws.info[])
end

function make_select_function(op, crit)::Function
    mycompare = function (wr_, wi_)
        wr = unsafe_load(wr_)
        wi = unsafe_load(wi_)
        return convert(Cint, op(wr * wr + wi * wi, crit) ? 1 : 0)
    end
    return mycompare
end

function dgees!(ws::DgeesWs, A::StridedMatrix{Float64}, op, crit)
    n = Ref{BlasInt}(size(A, 1))
    RldA = Ref{BlasInt}(max(1, stride(A, 2)))
    myfunc::Function = make_select_function(op, crit)
    mycompare_c = @cfunction($myfunc, Cint, (Ptr{Cdouble}, Ptr{Cdouble}))
    ccall(
        (@blasfunc(dgees_), liblapack),
        Cvoid,
        (
            Ref{UInt8},
            Ref{UInt8},
            Ptr{Cvoid},
            Ref{BlasInt},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{BlasInt},
            Ptr{Float64},
            Ptr{Float64},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{BlasInt},
            Ptr{BlasInt},
        ),
        ws.jobvs,
        'S',
        mycompare_c,
        n,
        A,
        RldA,
        ws.sdim,
        ws.wr,
        ws.wi,
        ws.vs,
        ws.ldvs,
        ws.work,
        ws.lwork,
        ws.bwork,
        ws.info,
    )
    copyto!(ws.eigen_values, complex.(ws.wr, ws.wi))
    chklapackerror(ws.info[])
end

mutable struct DggesWs
    alphar::Vector{Float64}
    alphai::Vector{Float64}
    beta::Vector{Float64}
    lwork::BlasInt
    work::Vector{Float64}
    bwork::Vector{Int64}
    sdim::BlasInt

    function DggesWs(
        jobvsl::Ref{UInt8},
        jobvsr::Ref{UInt8},
        sort::Ref{UInt8},
        A::StridedMatrix{Float64},
        B::StridedMatrix{Float64},
    )
        chkstride1(A, B)
        n, m = checksquare(A, B)
        if n != m
            throw(DimensionMismatch("Dimensions of A, ($n,$n), and B, ($m,$m), must match"))
        end
        n = BlasInt(size(A, 1))
        alphar = Vector{Float64}(undef, n)
        alphai = Vector{Float64}(undef, n)
        beta = Vector{Float64}(undef, n)
        bwork = Vector{Int64}(undef, n)
        ldvsl = BlasInt(1)
        ldvsr = BlasInt(1)
        sdim = BlasInt(0)
        lwork = BlasInt(-1)
        work = Vector{Float64}(undef, 1)
        sdim = BlasInt(0)
        info = BlasInt(0)
        mycompare_g_c =
            @cfunction(mycompare, Cint, (Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}))
        ccall(
            (@blasfunc(dgges_), liblapack),
            Nothing,
            (
                Ref{UInt8},
                Ref{UInt8},
                Ref{UInt8},
                Ptr{Nothing},
                Ref{BlasInt},
                Ptr{Float64},
                Ref{BlasInt},
                Ptr{Float64},
                Ref{BlasInt},
                Ref{BlasInt},
                Ptr{Float64},
                Ptr{Float64},
                Ptr{Float64},
                Ptr{Float64},
                Ref{BlasInt},
                Ptr{Float64},
                Ref{BlasInt},
                Ptr{Float64},
                Ref{BlasInt},
                Ptr{Int64},
                Ref{BlasInt},
            ),
            jobvsl,
            jobvsr,
            sort,
            mycompare_g_c,
            n,
            A,
            max(1, stride(A, 2)),
            B,
            max(1, stride(B, 2)),
            sdim,
            alphar,
            alphai,
            beta,
            C_NULL,
            ldvsl,
            C_NULL,
            ldvsr,
            work,
            lwork,
            bwork,
            info,
        )
        chklapackerror(info)
        lwork = BlasInt(real(work[1]))
        work = Vector{Float64}(undef, lwork)
        new(alphar, alphai, beta, lwork, work, bwork, sdim)
    end
end

function DggesWs(A::StridedMatrix{Float64}, B::StridedMatrix{Float64})
    DggesWs(Ref{UInt8}('N'), Ref{UInt8}('N'), Ref{UInt8}('N'), A, B)
end

function dgges!(
    jobvsl::Char,
    jobvsr::Char,
    A::StridedMatrix{Float64},
    B::StridedMatrix{Float64},
    vsl::Matrix{Float64},
    vsr::Matrix{Float64},
    eigval::Array{ComplexF64,1},
    ws::DggesWs,
)
    n = size(A, 1)
    ldvsl = jobvsl == 'V' ? n : 1
    ldvsr = jobvsr == 'V' ? n : 1
    sort = 'S'
    sdim = Ref{BlasInt}(0)
    info = Ref{BlasInt}(0)
    mycompare_g_c = @cfunction(mycompare, Cint, (Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Cdouble}))
    ccall(
        (@blasfunc(dgges_), liblapack),
        Nothing,
        (
            Ref{UInt8},
            Ref{UInt8},
            Ref{UInt8},
            Ptr{Nothing},
            Ref{BlasInt},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{BlasInt},
            Ptr{Float64},
            Ptr{Float64},
            Ptr{Float64},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{Float64},
            Ref{BlasInt},
            Ptr{Int64},
            Ref{Int64},
        ),
        jobvsl,
        jobvsr,
        sort,
        mycompare_g_c,
        n,
        A,
        max(1, stride(A, 2)),
        B,
        max(1, stride(B, 2)),
        sdim,
        ws.alphar,
        ws.alphai,
        ws.beta,
        vsl,
        ldvsl,
        vsr,
        ldvsr,
        ws.work,
        ws.lwork,
        ws.bwork,
        info,
    )
    ws.sdim = sdim[]
    if info[] > 0
        throw(DggesException(info[]))
    end
    for i = 1:n
        eigval[i] = complex(ws.alphar[i], ws.alphai[i]) / ws.beta[i]
    end
end


text:
using Printf

"""
 Inputs
 - x: The vector of (observed) X variables
 - z: The current sample of Z variables
 - θ: The vector parameters in the form [q, σ²]
 - k: The index of the Z variable of interest
Outputs
 The acceptance ratio for the proposal to switch Z_j
"""
function acceptance_ratio(x, z, θ, j)
    # Extract density parameters
    q, σ² = θ
    σ = sqrt(σ²)
    n = length(x)
    𝒩 = OffsetArray([Normal(0, σ), Normal(1, σ)], 0:1)
    if j == 1
        new = (q*(z[j+1] ≠ z[j]) + (1-q)*(z[j+1] == z[j]))*pdf(𝒩[1-z[j]], x[j])
        old = (q*(z[j+1] == z[j]) + (1-q)*(z[j+1] ≠ z[j]))*pdf(𝒩[z[j]], x[j])
    elseif j == n
        new = (q*(z[j-1] ≠ z[j]) + (1-q)*(z[j-1] == z[j]))*pdf(𝒩[1-z[j]], x[j])
        old = (q*(z[j-1] == z[j]) + (1-q)*(z[j-1] ≠ z[j]))*pdf(𝒩[z[j]], x[j])
    else
        new = (q*(z[j-1] ≠ z[j]) + (1-q)*(z[j-1] == z[j]))*(q*(z[j+1] ≠ z[j]) + (1-q)*(z[j+1] == z[j]))*pdf(𝒩[1-z[j]], x[j])
        old = (q*(z[j-1] == z[j]) + (1-q)*(z[j-1] ≠ z[j]))*(q*(z[j+1] == z[j]) + (1-q)*(z[j+1] ≠ z[j]))*pdf(𝒩[z[j]], x[j])
    end
    new/old
end

"""
Performs one single Gibbs sampler iteration of Z
Inputs
 - x: The vector of (observed) X variables
 - z: The current sample of Z variables
 - θ: The vector parameters in the form [q, σ²]
 - j: The index of the Z variable of interest
 Outputs
 A Z sample where each index of Z is sampled by conditioning on all other
 variables
"""
function get_single_gibbs_sample!(x, z, θ)
    n = length(x)
    for j = 1:n
        if rand() < acceptance_ratio(x, z, θ, j)
            z[j] = 1 - z[j]
        end
    end
end

"""
Returns a sample of Z, drawn from a
Inputs
 - x: The vector of (observed) X variables
 - θ: The vector parameters in the form [q, σ²]
 Outputs
A Z sample where Z ~ P(Z|X = x)
"""
function gibbs_sampler(x, θ)
    n = length(x)
    z = rand(0:1, n)
    for i = 1:75
        get_single_gibbs_sample!(x, z, θ)
    end
    z
end

"""
Estimates the values of a,b,c (as defined in example) via Monte Carlo
Inputs
 - x: The vector of (observed) X variables
 - θ: The vector parameters in the form [q, σ²]
 Outputs
 A vector in the form [a,b,c] representing a MC estimate of a,b, and c
"""
function estimate_a_b_c(x, θ)
    n = length(x)

    # Number of MC samples
    num_samples = 100

    # Estimate sum
    total_a = 0
    total_b = 0
    total_c = 0

    for k = 1:num_samples
        z_samples = gibbs_sampler(x, θ)
        estimate_a = sum(z_samples[1:(n-1)] .== z_samples[2:n])
        estimate_b = sum(z_samples[1:(n-1)] .!= z_samples[2:n])
        estimate_c = sum((x - z_samples).^2)

        total_a += estimate_a
        total_b += estimate_b
        total_c += estimate_c
    end

    return [total_a, total_b, total_c]./num_samples
end

"""
Performs EM algorithm to estimate θ
 Inputs
 - x: The vector of (observed) X variables
 Outputs
 An estimate of θ = [q, σ²]
"""
function em_algorithm(x)
    # Initialize θ parameter [q, σ²]
    θ = [0.5, 1]

    num_iterations = 100

    for i = 1:num_iterations
        a, b, c = estimate_a_b_c(x, θ)
        q = a/(a+b)
        σ² = c/(a+b+1)
        θ = [q, σ²]
        print(stderr,'\r')
        printstyled(stderr, "k = $i, $θ", color=:green)
    end

    θ
end

max_stars_repo_name: data-gymnasia/julia-binder

max_issues_repo_name: data-gymnasia/julia-binder

max_forks_repo_name: data-gymnasia/julia-binder


text:
# this is just to test locally, since we don't want
# to impose Gadfly dependency

p = plot(x=[1])
Image0 = Image(12, 16, p)

c = Code("""
h = 1/2
F' = sin(x)
""")

l = document([
    DocumentClass("article", ["11pt", "a4paper"]),
    Title("Title"),
    Section("Section",[
        Figure("Figure",Image0),
    ]),
])

openpdf(l)


text:
using RedPitayaDAQServer
using PyPlot

#rp = RedPitaya("rp-f04972.local")
rp = RedPitaya("192.168.178.46")

dec = 64
modulus = 4800
base_frequency = 125000000
periods_per_step = 50
samples_per_period = div(modulus, dec)*periods_per_step
periods_per_frame = div(1000, periods_per_step) # about 0.5 s frame length
frame_period = dec*samples_per_period*periods_per_frame / base_frequency
slow_dac_periods_per_frame = periods_per_frame

decimation(rp, dec)
samplesPerPeriod(rp, samples_per_period)
periodsPerFrame(rp, periods_per_frame)

slowDACPeriodsPerFrame(rp, slow_dac_periods_per_frame)
numSlowDACChan(rp, 1)
lut = collect(range(0,1,length=slow_dac_periods_per_frame))
setSlowDACLUT(rp, lut)

modeDAC(rp, "STANDARD")
frequencyDAC(rp,1,1, base_frequency / modulus)

freq = frequencyDAC(rp,1,1)
println(" frequency = $(freq)")
signalTypeDAC(rp, 1 , "SINE")
amplitudeDAC(rp, 1, 1, 400)
phaseDAC(rp, 1, 1, 0.0 ) # Phase has to be given in between 0 and 1

ramWriterMode(rp, "TRIGGERED")
triggerMode(rp, "INTERNAL")
masterTrigger(rp, false)
startADC(rp)
masterTrigger(rp, true)

sleep(0.1)

uFirstPeriod = readData(rp, 0, 2)

currFr = enableSlowDAC(rp, true, 2, frame_period, 0.5)
uCurrentPeriod = readData(rp, currFr, 2)

sleep(0.1)
currFr = enableSlowDAC(rp, true, 2, frame_period, 0.5)
uCurrentPeriod2 = readData(rp, currFr, 2)

figure(1)
clf()
subplot(2,1,1)
plot(vec(uCurrentPeriod[:,2,:,:]))
plot(vec(uCurrentPeriod[:,1,:,:]))
plot(vec(uCurrentPeriod2[:,1,:,:]))
legend(("DF", "FF1", "FF2"))
subplot(2,1,2)
plot(vec(uFirstPeriod[:,2,:,:]))
plot(vec(uCurrentPeriod[:,2,:,:]))
legend(("DF1", "DF2"))

stopADC(rp)


text:
using BPFnative
import BPFnative: API, RT, Host
using Sockets
using Test
using UProbes

# Useful for debugging libbpf loader failures
if !isfile(joinpath(@__DIR__, "bpf-print.so"))
    try
        run(`gcc -shared -fPIC -o bpf-print.so bpf-print.c`)
    catch
        @warn "Failed to build bpf-print.so"
    end
end
using Libdl
try
    libptr = dlopen(joinpath(@__DIR__, "bpf-print.so"))
    fptr = dlsym(libptr, "jl_bpf_print")
    BPFnative.API.bpfprintfn(fptr)
catch
    @warn "Failed to load bpf-print.so, skipping"
end

using InteractiveUtils

@testset "codegen" begin
    map_types = (UInt8, UInt16, UInt32, UInt64,
                 Int8,  Int16,  Int32,  Int64)
    @testset "empty" begin
        function kernel(x)
            return 0
        end
        asm = String(bpffunction(kernel, Tuple{Int}; format=:asm, license="abc"))
        @test occursin(".section\tlicense,", asm)
        @test occursin("_license,@object", asm)
        @test occursin(".asciz\t\"abc\"", asm)
    end
    @testset "map helpers" begin
        function kernel(x)
            mymap = RT.RTMap(;name="mymap", maptype=API.BPF_MAP_TYPE_HASH, keytype=UInt32, valuetype=UInt32, maxentries=3)
            elem = mymap[1]
            if elem !== nothing
                mymap[1] = elem+1
                if something(mymap[1], 0) > 3
                    delete!(mymap, 1)
                end
            else
                mymap[1] = 0
            end
            return 0
        end
        asm = String(bpffunction(kernel, Tuple{Int}; format=:asm))
        @test occursin("mymap ll", asm)
        @test count("mymap,@object", asm) == 1
    end
    @testset "map indexing" begin
        for K in map_types, V in map_types
            @testset "map[$K] = $V" begin
                k = @eval begin
                    function kernel(x)
                        mymap = RT.RTMap(;name="mymap", maptype=API.BPF_MAP_TYPE_HASH, keytype=$K, valuetype=$V, maxentries=1)
                        oK, oV = $(one(K)), $(one(V))
                        mymap[oK] = oV
                        return 0
                    end
                end
                asm = String(bpffunction(kernel, Tuple{Int}; format=:asm))
                @test occursin("mymap ll", asm)
                @test count("mymap,@object", asm) == 1
            end
        end
    end
    @testset "buffers/strings" begin
        @testset "buffer: simple" begin
            function kernel(x)
                buf = RT.create_buffer(4)
                RT.trace_printk(buf)
            end
            asm = String(bpffunction(kernel, Tuple{Int}; format=:asm))
            @test !occursin("gpu_gc_pool_alloc", asm)
        end
        @testset "string: simple" begin
            function kernel(x)
                str = RT.@create_string("hello!")
                RT.trace_printk(str)
            end
            asm = String(bpffunction(kernel, Tuple{Int}; format=:asm))
            @test !occursin("gpu_gc_pool_alloc", asm)
        end
        @testset "divergent execution" begin
            function kernel(x)
                if x > 1
                    RT.trace_printk(RT.@create_string("Greater"))
                else
                    RT.trace_printk(RT.@create_string("Lesser"))
                end
            end
            asm = String(bpffunction(kernel, Tuple{Int}; format=:asm))
            # TODO: Test that allocas sit in top of first block
        end
    end
end
@testset "libbpf" begin
    function kernel(x)
        mymap = RT.RTMap(;name="mymap", maptype=API.BPF_MAP_TYPE_ARRAY, keytype=UInt32, valuetype=UInt32)
        elem = mymap[1]
        return 0
    end
    exe = bpffunction(kernel, Tuple{UInt32}; name="mykern", prog_section="mysection", license="MIT")
    obj = API.Object(exe)
    @test length(API.name(obj)) > 0
    @testset "maps" begin
        @test length(API.maps(obj)) == 1
        map = API.maps(obj)[1]
        @test API.name(map) == "mymap"
        @test API.fd(obj, "mymap") == -1
        @test API.fd(map) == -1
        def = API.definition(map)
        @test def.type == UInt32(API.BPF_MAP_TYPE_ARRAY)
        @test def.key_size == def.value_size == 4
        @test def.max_entries == 1
        @test def.map_flags == 0
        API.resize!(map, 2)
        @test API.definition(map).max_entries == 2
    end
    @testset "programs" begin
        @test length(API.programs(obj)) == 1
        prog = API.programs(obj)[1]
        @test API.title(prog) == "mysection"
        @test occursin("mykern", API.name(prog))
        @test API.type(prog) == API.BPF_PROG_TYPE_UNSPEC
        API.set_kprobe!(prog)
        @test API.type(prog) == API.BPF_PROG_TYPE_KPROBE
    end
end
@testset "sockets" begin
    srv = listen(4789)
    chan = Channel{Int}()
    function open_socks(srv, port)
        s_sock = @async accept(srv)
        c_sock = connect(port)
        s_sock = fetch(s_sock)
        s_sock, c_sock
    end
    @testset "attach" begin
        s_sock, c_sock = open_socks(srv, 4789)
        write(s_sock, 1)
        @test read(c_sock, Int) == 1
        dummy_filter(ctx) = 64
        bytecode = bpffunction(dummy_filter, Tuple{Ptr{Cvoid}}; btf=false, prog_section="socket_filter")
        obj = API.Object(bytecode)
        API.load(obj)
        filt = API.fd(first(API.programs(obj)))
        @test Host.setsockopt(c_sock, Host.SOL_SOCKET, Host.SO_ATTACH_BPF, filt) == 0
        @test Host.getsockopt(c_sock, Host.SOL_SOCKET, Host.SO_PROTOCOL, UInt64) == API.Network.IPPROTO_TCP
        write(s_sock, 1)
        @test read(c_sock, Int) == 1
        @test Host.setsockopt(c_sock, Host.SOL_SOCKET, Host.SO_DETACH_BPF, filt) == 0
        close(s_sock)
        close(c_sock)
    end
    @testset "packet counting" begin
        s_sock, c_sock = open_socks(srv, 4789)
        function count_filter(ctx)
            mymap = RT.RTMap(name="mymap", maptype=API.BPF_MAP_TYPE_ARRAY, keytype=Int32, valuetype=UInt8, maxentries=1)
            mymap[1] = something(mymap[1], 0) + 1
            255
        end
        bytecode = bpffunction(count_filter, Tuple{Ptr{Cvoid}}; btf=false, prog_section="socket_filter")
        obj = API.Object(bytecode)
        API.load(obj)
        filt = API.fd(first(API.programs(obj)))
        Host.setsockopt(c_sock, Host.SOL_SOCKET, Host.SO_ATTACH_BPF, filt)
        write(s_sock, 1)
        read(c_sock, UInt8)
        hmap = Host.hostmap(first(API.maps(obj)); K=Int32, V=UInt8)
        @test hmap[1] > 0
        close(s_sock)
        close(c_sock)
    end
    @testset "packet reading" begin
        s_sock, c_sock = open_socks(srv, 4789)
        function modify_filter(ctx)
            mymap = RT.RTMap(name="mymap", maptype=API.BPF_MAP_TYPE_ARRAY, keytype=Int32, valuetype=UInt8, maxentries=1)
            doff = RT.load_byte(ctx, API.@offsetof(API.Network.tcphdr, :doff))
            doff = (doff >> 4) * 4
            mymap[1] = RT.load_byte(ctx, doff)
            255
        end
        bytecode = bpffunction(modify_filter, Tuple{API.pointertype(API.sk_buff)}; btf=false, prog_section="socket_filter")
        obj = API.Object(bytecode)
        API.load(obj)
        filt = API.fd(first(API.programs(obj)))
        Host.setsockopt(c_sock, Host.SOL_SOCKET, Host.SO_ATTACH_BPF, filt)
        write(s_sock, 0x42)
        read(c_sock, UInt8)
        hmap = Host.hostmap(first(API.maps(obj)); K=Int32, V=UInt8)
        @test hmap[1] == 0x42
        close(s_sock)
        close(c_sock)
    end
    close(srv)
end
run_root_tests = parse(Bool, get(ENV, "BPFNATIVE_ROOT_TESTS", "0"))
if run_root_tests
    test_file, test_io = mktemp(;cleanup=true)
    @info "Running root-only tests"
    @testset "probes" begin
        @testset "kprobe" begin
            kp = KProbe("ksys_write") do regs
                return 0
            end
            API.load(kp)
            API.unload(kp)
            @testset "retprobe" begin
                kp = KProbe("ksys_write"; retprobe=true) do regs
                    return 0
                end
                API.load(kp)
                API.unload(kp)
            end
        end
        @test_skip "uprobe"
        #@testset "uprobe" begin
        #    up = UProbe(+, Tuple{Int,Int}) do regs
        #        return 0
        #    end
        #    API.load(up)
        #    API.unload(up)
        #    @testset "retprobe" begin
        #        up = UProbe(+, Tuple{Int,Int}; retprobe=true) do regs
        #            return 0
        #        end
        #        API.load(up)
        #        API.unload(up)
        #    end
        #end
        @testset "tracepoint" begin
            p = Tracepoint("clk", "clk_enable") do regs
                return 0
            end
            API.load(p)
            API.unload(p)
        end
        @testset "usdt" begin
            function f(arg)
                # FIXME: if @query(:julia, :test, typeof(arg))
                    @probe(:julia, :test, arg)
                #end
                arg
            end
            f(1)
            julia_path = Base.julia_cmd().exec[1]
            usdt = USDT(getpid(), julia_path, "julia:test") do ctx
                usdtmap = RT.RTMap(;name="usdtmap",
                                    maptype=API.BPF_MAP_TYPE_HASH,
                                    keytype=Int32,
                                    valuetype=Int32,
                                    maxentries=1)
                usdtmap[1] = 1 # TODO: Get 1st (Cint) argument
                0
            end
            API.load(usdt) do
                f(1)
                host_usdtmap = Host.hostmap(API.findmap(usdt.obj, "usdtmap"); K=Int32, V=Int32)
                @test host_usdtmap[1] == 1
                host_usdtmap[1] = 2
                @test host_usdtmap[1] == 2
                f(1)
                @test host_usdtmap[1] == 1
            end
        end
        # TODO: perf_event
        # TODO: xdp
    end
    @testset "bpf syscall" begin
        @testset "array" begin
            h = Host.HostMap(;map_type=API.BPF_MAP_TYPE_ARRAY, key_type=Int32, value_type=Int64, max_entries=1)
            @test h[1] == 0
            h[1] = 42
            @test h[1] == 42
            @test_throws Exception h[0]
            @test_throws Exception h[2]
        end
        @testset "hash" begin
            h = Host.HostMap(;map_type=API.BPF_MAP_TYPE_HASH, key_type=Int32, value_type=Int64, max_entries=1)
            @test !haskey(h, 1)
            h[1] = 42
            @test haskey(h, 1)
            @test h[1] == 42
            @test_throws Exception h[2] = 43
            @test_throws Exception h[2]
            delete!(h, 1)
            @test !haskey(h, 1)
            h[2] = 43
            @test h[2] == 43
        end
    end
    @testset "map interfacing" begin
        function kp_func(regs)
            mymap = RT.RTMap(;name="mymap", maptype=API.BPF_MAP_TYPE_ARRAY, keytype=UInt32, valuetype=UInt32)
            elem = mymap[1]
            if elem !== nothing
                mymap[1] = 42
            else
                mymap[1] = 1
            end
            return 0
        end
        kp = KProbe(kp_func, "ksys_write")
        API.load(kp) do
            map = first(API.maps(kp.obj))
            hmap = Host.hostmap(map; K=UInt32, V=UInt32)
            write(test_io, "1"); flush(test_io)
            @test hmap[1] == 42
        end
    end
    @testset "helpers" begin
        # XXX: The below helper kernels are marked as GPL for the purpose of
        # testing that the helper works as expected, however they are still
        # licensed according to the MIT license. If you actually use GPL-only
        # helpers in your kernels, make sure you adhere to the GPL license!
        @test_skip "probe_read"
        @testset "ktime_get_ns" begin
            kp = KProbe("ksys_write"; license="GPL") do x
                mymap = RT.RTMap(;name="mymap", maptype=API.BPF_MAP_TYPE_ARRAY, keytype=UInt32, valuetype=UInt64)
                mymap[1] = RT.ktime_get_ns()
                0
            end
            API.load(kp) do
                map = first(API.maps(kp.obj))
                hmap = Host.hostmap(map; K=UInt32, V=UInt32)
                write(test_io, "1"); flush(test_io)
                old = hmap[1]
                write(test_io, "1"); flush(test_io)
                @test hmap[1] > old
            end
        end
        @testset "trace_printk" begin
            kp = KProbe("ksys_write"; license="GPL") do x
                y = 1234
                z = RT.@create_string("1234")
                RT.trace_printk(RT.@create_string("%d==%s"), y, z)
                0
            end
            API.load(kp) do
                write(test_io, "1"); flush(test_io)
                run(`grep -q -m 1 '1234==1234' /sys/kernel/debug/tracing/trace_pipe`)
            end
        end
        @testset "get_prandom_u32" begin
            kp = KProbe("ksys_write"; license="GPL") do x
                mymap = RT.RTMap(;name="mymap", maptype=API.BPF_MAP_TYPE_ARRAY, keytype=UInt32, valuetype=UInt32)
                mymap[1] = RT.get_prandom_u32()
                0
            end
            API.load(kp) do
                map = first(API.maps(kp.obj))
                hmap = Host.hostmap(map; K=UInt32, V=UInt32)
                write(test_io, "1"); flush(test_io)
                old = hmap[1]
                write(test_io, "1"); flush(test_io)
                @test hmap[1] != old
            end
        end
        @testset "get_smp_processor_id" begin
            @eval const CPU_THREADS = Sys.CPU_THREADS # Sys.CPU_THREADS is not const
            kp = KProbe("ksys_write"; license="GPL") do x
                mymap = RT.RTMap(;name="mymap", maptype=API.BPF_MAP_TYPE_ARRAY, keytype=UInt32, valuetype=UInt32, maxentries=CPU_THREADS+1)
                mymap[RT.get_smp_processor_id()+1] = 1
                0
            end
            API.load(kp) do
                map = first(API.maps(kp.obj))
                hmap = Host.hostmap(map; K=UInt32, V=UInt32)
                for i in 1:100
                    write(test_io, "1"); flush(test_io)
                end
                was_set = false
                for idx in 1:Sys.CPU_THREADS
                    if hmap[idx] == 1
                        was_set = true
                    end
                end
                @test was_set
                @test !haskey(hmap, Sys.CPU_THREADS+1)
            end
        end
        @testset "skb_store_bytes and (l3/l4)_csum_replace" begin
            function kernel(ctx)
                eth_hdr = API.Network.@ETH_HLEN()
                ver = (RT.load_byte(ctx, eth_hdr) & 0xF0) >> 4
                ihl = (RT.load_byte(ctx, eth_hdr) & 0xF)
                if (ver != 4) || (ihl > 5)
                    return 0
                end
                ip_proto = RT.load_byte(ctx, eth_hdr + API.@offsetof(API.Network.iphdr, :protocol))
                if ip_proto != API.Network.IPPROTO_TCP
                    return 0
                end
                ip_hdr = eth_hdr + sizeof(API.Network.iphdr)
                doff = RT.load_byte(ctx, ip_hdr + API.@offsetof(API.Network.tcphdr, :doff))
                doff = (doff >> 4) * 4
                doff += ip_hdr
                oldbyte = RT.load_byte(ctx, doff)
                if oldbyte != 0x1
                    return 0
                end
                newbyte = 0x2
                ret = RT.skb_store_bytes(ctx, doff, newbyte, sizeof(newbyte), 0)
                if ret < 0
                    RT.trace_printk(RT.@create_string("Store failed: %d"), ret)
                    return 2
                end
                0
            end
            str = bpffunction(kernel, Tuple{API.pointertype(API.sk_buff)}; prog_section="classifier", license="GPL")
            path, io = mktemp(;cleanup=true)
            write(io, str); flush(io)
            run(`ip link add name jlbpf_test type veth peer name jlbpf_test2`)
            try
                run(`ip link set jlbpf_test up`)
                run(`ip netns add jlbpf_ns`)
                try
                    run(`ip link set jlbpf_test2 netns jlbpf_ns`)
                    run(`ip netns exec jlbpf_ns ip addr add 10.45.98.2/24 dev jlbpf_test2`)
                    run(`ip netns exec jlbpf_ns ip link set jlbpf_test2 up`)
                    run(`ip addr add 10.45.98.1/24 dev jlbpf_test`)
                    run(`ip netns exec jlbpf_ns ip route add default via 10.45.98.1`)
                    run(`ip netns exec jlbpf_ns tc qdisc add dev jlbpf_test2 clsact`)
                    run(`ip netns exec jlbpf_ns tc filter add dev jlbpf_test2 ingress bpf da obj $path`)
                    jl = run(`ip netns exec jlbpf_ns $(unsafe_string(Base.JLOptions().julia_bin)) -e 'using Sockets;l=listen(IPv4("10.45.98.2"),8765);s=accept(l);write(s,read(s,UInt8))'`; wait=false)
                    sleep(1)
                    try
                        sock = connect("10.45.98.2", 8765)
                        write(sock, 0x1)
                        @test read(sock, UInt8) == 0x2
                    catch err
                        kill(jl)
                        rethrow(err)
                    end
                finally
                    run(`ip netns del jlbpf_ns`)
                end
            finally
                run(`ip link del dev jlbpf_test`)
            end
        end
        @testset "get_current_pid_tgid" begin
            kp = KProbe("ksys_write") do x
                mymap = RT.RTMap(;name="mymap",maptype=API.BPF_MAP_TYPE_HASH,keytype=UInt32,valuetype=UInt32,maxentries=2)
                pid, tgid = RT.get_current_pid_tgid()
                mymap[tgid] = pid
                0
            end
            API.load(kp) do
                map = first(API.maps(kp.obj))
                hmap = Host.hostmap(map; K=UInt32, V=UInt32)
                write(test_io, "1"); flush(test_io)
                # FIXME: Why doesn't this work?
                #@test haskey(hmap, getpid())
                #@test hmap[getpid()] == getpid()
            end
        end
        iob = IOBuffer()
        run(pipeline(`id -u`; stdout=iob))
        euid = parse(Int, chomp(String(take!(iob))))
        @testset "get_current_uid_gid" begin
            kp = KProbe("ksys_write") do x
                mymap = RT.RTMap(;name="mymap",maptype=API.BPF_MAP_TYPE_HASH,keytype=UInt32,valuetype=UInt32,maxentries=2)
                uid, gid = RT.get_current_uid_gid()
                mymap[uid] = gid
                0
            end
            API.load(kp) do
                map = first(API.maps(kp.obj))
                hmap = Host.hostmap(map; K=UInt32, V=UInt32)
                write(test_io, "1"); flush(test_io)
                @test haskey(hmap, euid)
                @test hmap[euid] == euid # Not sure if a good idea, but eh
            end
        end
        # TODO: get_current_comm
        @testset "get_stackid" begin
            # from BCC's stackcount
            struct StackKey
                tgid::UInt32
                sid::Clong
            end
            kp = KProbe("ksys_write"; license="GPL") do x
                stacks = RT.RTMap(;name="stacks",maptype=API.BPF_MAP_TYPE_STACK_TRACE,keytype=UInt32,valuetype=NTuple{API.PERF_MAX_STACK_DEPTH,UInt64},maxentries=10000)
                counts = RT.RTMap(;name="counts",maptype=API.BPF_MAP_TYPE_HASH,keytype=StackKey,valuetype=UInt32,maxentries=10000)
                pid, tgid = RT.get_current_pid_tgid()
                sid = RT.get_stackid(x, stacks, 0)
                key = StackKey(tgid, sid)
                old_count = get(counts, key, 0)
                counts[key] = old_count + 1
                0
            end
            API.load(kp) do
                stacks = Host.hostmap(API.findmap(kp.obj, "stacks"); K=UInt32, V=NTuple{API.PERF_MAX_STACK_DEPTH,UInt64})
                counts = Host.hostmap(API.findmap(kp.obj, "counts"); K=StackKey, V=UInt32)
                write(test_io, "1"); flush(test_io)
                ks = collect(keys(counts))
                @test length(ks) > 0
                key = first(ks)
                # TODO: Should we be able to find a key with getpid() == key.tgid?
                @test haskey(counts, key)
                # TODO: This is potentially racy
                @test haskey(stacks, key.sid)
                @test occursin("ksys_write", Host.stack_to_string(stacks[key.sid]))
            end
        end
    end
end