text:
#MDDatasets: Dataset operations
#TODO: optimize operations so they run faster
#TODO: ensure length(v)>1?
#TODO: add xaty?
#-------------------------------------------------------------------------------

#==Data accessors
===============================================================================#

#Obtain a dataset of the x-values
#-------------------------------------------------------------------------------
xval(d::DataF1) = DataF1(d.x, copy(d.x)) #TODO: is copy necessary?  User should not modify

xmax(d::DataF1) = maximum(d.x)
xmin(d::DataF1) = minimum(d.x)

#Element-by-element difference of y-values:
#(shift x-values @ mean position)
#-------------------------------------------------------------------------------
function delta(d::DataF1; shiftx=true)
	x = shiftx ? meanadj(d.x) : d.x[1:end-1]
	return DataF1(x, delta(d.y))
end

#==X-value modifiers
===============================================================================#

#Shifts x-values of a dataset by +/-offset:
#-------------------------------------------------------------------------------
function xshift(d::DataF1, offset::Number)
	return DataF1(d.x.+offset, copy(d.y))
end

#Scales x-values of a dataset by fact:
#-------------------------------------------------------------------------------
function xscale(d::DataF1, fact::Number)
	return DataF1(d.x.*fact, copy(d.y))
end

#-------------------------------------------------------------------------------
function yvsx(y::DataF1, x::DataF1)
	_x = x+0*y
	_y = y+0*x
	@assert(_x.x==_y.x, "xvsy algorithm error: not generating unique x-vector.")
	return DataF1(_x.y, _y.y)
end

#==Differential/integral math
===============================================================================#

#-------------------------------------------------------------------------------
function deriv(d::DataF1; shiftx=true)
	x = shiftx ? meanadj(d.x) : d.x[1:end-1]
	return DataF1(x, delta(d.y)./delta(d.x))
end

#Indefinite integral:
#-------------------------------------------------------------------------------
function iinteg(d::DataF1)
	#meanadj ≜ (vi+(vi+1))/2
	area = meanadj(d.y).*delta(d.x)
	return DataF1(d.x, vcat(zero(eltype(d.y)), cumsum(area)))
end

#Definite integral:
#TODO: add start/stop?
#-------------------------------------------------------------------------------
function integ(d::DataF1)
	#meanadj ≜ (vi+(vi+1))/2
	area = meanadj(d.y).*delta(d.x)
	return sum(area)
end

#==Clip
===============================================================================#

#-------------------------------------------------------------------------------
function clip(d::DataF1{TX,TY}, rng::Limits1D{TX}) where {TX<:Number, TY<:Number}
	validate(d); #Expensive, but might avoid headaches
	ensurenotinverted(rng)
	if length(d) < 1; return d; end;

	xmin = clamp(d.x[1], rng)
	xmax = clamp(d.x[end], rng)
	dx = d.x
	x = Vector{TX}(undef, length(dx))

	id=1
	while dx[id]<xmin
		id+=1
	end
	#Here: dx[id]>=xmin
	i=1
	x[i] = xmin
	if dx[id]>xmin; i+=1; end
	istart = i
	dyoffset = id-i
	while dx[id]<xmax
		x[i] = dx[id]
		id+=1
		i+=1
	end
	if !(xmax==xmin) #not already @ max position
		x[i] = xmax
	end

	resize!(x, i)

	#Copy y-values:
	TYR = typeof(one(promote_type(TX,TY))/2) #TODO: is there better way?
	y = Vector{TYR}(undef, length(x))
	for i in istart:(length(x)-1)
		y[i] = d.y[dyoffset+i]
	end
	#TODO: don't use value().  Interpolate in place instead:
	y[1] = value(d, x=x[1])
	y[end] = value(d, x=x[end])

	return DataF1(x, y)
end
clip(d::DataF1{TX,TY}; xmin=nothing, xmax=nothing) where {TX<:Number, TY<:Number} =
	clip(d, Limits1D{TX}(xmin, xmax))
clip(d::DataF1{TX,TY}, rng::AbstractRange) where {TX<:Number, TY<:Number} =
	clip(d, Limits1D{TX}(rng))

#==Sampling algorithm
===============================================================================#

#-------------------------------------------------------------------------------
function sample(d::DataF1{TX,TY}, x::AbstractRange) where {TX<:Number, TY<:Number}
	validate(d); ensureincreasingx(x); #Expensive, but might avoid headaches
	#TODO: deal with empty d
	if length(x) < 1
		return DataF1(zeros(eltype(x),0), zeros(eltype(d.y),0))
	end
	n = length(x)
	y = Vector{TY}(undef, n)
	x = collect(x) #Need it in this form anyways
	dx = d.x #shortcut
	_dx = dx[1]; dx_ = dx[end]
	_x = x[1]; x_ = x[end]
	_xint = max(_dx, _x) #First intersecting point
	xint_ = min(dx_, x_) #Last intersecting point

	#Disjoint dataset:
	if _x > dx_ || _dx > x_
		return DataF1(collect(x), zeros(eltype(d.y),length(x)))
	end

	i = 1 #index into x/y arrays
	id = 1 #index into dx
	while x[i] < _xint
		y[i] = zero(TY)
		i += 1; #x[i] < _xint and set not disjoint: safe to increment i
	end
	p = pnext = Point2D(d, id)
	while x[i] < xint_ #Intersecting section of x
		while pnext.x <= x[i]
			id += 1 #x[i] < _xint: safe to increment id
			p = pnext; pnext = Point2D(d, id)
		end
		y[i] = interpolate(p, pnext, x=x[i])
		i+=1
	end
	#End of intersecting section (x[i]==xint_):
		while pnext.x < x[i]
			id += 1 #x[i] == xint_ && pnext.x < x[i]: safe to increment id
			p = pnext; pnext = Point2D(d, id)
		end
		y[i] = interpolate(p, pnext, x=x[i])
	while i < n #Get remaining points
		i += 1
		y[i] = zero(TY)
	end
	return DataF1(x,y)
end

#Last line


text:
#=
This is a thin slice of Resynthesizer.
To test type stability.
=#

# For "load" local  files
using FileIO

include("../src/neighbor.jl")
include("../src/image.jl")
include("../src/pointCompare.jl")

# load an image

img_path = "/home/bootch/git/resynthesizerJulia/test/data/tinylighthouse.png"
img = load(img_path)

println(typeof(img))

# Need a mask to create MaskedImage
# The mask selcts whole image
mask = trues(size(img))

maskedImage = MaskedImage(img, mask)

#=
Create a dummy neighbor
=#

# Use the same index for offset, wildPoint
point = CartesianIndex(1,1)
offset = point

neighbor = Neighbor(
                    offset,
                    maskedImage,    # target,
                    offset  # framed point in target
                )
println("Describing neighbor instance")
println(neighbor)
println(typeof(neighbor.offset))
# call compare
#=
@code_warntype comparePointsTargetWithCorpus(
    neighbor,
    maskedImage,
    # Use same dummy point
    point    # framed point
    )
=#

function test(x::Int64)
    for  i in x
        comparePointsTargetWithCorpus(
            neighbor,
            maskedImage,
            # Use same dummy point
            point    # framed point
            )
    end
end

# @code_warntype test()
@time test(10000)

ext: jl

max_stars_repo_name: bootchk/resynthesizerJulia

max_issues_repo_name: bootchk/resynthesizerJulia

max_forks_repo_name: bootchk/resynthesizerJulia


text:
include("scf_callbacks.jl")

function default_n_bands(model)
    min_n_bands = div(model.n_electrons, filled_occupation(model))
    n_extra = model.temperature == 0 ? 0 : max(4, ceil(Int, 0.2 * min_n_bands))
    min_n_bands + n_extra
end

"""
Obtain new density ρ by diagonalizing `ham`.
"""
function next_density(ham::Hamiltonian;
                      n_bands=default_n_bands(ham.basis.model),
                      ψ=nothing, n_ep_extra=3,
                      eigensolver=lobpcg_hyper,
                      occupation_function=compute_occupation, kwargs...)
    if ψ !== nothing
        @assert length(ψ) == length(ham.basis.kpoints)
        for ik in 1:length(ham.basis.kpoints)
            @assert size(ψ[ik], 2) == n_bands + n_ep_extra
        end
    end

    # Diagonalize
    eigres = diagonalize_all_kblocks(eigensolver, ham, n_bands + n_ep_extra; guess=ψ,
                                     n_conv_check=n_bands, kwargs...)
    eigres.converged || (@warn "Eigensolver not converged" iterations=eigres.iterations)

    # Update density from new ψ
    occupation, εF = occupation_function(ham.basis, eigres.λ)
    ρout, ρ_spin_out = compute_density(ham.basis, eigres.X, occupation)

    (ψ=eigres.X, eigenvalues=eigres.λ, occupation=occupation, εF=εF,
     ρout=ρout, ρ_spin_out=ρ_spin_out, diagonalization=eigres)
end

"""
Solve the Kohn-Sham equations with a SCF algorithm, starting at ρ.
"""
@timing function self_consistent_field(basis::PlaneWaveBasis;
                                       n_bands=default_n_bands(basis.model),
                                       ρ=guess_density(basis),
                                       ρspin=guess_spin_density(basis),
                                       ψ=nothing,
                                       tol=1e-6,
                                       maxiter=100,
                                       solver=scf_nlsolve_solver(),
                                       eigensolver=lobpcg_hyper,
                                       n_ep_extra=3,
                                       determine_diagtol=ScfDiagtol(),
                                       mixing=SimpleMixing(),
                                       is_converged=ScfConvergenceEnergy(tol),
                                       callback=ScfDefaultCallback(),
                                       compute_consistent_energies=true,
                                       enforce_symmetry=false,
                                       occupation_function=compute_occupation,
                                      )
    T = eltype(basis)
    model = basis.model

    # All these variables will get updated by fixpoint_map
    if ψ !== nothing
        @assert length(ψ) == length(basis.kpoints)
        for ik in 1:length(basis.kpoints)
            @assert size(ψ[ik], 2) == n_bands + n_ep_extra
        end
    end
    occupation = nothing
    eigenvalues = nothing
    ρout = ρ
    ρ_spin_out = ρspin
    εF = nothing
    n_iter = 0
    energies = nothing
    ham = nothing
    info = (n_iter=0, ρin=ρ, ρ_spin_in=ρspin)   # Populate info with initial values
    converged = false

    # We do density mixing in the real representation
    # TODO support other mixing types
    function fixpoint_map(x)
        converged && return x  # No more iterations if convergence flagged

        n_iter += 1
        if model.n_spin_components == 2  # TODO So ugly
            # x has 2 blocks: total and spin density
            ρin, ρ_spin_in = from_real(basis,x[:, :, :, 1]), from_real(basis,x[:, :, :, 2])
        else
            ρin, ρ_spin_in = from_real(basis, x), nothing
        end

        # Build next Hamiltonian, diagonalize it, get ρout
        if n_iter == 1 # first iteration
            _, ham = energy_hamiltonian(basis, nothing, nothing;
                                        ρ=ρin, ρspin=ρ_spin_in, eigenvalues=nothing, εF=nothing)
        else
            # Note that ρin is not the density of ψ, and the eigenvalues
            # are not the self-consistent ones, which makes this energy non-variational
            energies, ham = energy_hamiltonian(basis, ψ, occupation;
                                               ρ=ρin, ρspin=ρ_spin_in, eigenvalues=eigenvalues, εF=εF)
        end

        # Diagonalize `ham` to get the new state
        nextstate = next_density(ham; n_bands=n_bands, ψ=ψ, eigensolver=eigensolver,
                                 miniter=1, tol=determine_diagtol(info),
                                 n_ep_extra=n_ep_extra,
                                 occupation_function=occupation_function)
        ψ, eigenvalues, occupation, εF, ρout, ρ_spin_out = nextstate

        if enforce_symmetry
            ρout = DFTK.symmetrize(ρout)
            !isnothing(ρ_spin_out) && (ρ_spin_out = DFTK.symmetrize(ρ_spin_out))
        end

        # Update info with results gathered so far
        info = (ham=ham, basis=basis, converged=converged, stage=:iterate,
                ρin=ρin, ρ_spin_in=ρ_spin_in, ρout=ρout, ρ_spin_out=ρ_spin_out,
                n_iter=n_iter, n_ep_extra=n_ep_extra, nextstate...)

        # Compute the energy of the new state
        if compute_consistent_energies
            energies, _ = energy_hamiltonian(basis, ψ, occupation;
                                             ρ=ρout, ρspin=ρ_spin_out, eigenvalues=eigenvalues, εF=εF)
        end
        info = merge(info, (energies=energies, ))

        # Apply mixing and pass it the full info as kwargs
        δF_spin = isnothing(ρ_spin_out) ? nothing : ρ_spin_out - ρ_spin_in
        δρ, δρ_spin = mix(mixing, basis, ρout - ρin, δF_spin; info...)
        ρnext = δρ + ρin
        ρ_spin_next = isnothing(ρ_spin_out) ? nothing : δρ_spin + ρ_spin_in
        if enforce_symmetry
            ρnext = DFTK.symmetrize(ρnext)
            !isnothing(ρ_spin_next) && (ρ_spin_next = DFTK.symmetrize(ρ_spin_next))
        end
        info = merge(info, (ρnext=ρnext, ρ_spin_next=ρ_spin_next))

        callback(info)
        is_converged(info) && (converged = true)

        if model.n_spin_components == 2
            cat(ρnext.real, ρ_spin_next.real, dims=4)  # TODO This really has to go
        else
            ρnext.real
        end
    end

    # Tolerance and maxiter are only dummy here: Convergence is flagged by is_converged
    # inside the fixpoint_map. Also we do not use the return value of fpres but rather the
    # one that got updated by fixpoint_map
    ρcat_real = model.n_spin_components == 2 ? cat(ρout.real, ρ_spin_out.real, dims=4) : ρout.real
    fpres = solver(fixpoint_map, ρcat_real, maxiter; tol=eps(T))

    # We do not use the return value of fpres but rather the one that got updated by fixpoint_map
    # ψ is consistent with ρout, so we return that. We also perform
    # a last energy computation to return a correct variational energy
    energies, ham = energy_hamiltonian(basis, ψ, occupation;
                                       ρ=ρout, ρspin=ρ_spin_out, eigenvalues=eigenvalues, εF=εF)

    # Callback is run one last time with final state to allow callback to clean up
    info = (ham=ham, basis=basis, energies=energies, converged=converged,
            ρ=ρout, ρspin=ρ_spin_out, eigenvalues=eigenvalues, occupation=occupation, εF=εF,
            n_iter=n_iter, n_ep_extra=n_ep_extra, ψ=ψ, diagonalization=info.diagonalization,
            stage=:finalize)
    callback(info)
    info
end


text:
using MicroscopyLabels
using Test
using Documenter
using AxisArrays
using ImageMetadata

doctest(MicroscopyLabels)

@testset "timestamps" begin

    @testset "No time axis" begin
        tmp = AxisArray(rand(10, 10), Axis{:x}(1:10), Axis{:y}(1:10));

        @test_logs (:info, "No time axis detected!") timestamp!(tmp)
    end

    @testset "4+ dimensions" begin
        tmp = AxisArray(zeros(200, 200, 10, 3),
                        Axis{:x}(1:200),
                        Axis{:y}(1:200),
                        Axis{:time}(1:10),
                        Axis{:position}(1:3)
                        );
        timestamp!(tmp)

        result = """[0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.16470588235294117 0.6509803921568628 0.6705882352941176 0.16470588235294117 0.0; 0.0 0.37254901960784315 0.3333333333333333 0.0 0.0 0.0 0.0 0.0 0.0 0.2549019607843137 0.3764705882352941 0.4470588235294118 0.6705882352941176 0.0; 0.0 0.40784313725490196 1.0 0.9098039215686274 0.5803921568627451 1.0 1.0 1.0 0.09411764705882353 0.0 0.0 0.26666666666666666 0.5137254901960784 0.0; 0.0 0.40784313725490196 0.34509803921568627 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.18823529411764706 0.7019607843137254 0.03137254901960784 0.0; 0.0 0.39215686274509803 0.42745098039215684 0.058823529411764705 0.5803921568627451 1.0 1.0 1.0 0.09411764705882353 0.06666666666666667 0.6705882352941176 0.050980392156862744 0.0 0.0; 0.0 0.1607843137254902 0.9019607843137255 0.9254901960784314 0.0196078431372549 0.0 0.0 0.0 0.0 0.39215686274509803 1.0 1.0 0.9254901960784314 0.0; 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]"""

        @test all(tmp[10:17, 10:23, 2, 1].data .≈ eval(Meta.parse(result)))
    end

    @testset "ImageMetadata" begin
        tmp = AxisArray(rand(30, 30, 10), Axis{:x}(1:30), Axis{:y}(1:30), Axis{:time}(1:10));
        timestamp!(ImageMeta(tmp))
    end

end


text:
module NumericalMethodsInQuantumMechanics

include("EigenvalueProblems/EigenvalueProblems.jl")

end # module


text:
using Test
using Spandex

@testset "Intlist" begin
    include("Intlist.jl")
end

@testset "DirectedGraph" begin
    include("DirectedGraph.jl")
end

@testset "SparseArray" begin
    include("SparseArray.jl")
end

@testset "SparseMatrix" begin
    include("SparseMatrix.jl")
end

@testset "SparseArithmetic" begin
    include("SparseArithmetic.jl")
end

@testset "SegmentTree" begin
    include("SegmentTree.jl")
end

@testset "PermuteTable" begin
    include("PermuteTable.jl")
end

@testset "CholeskySolver" begin
    include("CholeskySolver.jl")
end

@testset "Normalization" begin
    include("Normalization.jl")
end

@testset "PriorityQueue" begin
    include("PriorityQueue.jl")
end


text:
function read_IDA(dt::Date)

    @assert BusinessDays.isbday(:BRSettlement, dt) "$dt should be a business day in Brazil"

    url = "https://www.anbima.com.br/informacoes/ida/IDA_down.asp"
    str_dt = Dates.format(dt, "dd%2Fmm%2Fyyyy")
    str_month = Dates.format(dt, "mm%2Fyyyy")

    header = [
        "Host" => "www.anbima.com.br"
        "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0"
        "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
        "Accept-Language" => "pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3"
        "Accept-Encoding" => "gzip, deflate, br"
        "Content-Type" => "application/x-www-form-urlencoded"
        "Content-Length" => "73"
        "Origin" => "https://www.anbima.com.br"
        "Connection" => "keep-alive"
        "Referer" => "https://www.anbima.com.br/informacoes/ida/IDA_result.asp"
        "Cookie" => "lumClientId=8A2AB290749450B201749709905D1504; JSESSIONID=23564884E50B8DB92E68D45AC216EDB1.LumisProdA; lumUserLocale=pt_BR; lumMonUid=GB9v_UzD1CZbwjVzKKYvn0QTc3CJxsuf; AWSELB=359F6F8906C702E7D2BBD3C04A400F8539C6D91FD23AB4870C6F06E79BBF1036E517A60EF149A503B53EBF4D8862B25DAA307E36A36717521B34D32279CC0AF98F016EE242940E4EDC29638DEB2407933C4CE9B519; ASPSESSIONIDQESTDBAS=BEEEIPJAJGLADHHNEKBGLKPE; BIGipServerPool_ANBSPCLD-WEB02_SSL=204005386.47873.0000; __utma=234609614.893389923.1600261823.1600275110.1600302962.3; __utmc=234609614; __utmz=234609614.1600261823.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); _ga=GA1.3.893389923.1600261823; _gid=GA1.3.220011512.1600261823; _fbp=fb.2.1600261824060.1044754934; _hjTLDTest=1; _hjid=67d810ba-8ef2-40f5-80d2-63d7dbac00b7; __trf.src=encoded_eyJmaXJzdF9zZXNzaW9uIjp7InZhbHVlIjoiMjM0NjA5NjE0LjE2MDAyNjE4MjMuMS4xLnV0bWNzcj1nb29nbGV8dXRtY2NuPShvcmdhbmljKXx1dG1jbWQ9b3JnYW5pY3x1dG1jdHI9KG5vdCBwcm92aWRlZCkiLCJleHRyYV9wYXJhbXMiOnt9fSwiY3VycmVudF9zZXNzaW9uIjp7InZhbHVlIjoiaHR0cHM6Ly93d3cuYW5iaW1hLmNvbS5ici9wdF9ici9pbmZvcm1hci9wcmVjb3MtZS1pbmRpY2VzL2luZGljZXMvaW1hLmh0bSIsImV4dHJhX3BhcmFtcyI6e319LCJjcmVhdGVkX2F0IjoxNjAwMzAzMTYwMDUwfQ==; rdtrk=%7B%22id%22%3A%221d5766e6-4883-442c-930a-d1d22efb296f%22%7D; ADRUM=s=1600303155552&r=https%3A%2F%2Fwww.anbima.com.br%2Fpt_br%2Finformar%2Fprecos-e-indices%2Findices%2Fida.htm%3F660476728; __utmb=234609614.15.10.1600302962; __utmt=1; __utmt_UA-18261922-8=1; lumUserSessionId=uwNfY6_NU9CN6CE6PJEs_Hn6FrkezUxJ; lumUserName=Guest; lumIsLoggedUser=false; _gat_UA-18261922-22=1; _gat_UA-18261922-23=1; _dc_gtm_UA-18261922-14=1"
        "Upgrade-Insecure-Requests" => "1"
    ]

    body = "DataIniD=$str_dt&DataIniM=$str_month&indice=GERAL&tipo=qr&saida=csv"

    r = HTTP.post(url, header, body)

    response_body = String(r.body)
    @assert _has_data_ida(response_body) "no IDA data for date $dt"
    out = _parse_ida_result(response_body)
    for (k, ida) in out.elements
        @assert ida.date == dt "Invalid date for $(k): expected $(dt) got $(ida.date)"
    end
    return out

end

function _has_data_ida(s::String)
    lines = split(s, "\r\n")
    return length(lines) > 3
end

function _parse_ida_result(s::String)
    lines = split(s, "\r\n")
    v_elements = Vector{IDA}()
    for line in lines[4:(end-1)]
        vals = split(line, ";")
        @assert length(vals) == 11 "esperava 11 campos na linha mas recebeu $(length(vals)): $line"
        element = IDA(
            vals[1],
            Date(vals[2], "dd/mm/yyyy"),
            parse_value(Float64, vals[3]),
            parse_value(Float64, vals[4]),
            parse_value(Float64, vals[5]),
            parse_value(Float64, vals[6]),
            parse_value(Float64, vals[7]),
            parse_value(Float64, vals[8]),
            parse_value(Int64, vals[9]),
            parse_value(Float64, vals[10]),
            parse_value(Float64, vals[11])
        )
        push!(v_elements, element)
    end
    return IDAResult(v_elements)
end


text:
# GMM estimation for a sample from Chi^2(theta)
# compare to two method of moments estimators (see chi2mm.m)
using Econometrics, Random, LinearAlgebra, Distributions, Plots
function main()
n = 30
theta = 3.0
reps = 10000
results = zeros(reps)
W = eye(2)
y = zeros(n) # this is just a place holder to define the moments, below
# define the moment conditions
m = theta -> [theta.-mean(y); theta.-0.5*var(y)]
for i = 1:reps
    rand!(Chisq(theta), y) # this replaces the place holder, from above
    obj = theta -> dot(m(theta),W*m(theta))
    thetahat, junk, junk = fminunc(obj, [3.0])
    results[i] = sqrt(n)*(thetahat[1]-theta)
end
p = histogram(results,nbins=99, legend=false)
end
main()

max_stars_repo_name: Hiroakiyusheng/Econometrics

max_issues_repo_name: Hiroakiyusheng/Econometrics

max_forks_repo_name: Hiroakiyusheng/Econometrics


text:
function Transformation(transform_func=identity)
    flip = Node((false, false, false))
    scale = Node(Vec3f0(1))
    scale = lift(flip, scale) do f, s
        map((f, s)-> f ? -s : s, Vec(f), s)
    end
    translation, rotation, align = (
        Node(Vec3f0(0)),
        Node(Quaternionf0(0, 0, 0, 1)),
        Node(Vec2f0(0))
    )
    trans = nothing
    model = map_once(scale, translation, rotation, align, flip) do s, o, q, a, flip
        parent = if trans !== nothing && isassigned(trans.parent)
            boundingbox(trans.parent[])
        else
            nothing
        end
        transformationmatrix(o, s, q, a, flip, parent)
    end
    return Transformation(
        translation,
        scale,
        rotation,
        model,
        flip,
        align,
        Node{Any}(transform_func)
    )
end

function Transformation(scene::SceneLike)
    flip = Node((false, false, false))
    scale = Node(Vec3f0(1))
    translation, rotation, align = (
        Node(Vec3f0(0)),
        Node(Quaternionf0(0, 0, 0, 1)),
        Node(Vec2f0(0))
    )
    pmodel = transformationmatrix(scene)
    trans = nothing
    model = map_once(scale, translation, rotation, align, pmodel, flip) do s, o, q, a, p, f
        bb = if trans !== nothing && isassigned(trans.parent)
            boundingbox(trans.parent[])
        else
            nothing
        end
        return p * transformationmatrix(o, s, q, align, f, bb)
    end

    ptrans = transformation(scene)
    trans = Transformation(
        translation,
        scale,
        rotation,
        model,
        flip,
        align,
        copy(ptrans.transform_func)
    )
    return trans
end

function translated(scene::Scene, translation...)
    tscene = Scene(scene, transformation = Transformation())
    transform!(tscene, translation...)
    tscene
end

function translated(scene::Scene; kw_args...)
    tscene = Scene(scene, transformation = Transformation())
    transform!(tscene; kw_args...)
    tscene
end

function transform!(
        scene::SceneLike;
        translation = Vec3f0(0),
        scale = Vec3f0(1),
        rotation = 0.0,
    )
    translate!(scene, translation)
    scale!(scene, scale)
    rotate!(scene, rotation)
end

transformation(t::Scene) = t.transformation
transformation(t::AbstractPlot) = t.transformation
transformation(t::Transformation) = t

scale(t::Transformable) = transformation(t).scale

scale!(t::Transformable, s) = (scale(t)[] = to_ndim(Vec3f0, Float32.(s), 1))

"""
    scale!(t::Transformable, x, y)
    scale!(t::Transformable, x, y, z)
    scale!(t::Transformable, xyz)
    scale!(t::Transformable, xyz...)

Scale the given `Transformable` (a Scene or Plot) to the given arguments.
Can take `x, y` or `x, y, z`.
This is an absolute scaling, and there is no option to perform relative scaling.
"""
scale!(t::Transformable, xyz...) = scale!(t, xyz)

rotation(scene::Transformable) = transformation(scene).rotation

function rotate!(::Type{T}, scene::Transformable, q) where T
    rot = convert_attribute(q, key"rotation"())
    if T === Accum
        rot1 = rotation(scene)[]
        rotation(scene)[] = rot1 * rot
    elseif T == Absolute
        rotation(scene)[] = rot
    else
        error("Unknown transformation: $T")
    end
end

"""
    rotate!(Accum, scene::Transformable, axis_rot...)

Apply a relative rotation to the Scene, by multiplying by the current rotation.
"""
rotate!(::Type{T}, scene::Transformable, axis_rot...) where T = rotate!(T, scene, axis_rot)

"""
    rotate!(scene::Transformable, axis_rot::Quaternion)
    rotate!(scene::Transformable, axis_rot::AbstractFloat)
    rotate!(scene::Transformable, axis_rot...)

Apply an absolute rotation to the Scene. Rotations are all internally converted to `Quaternion`s.
"""
rotate!(scene::Transformable, axis_rot...) = rotate!(Absolute, scene, axis_rot)
rotate!(scene::Transformable, axis_rot::Quaternion) = rotate!(Absolute, scene, axis_rot)
rotate!(scene::Transformable, axis_rot::AbstractFloat) = rotate!(Absolute, scene, axis_rot)

translation(scene::Transformable) = transformation(scene).translation

"""
    Accum
Force transformation to be relative to the current state, not absolute.
"""
struct Accum end

"""
    Absolute
Force transformation to be absolute, not relative to the current state.
This is the default setting.
"""
struct Absolute end

function translate!(::Type{T}, scene::Transformable, t) where T
    offset = to_ndim(Vec3f0, Float32.(t), 0)
    if T === Accum
        translation(scene)[] = translation(scene)[] .+ offset
    elseif T === Absolute
        translation(scene)[] = offset
    else
        error("Unknown translation type: $T")
    end
end
"""
    translate!(scene::Transformable, xyz::VecTypes)
    translate!(scene::Transformable, xyz...)

Apply an absolute translation to the Scene, translating it to `x, y, z`.
"""
translate!(scene::Transformable, xyz::VecTypes) = translate!(Absolute, scene, xyz)
translate!(scene::Transformable, xyz...) = translate!(Absolute, scene, xyz)
"""
    translate!(Accum, scene::Transformable, xyz...)

Translate the scene relative to its current position.
"""
translate!(::Type{T}, scene::Transformable, xyz...) where T = translate!(T, scene, xyz)

function transform!(scene::Transformable, x::Tuple{Symbol, <: Number})
    plane, dimval = string(x[1]), Float32(x[2])
    if length(plane) != 2 || (!all(x-> x in ('x', 'y', 'z'), plane))
        error("plane needs to define a 2D plane in xyz. It should only contain 2 symbols out of (:x, :y, :z). Found: $plane")
    end
    if all(x-> x in ('x', 'y'), plane) # xy plane
        translate!(scene, 0, 0, dimval)
    elseif all(x-> x in ('x', 'z'), plane) # xz plane
        rotate!(scene, Vec3f0(1, 0, 0), 0.5pi)
        translate!(scene, 0, dimval, 0)
    else #yz plane
        r1 = qrotation(Vec3f0(0, 1, 0), 0.5pi)
        r2 = qrotation(Vec3f0(1, 0, 0), 0.5pi)
        rotate!(scene,  r2 * r1)
        translate!(scene, dimval, 0, 0)
    end
    scene
end

transformationmatrix(x) = transformation(x).model

transform_func(x) = transform_func_obs(x)[]
transform_func_obs(x) = transformation(x).transform_func

"""
    apply_transform(f, data)
Apply the data transform func to the data
"""
apply_transform(f::typeof(identity), x) = x
# these are all ambiguity fixes
apply_transform(f::typeof(identity), x::AbstractArray) = x
apply_transform(f::typeof(identity), x::VecTypes) = x
apply_transform(f::typeof(identity), x::Number) = x
apply_transform(f::typeof(identity), x::ClosedInterval) = x

apply_transform(f::NTuple{2, typeof(identity)}, x) = x
apply_transform(f::NTuple{2, typeof(identity)}, x::AbstractArray) = x
apply_transform(f::NTuple{2, typeof(identity)}, x::VecTypes) = x
apply_transform(f::NTuple{2, typeof(identity)}, x::Number) = x
apply_transform(f::NTuple{2, typeof(identity)}, x::ClosedInterval) = x

apply_transform(f::NTuple{3, typeof(identity)}, x) = x
apply_transform(f::NTuple{3, typeof(identity)}, x::AbstractArray) = x
apply_transform(f::NTuple{3, typeof(identity)}, x::VecTypes) = x
apply_transform(f::NTuple{3, typeof(identity)}, x::Number) = x
apply_transform(f::NTuple{3, typeof(identity)}, x::ClosedInterval) = x

struct PointTrans{N, F}
    f::F
    function PointTrans{N}(f::F) where {N, F}
        if !hasmethod(f, Tuple{Point{N}})
            error("PointTrans with parameter N = $N must be applicable to an argument of type Point{$N}.")
        end
        new{N, F}(f)
    end
end

# PointTrans{N}(func::F) where {N, F} = PointTrans{N, F}(func)
Base.broadcastable(x::PointTrans) = (x,)

function apply_transform(f::PointTrans{N}, point::Point{N}) where N
    return f.f(point)
end

function apply_transform(f::PointTrans{N1}, point::Point{N2}) where {N1, N2}
    p_dim = to_ndim(Point{N1, Float32}, point, 0.0)
    p_trans = f.f(p_dim)
    if N1 < N2
        p_large = ntuple(i-> i <= N1 ? p_trans[i] : point[i], N2)
        return Point{N2, Float32}(p_large)
    else
        return to_ndim(Point{N2, Float32}, p_trans, 0.0)
    end
end

function apply_transform(f, data::AbstractArray)
    map(point-> apply_transform(f, point), data)
end

function apply_transform(f::Tuple{Any, Any}, point::VecTypes{2})
    Point2{Float32}(
        f[1](point[1]),
        f[2](point[2]),
    )
end
# ambiguity fix
apply_transform(f::NTuple{2, typeof(identity)}, point::VecTypes{2}) = point

function apply_transform(f::Tuple{Any, Any}, point::VecTypes{3})
    apply_transform((f..., identity), point)
end
# ambiguity fix
apply_transform(f::NTuple{2, typeof(identity)}, point::VecTypes{3}) = point

function apply_transform(f::Tuple{Any, Any, Any}, point::VecTypes{3})
    Point3{Float32}(
        f[1](point[1]),
        f[2](point[2]),
        f[3](point[3]),
    )
end
# ambiguity fix
apply_transform(f::NTuple{3, typeof(identity)}, point::VecTypes{3}) = point

apply_transform(f, number::Number) = f(number)

function apply_transform(f::Observable, data::Observable)
    return lift((f, d)-> apply_transform(f, d), f, data)
end

apply_transform(f, itr::Pair) = apply_transform(f, itr[1]) => apply_transform(f, itr[2])
function apply_transform(f, itr::ClosedInterval)
    mini, maxi = extrema(itr)
    return apply_transform(f, mini) .. apply_transform(f, maxi)
end

function apply_transform(f, r::Rect)
    mi = minimum(r)
    ma = maximum(r)
    mi_t = apply_transform(f, mi)
    ma_t = apply_transform(f, ma)
    Rect(Vec(mi_t), Vec(ma_t .- mi_t))
end
# ambiguity fix
apply_transform(f::typeof(identity), r::Rect) = r
apply_transform(f::NTuple{2, typeof(identity)}, r::Rect) = r
apply_transform(f::NTuple{3, typeof(identity)}, r::Rect) = r

pseudolog10(x) = sign(x) * log10(abs(x) + 1)
inv_pseudolog10(x) = sign(x) * (exp10(abs(x)) - 1)

struct Symlog10
    low::Float64
    high::Float64
    function Symlog10(low, high)
        if !(low < 0 && high > 0)
            error("Low bound needs to be smaller than 0 and high bound larger than 0. You gave $low, $high.")
        end
        new(Float64(low), Float64(high))
    end
end
function Symlog10(x)
    Symlog10(-x, x)
end
function (s::Symlog10)(x)
    if x > 0
        x <= s.high ? x / s.high * log10(s.high) : log10(x)
    elseif x < 0
        x >= s.low ? x / abs(s.low) * log10(abs(s.low)) : sign(x) * log10(abs(x))
    else
        x
    end
end
function inv_symlog10(x, low, high)
    if x > 0
        l = log10(high)
        x <= l ? x / l * high : exp10(x)
    elseif x < 0
        l = sign(x) * log10(abs(low))
        x >= l ? x / l * abs(s.low) : sign(x) * exp10(abs(x))
    else
        x
    end
end

inverse_transform(::typeof(identity)) = identity
inverse_transform(::typeof(log10)) = exp10
inverse_transform(::typeof(log)) = exp
inverse_transform(::typeof(log2)) = exp2
inverse_transform(::typeof(sqrt)) = x -> x ^ 2
inverse_transform(::typeof(pseudolog10)) = inv_pseudolog10
inverse_transform(F::Tuple) = map(inverse_transform, F)
inverse_transform(::typeof(logit)) = logistic
inverse_transform(s::Symlog10) = x -> inv_symlog10(x, s.low, s.high)


text:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Description
#
#    Tests of renderers.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

@testset "Renderers - printf" begin
    matrix = Any[BigFloat(pi) float(pi) 10.0f0  Float16(1)
                 0x01         0x001     0x00001 0x000000001
                 true         false     true    false
                 "Teste" "Teste\nTeste" "Teste \"quote\" Teste" "Teste\n\"quote\"\nTeste"]

    header = ["C1" "C2" "C3" "C4"
              "S1" "S2" "S3" "S4"]

    row_names = [1,2,"3",'4']

    # Print
    # --------------------------------------------------------------------------

    expected = """
┌───┬──────┬──────────────────────────────────────────────────────────────────────────────────┬─────────┬─────────────────────┬─────────┐
│ # │ Test │                                                                               C1 │      C2 │                  C3 │      C4 │
│   │      │                                                                               S1 │      S2 │                  S3 │      S4 │
├───┼──────┼──────────────────────────────────────────────────────────────────────────────────┼─────────┼─────────────────────┼─────────┤
│ 1 │    1 │ 3.141592653589793238462643383279502884197169399375105820974944592307816406286198 │ 3.14159 │                10.0 │     1.0 │
│ 2 │    2 │                                                                                1 │       1 │                   1 │       1 │
│ 3 │    3 │                                                                             true │   false │                true │   false │
│ 4 │    4 │                                                                            Teste │   Teste │ Teste "quote" Teste │   Teste │
│   │      │                                                                                │   Teste │                     │ "quote" │
│   │      │                                                                                │         │                     │   Teste │
└───┴──────┴──────────────────────────────────────────────────────────────────────────────────┴─────────┴─────────────────────┴─────────┘
"""

    result = pretty_table(String, matrix, header;
                          linebreaks = true,
                          row_names = row_names,
                          row_name_column_title = "Test",
                          row_number_column_title = "#",
                          show_row_number = true)

    @test expected == result

    expected = """
┌───┬──────┬──────────────────────────────────────────────────────────────────────────────────┬───────────────────┬─────────────────────┬─────────┐
│ # │ Test │                                                                               C1 │                C2 │                  C3 │      C4 │
│   │      │                                                                               S1 │                S2 │                  S3 │      S4 │
├───┼──────┼──────────────────────────────────────────────────────────────────────────────────┼───────────────────┼─────────────────────┼─────────┤
│ 1 │    1 │ 3.141592653589793238462643383279502884197169399375105820974944592307816406286198 │ 3.141592653589793 │                10.0 │     1.0 │
│ 2 │    2 │                                                                                1 │                 1 │                   1 │       1 │
│ 3 │    3 │                                                                             true │             false │                true │   false │
│ 4 │    4 │                                                                            Teste │             Teste │ Teste "quote" Teste │   Teste │
│   │      │                                                                                │             Teste │                     │ "quote" │
│   │      │                                                                                │                   │                     │   Teste │
└───┴──────┴──────────────────────────────────────────────────────────────────────────────────┴───────────────────┴─────────────────────┴─────────┘
"""

    result = pretty_table(String, matrix, header;
                          compact_printing = false,
                          linebreaks = true,
                          row_names = row_names,
                          row_name_column_title = "Test",
                          row_number_column_title = "#",
                          show_row_number = true)

    @test expected == result
end

@testset "Renderers - show" begin
    matrix = Any[BigFloat(pi) float(pi) 10.0f0  Float16(1)
                 0x01         0x001     0x00001 0x000000001
                 true         false     true    false
                 "Teste" "Teste\nTeste" "Teste \"quote\" Teste" "Teste\n\"quote\"\nTeste"]

    header = ["C1" "C2" "C3" "C4"
              "S1" "S2" "S3" "S4"]

    row_names = [1,2,"3",'4']

    # Show
    # --------------------------------------------------------------------------

    expected = """
┌───┬──────┬─────────┬─────────┬─────────────────────────┬────────────────────┐
│ # │ Test │      C1 │      C2 │                      C3 │                 C4 │
│   │      │      S1 │      S2 │                      S3 │                 S4 │
├───┼──────┼─────────┼─────────┼─────────────────────────┼────────────────────┤
│ 1 │    1 │ 3.14159 │ 3.14159 │                    10.0 │                1.0 │
│ 2 │    2 │    0x01 │  0x0001 │              0x00000001 │ 0x0000000000000001 │
│ 3 │    3 │    true │   false │                    true │              false │
│ 4 │    4 │ "Teste" │ "Teste" │ "Teste \\"quote\\" Teste" │            "Teste" │
│   │      │         │ "Teste" │                         │        "\\"quote\\"" │
│   │      │         │         │                         │            "Teste" │
└───┴──────┴─────────┴─────────┴─────────────────────────┴────────────────────┘
"""

    result = pretty_table(String, matrix, header;
                          linebreaks = true,
                          renderer = :show,
                          row_names = row_names,
                          row_name_column_title = "Test",
                          row_number_column_title = "#",
                          show_row_number = true)

    @test expected == result

    expected = """
┌───┬──────┬──────────────────────────────────────────────────────────────────────────────────┬───────────────────┬─────────────────────────┬────────────────────┐
│ # │ Test │                                                                               C1 │                C2 │                      C3 │                 C4 │
│   │      │                                                                               S1 │                S2 │                      S3 │                 S4 │
├───┼──────┼──────────────────────────────────────────────────────────────────────────────────┼───────────────────┼─────────────────────────┼────────────────────┤
│ 1 │    1 │ 3.141592653589793238462643383279502884197169399375105820974944592307816406286198 │ 3.141592653589793 │                  10.0f0 │       Float16(1.0) │
│ 2 │    2 │                                                                             0x01 │            0x0001 │              0x00000001 │ 0x0000000000000001 │
│ 3 │    3 │                                                                             true │             false │                    true │              false │
│ 4 │    4 │                                                                          "Teste" │           "Teste" │ "Teste \\"quote\\" Teste" │            "Teste" │
│   │      │                                                                                │           "Teste" │                         │        "\\"quote\\"" │
│   │      │                                                                                │                   │                         │            "Teste" │
└───┴──────┴──────────────────────────────────────────────────────────────────────────────────┴───────────────────┴─────────────────────────┴────────────────────┘
"""

    result = pretty_table(String, matrix, header;
                          compact_printing = false,
                          linebreaks = true,
                          renderer = :show,
                          row_names = row_names,
                          row_name_column_title = "Test",
                          row_number_column_title = "#",
                          show_row_number = true)

    @test expected == result

    # Test the behavior if a formatter returns a string but the original data is
    # not a string. In this case, the renderer `show` must not add surrounding
    # quotes.
    matrix = ['1' "2" 3 s"123"]

    f = (v,i,j)->begin
        if j == 1
            return "😀😀😀"
        elseif j == 2
            return "😁😁"
        elseif j == 3
            return 'a'
        else
            return v
        end
    end

    expected = """
┌────────┬────────┬────────┬────────┐
│ Col. 1 │ Col. 2 │ Col. 3 │ Col. 4 │
├────────┼────────┼────────┼────────┤
│ 😀😀😀 │ "😁😁" │    'a' │ s"123" │
└────────┴────────┴────────┴────────┘
"""

    result = pretty_table(String, matrix,
                          formatters = f,
                          renderer = :show)

    @test result == expected
end


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "FreeType2"
version = v"2.10.0"

# Collection of sources required to build FreeType2
sources = [
    "https://download.savannah.gnu.org/releases/freetype/freetype-2.10.0.tar.gz" =>
    "955e17244e9b38adb0c98df66abb50467312e6bb70eac07e49ce6bd1a20e809a",

]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir

if [[ "${target}" == *mingw* ]]; then

cd freetype-2.10.0/builds
cat > exports.patch << 'END'
--- exports.mk
+++ exports.mk
@@ -30,9 +30,7 @@
   # on the host machine.  This isn't necessarily the same as the compiler
   # which can be a cross-compiler for a different architecture, for example.
   #
-  ifeq ($(CCexe),)
-    CCexe := $(CC)
-  endif
+  CCexe := /opt/x86_64-linux-gnu/bin/gcc   # use hard-coded path

   # TE acts like T, but for executables instead of object files.
   ifeq ($(TE),)
END

patch --ignore-whitespace < exports.patch

cd ..
./configure --prefix=$prefix --host=$target

else

cd freetype-2.10.0
mkdir build && cd build
CMAKE_FLAGS="-DCMAKE_INSTALL_PREFIX=${prefix} -DCMAKE_TOOLCHAIN_FILE=/opt/${target}/${target}.toolchain"
CMAKE_FLAGS="${CMAKE_FLAGS} -DBUILD_SHARED_LIBS=true"
cmake .. ${CMAKE_FLAGS}

fi

make -j${nproc}
make install

"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# The products that we will ensure are always built
products(prefix) = [
    LibraryProduct(prefix, "libfreetype", :libfreetype)
]

# Dependencies that must be installed before this package can be built
dependencies = [
    "https://github.com/staticfloat/Bzip2Builder/releases/download/v1.0.6-1/build_Bzip2.v1.0.6.jl",
    "https://github.com/bicycle1885/ZlibBuilder/releases/download/v1.0.4/build_Zlib.v1.2.11.jl"

]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)


text:
# An Int-valued attribute
struct MockModelAttribute <: MOI.AbstractModelAttribute
end

# An Int-valued attribute
struct MockVariableAttribute <: MOI.AbstractVariableAttribute
end

# An Int-valued attribute
struct MockConstraintAttribute <: MOI.AbstractConstraintAttribute
end

# A mock optimizer used for testing.
mutable struct MockOptimizer{MT<:MOI.ModelLike} <: MOI.AbstractOptimizer
    inner_model::MT
    attribute::Int # MockModelAttribute
    varattribute::Dict{MOI.VariableIndex,Int} # MockVariableAttribute
    conattribute::Dict{MOI.ConstraintIndex,Int} # MockConstraintAttribute
    supports_names::Bool # Allows to test with optimizer not supporting names
    needs_allocate_load::Bool # Allows to tests the Allocate-Load interface, see copy_to
    add_var_allowed::Bool # If false, the optimizer throws AddVariableNotAllowed
    add_con_allowed::Bool # If false, the optimizer throws AddConstraintNotAllowed
    modify_allowed::Bool # If false, the optimizer throws Modify...NotAllowed
    delete_allowed::Bool # If false, the optimizer throws DeleteNotAllowed
    optimize!::Function
    solved::Bool
    hasprimal::Bool
    hasdual::Bool
    result_count::Int
    terminationstatus::MOI.TerminationStatusCode
    # Computes `ObjectiveValue` by evaluating the `ObjectiveFunction` with
    # `VariablePrimal`. See `get_fallback`.
    eval_objective_value::Bool
    objective_value::Float64 # set this using MOI.set(model, MOI.ObjectiveValue(), value)
    # Computes `DualObjectiveValue` using `get_fallback`
    eval_dual_objective_value::Bool
    dual_objective_value::Float64 # set this using MOI.set(model, MOI.DualObjectiveValue(), value)
    primalstatus::MOI.ResultStatusCode
    dualstatus::MOI.ResultStatusCode
    varprimal::Dict{MOI.VariableIndex,Float64}
    callback_variable_primal::Dict{MOI.VariableIndex, Float64}
    # Computes `ConstraintDual` of constraints with `SingleVariable` or
    # `VectorOfVariables` functions by evaluating the `ConstraintDual` of
    # constraints having the variable in the function. See `get_fallback`.
    eval_variable_constraint_dual::Bool
    condual::Dict{MOI.ConstraintIndex,Any}
    con_basis::Dict{MOI.ConstraintIndex,MOI.BasisStatusCode}
    # The attributes set by `MOI.optimize!` cannot be set to `model`.
    # We detect them with `is_set_by_optimize` and store them in the following:
    optimizer_attributes::Dict{MOI.AbstractOptimizerAttribute, Any}
    model_attributes::Dict{MOI.AbstractModelAttribute, Any}
    submitted::Dict{MOI.AbstractSubmittable, Vector{Tuple}}
end

# All user-facing indices are xor'd with this mask to produce unusual indices.
# This is good at catching bugs.
const internal_xor_mask = Int64(12345678)
xor_index(vi::VI) = VI(xor(vi.value, internal_xor_mask))
xor_index(ci::CI{F,S}) where {F,S} = CI{F,S}(xor(ci.value, internal_xor_mask))
xor_indices(x) = map_indices(xor_index, x)

function MockOptimizer(inner_model::MOI.ModelLike; supports_names=true,
                       needs_allocate_load=false,
                       add_var_allowed=!needs_allocate_load,
                       add_con_allowed=!needs_allocate_load,
                       eval_objective_value=true,
                       eval_dual_objective_value=true,
                       eval_variable_constraint_dual=true)
    return MockOptimizer(inner_model,
                         0,
                         Dict{MOI.VariableIndex,Int}(),
                         Dict{MOI.ConstraintIndex,Int}(),
                         supports_names,
                         needs_allocate_load,
                         add_var_allowed,
                         add_con_allowed,
                         true,
                         true,
                         (::MockOptimizer) -> begin end,
                         false,
                         false,
                         false,
                         1,
                         MOI.OPTIMIZE_NOT_CALLED,
                         eval_objective_value,
                         NaN,
                         eval_dual_objective_value,
                         NaN,
                         MOI.NO_SOLUTION,
                         MOI.NO_SOLUTION,
                         Dict{MOI.VariableIndex,Float64}(),
                         Dict{MOI.VariableIndex,Float64}(),
                         eval_variable_constraint_dual,
                         Dict{MOI.ConstraintIndex,Any}(),
                         Dict{MOI.ConstraintIndex,MOI.BasisStatusCode}(),
                         Dict{MOI.AbstractOptimizerAttribute, Any}(),
                         Dict{MOI.AbstractModelAttribute, Any}(),
                         Dict{MOI.AbstractSubmittable, Vector{Tuple}}())
end

function MOI.add_variable(mock::MockOptimizer)
    if mock.add_var_allowed
        return xor_index(MOI.add_variable(mock.inner_model))
    else
        throw(MOI.AddVariableNotAllowed())
    end
end

function MOI.add_constraint(mock::MockOptimizer,
                            func::MOI.AbstractFunction,
                            set::MOI.AbstractSet)
    if mock.add_con_allowed
        ci = MOI.add_constraint(mock.inner_model, xor_indices(func), set)
        return xor_index(ci)
    else
        throw(MOI.AddConstraintNotAllowed{typeof(func), typeof(set)}())
    end
end
function MOI.optimize!(mock::MockOptimizer)
    mock.solved = true
    mock.hasprimal = true
    mock.hasdual = true
    mock.optimize!(mock)
end

function throw_mock_unsupported_names(attr)
    throw(MOI.UnsupportedAttribute(
        attr, "The MockOptimizer was configured not to support names for " *
        "testing purpose using the `support_names=false` constructor keyword " *
        "argument."))
end

function MOI.supports(mock::MockOptimizer,
                      ::Union{MOI.VariablePrimal, MockVariableAttribute},
                      ::Type{MOI.VariableIndex})
    return true
end
function MOI.supports(mock::MockOptimizer,
                      attr::MOI.AbstractVariableAttribute,
                      IdxT::Type{MOI.VariableIndex})
    return MOI.supports(mock.inner_model, attr, IdxT)
end
function MOI.supports(mock::MockOptimizer,
                      ::Union{MOI.ConstraintDual, MockConstraintAttribute},
                      ::Type{<:MOI.ConstraintIndex})
    return true
end
function MOI.supports(mock::MockOptimizer,
                      attr::MOI.AbstractConstraintAttribute,
                      IdxT::Type{<:MOI.ConstraintIndex})
    return MOI.supports(mock.inner_model, attr, IdxT)
end

MOI.supports(mock::MockOptimizer, ::MockModelAttribute) = true
MOI.set(mock::MockOptimizer, ::MOI.TerminationStatus, value::MOI.TerminationStatusCode) = (mock.terminationstatus = value)
MOI.set(mock::MockOptimizer, ::MOI.ObjectiveValue, value::Real) = (mock.objective_value = value)
MOI.set(mock::MockOptimizer, ::MOI.DualObjectiveValue, value::Real) = (mock.dual_objective_value = value)
MOI.set(mock::MockOptimizer, ::MOI.PrimalStatus, value::MOI.ResultStatusCode) = (mock.primalstatus = value)
MOI.set(mock::MockOptimizer, ::MOI.DualStatus, value::MOI.ResultStatusCode) = (mock.dualstatus = value)
MOI.set(mock::MockOptimizer, ::MockModelAttribute, value::Integer) = (mock.attribute = value)
function MOI.supports(mock::MockOptimizer, attr::MOI.AbstractOptimizerAttribute)
    # `supports` is not defined if `is_set_by_optimize(attr)` so we pass it to
    # `mock.inner_model`.
    return MOI.supports(mock.inner_model, attr)
end
function MOI.set(mock::MockOptimizer, attr::MOI.AbstractOptimizerAttribute,
                 value)
    if MOI.is_set_by_optimize(attr)
        mock.optimizer_attributes[attr] = value
    else
        MOI.set(mock.inner_model, attr, xor_indices(value))
    end
end
function MOI.supports(mock::MockOptimizer, attr::MOI.AbstractModelAttribute)
    # `supports` is not defined if `is_set_by_optimize(attr)` so we pass it to
    # `mock.inner_model`.
    return MOI.supports(mock.inner_model, attr)
end
function MOI.set(mock::MockOptimizer, attr::MOI.AbstractModelAttribute, value)
    if MOI.is_set_by_optimize(attr)
        mock.model_attributes[attr] = value
    else
        MOI.set(mock.inner_model, attr, xor_indices(value))
    end
end

function MOI.set(mock::MockOptimizer, attr::MOI.AbstractVariableAttribute,
                 idx::MOI.VariableIndex, value)
    MOI.set(mock.inner_model, attr, xor_index(idx), xor_indices(value))
end
function MOI.set(mock::MockOptimizer, ::MOI.VariablePrimal,
                 idx::MOI.VariableIndex, value)
    mock.varprimal[xor_index(idx)] = value
end
function MOI.set(mock::MockOptimizer, ::MOI.CallbackVariablePrimal,
                 idx::MOI.VariableIndex, value)
    mock.callback_variable_primal[xor_index(idx)] = value
end
function MOI.set(mock::MockOptimizer, ::MockVariableAttribute,
                 idx::MOI.VariableIndex, value)
    mock.varattribute[xor_index(idx)] = value
end
function MOI.set(mock::MockOptimizer, attr::MOI.AbstractConstraintAttribute,
                 idx::MOI.ConstraintIndex, value)
    MOI.set(mock.inner_model, attr, xor_index(idx), value)
end
function MOI.set(mock::MockOptimizer, ::MockConstraintAttribute,
                 idx::MOI.ConstraintIndex, value)
    mock.conattribute[xor_index(idx)] = value
end
function MOI.set(mock::MockOptimizer, ::MOI.ConstraintDual,
                 idx::MOI.ConstraintIndex, value)
    mock.condual[xor_index(idx)] = value
end
function MOI.set(mock::MockOptimizer, ::MOI.ConstraintBasisStatus,
                 idx::MOI.ConstraintIndex, value)
    mock.con_basis[xor_index(idx)] = value
end

MOI.get(mock::MockOptimizer, ::MOI.RawSolver) = mock
function MOI.get(mock::MockOptimizer, attr::MOI.AbstractOptimizerAttribute)
    if MOI.is_set_by_optimize(attr)
        return mock.optimizer_attributes[attr]
    else
        return xor_indices(MOI.get(mock.inner_model, attr))
    end
end
function MOI.get(mock::MockOptimizer, attr::MOI.AbstractModelAttribute)
    if MOI.is_set_by_optimize(attr)
        return mock.model_attributes[attr]
    else
        return xor_indices(MOI.get(mock.inner_model, attr))
    end
end

#####
##### Names
#####

function MOI.supports(mock::MockOptimizer, attr::MOI.Name)
    return mock.supports_names && MOI.supports(mock.inner_model, attr)
end
function MOI.set(mock::MockOptimizer, attr::MOI.Name, value)
    if mock.supports_names
        MOI.set(mock.inner_model, attr, value)
    else
        throw_mock_unsupported_names(attr)
    end
end
function MOI.supports(mock::MockOptimizer, attr::MOI.VariableName,
                      IdxT::Type{MOI.VariableIndex})
    return mock.supports_names && MOI.supports(mock.inner_model, attr, IdxT)
end
function MOI.set(mock::MockOptimizer,
                 attr::MOI.VariableName,
                 index::MOI.VariableIndex, value)
    if mock.supports_names
        MOI.set(mock.inner_model, attr, xor_index(index), value)
    else
        throw_mock_unsupported_names(attr)
    end
end
function MOI.supports(mock::MockOptimizer, attr::MOI.ConstraintName,
                      IdxT::Type{<:MOI.ConstraintIndex})
    return mock.supports_names && MOI.supports(mock.inner_model, attr, IdxT)
end
function MOI.set(mock::MockOptimizer,
                 attr::MOI.ConstraintName,
                 index::MOI.ConstraintIndex, value)
    if mock.supports_names
        MOI.set(mock.inner_model, attr, xor_index(index), value)
    else
        throw_mock_unsupported_names(attr)
    end
end
function MOI.get(b::MockOptimizer, IdxT::Type{<:MOI.Index}, name::String)
    index = MOI.get(b.inner_model, IdxT, name)
    if index === nothing
        return nothing
    else
        return xor_index(index)
    end
end

#####
##### Results
#####

MOI.get(mock::MockOptimizer, ::MOI.ResultCount) = mock.result_count
MOI.set(mock::MockOptimizer, ::MOI.ResultCount, x) = (mock.result_count = x)

MOI.get(mock::MockOptimizer, ::MOI.TerminationStatus) = mock.terminationstatus
function MOI.get(mock::MockOptimizer, attr::MOI.ObjectiveValue)
    MOI.check_result_index_bounds(mock, attr)
    if mock.eval_objective_value
        return get_fallback(mock, attr)
    else
        return mock.objective_value
    end
end
function MOI.get(mock::MockOptimizer, attr::MOI.DualObjectiveValue)
    MOI.check_result_index_bounds(mock, attr)
    if mock.eval_dual_objective_value
        return get_fallback(mock, attr, Float64)
    else
        return mock.dual_objective_value
    end
end
function MOI.get(mock::MockOptimizer, attr::MOI.PrimalStatus)
    if attr.N > mock.result_count
        return MOI.NO_SOLUTION
    else
        return mock.primalstatus
    end
end
function MOI.get(mock::MockOptimizer, attr::MOI.DualStatus)
    if attr.N > mock.result_count
        return MOI.NO_SOLUTION
    else
        return mock.dualstatus
    end
end
MOI.get(mock::MockOptimizer, ::MockModelAttribute) = mock.attribute

function MOI.get(mock::MockOptimizer, attr::MOI.AbstractVariableAttribute,
                 idx::MOI.VariableIndex)
    return xor_indices(MOI.get(mock.inner_model, attr, xor_index(idx)))
end
MOI.get(mock::MockOptimizer, ::MockVariableAttribute, idx::MOI.VariableIndex) = mock.varattribute[xor_index(idx)]

function MOI.get(
    mock::MockOptimizer, attr::MOI.VariablePrimal, idx::MOI.VariableIndex
)
    MOI.check_result_index_bounds(mock, attr)
    primal = get(mock.varprimal, xor_index(idx), nothing)
    if primal !== nothing
        return primal
    elseif MOI.is_valid(mock, idx)
        error("No mock primal is set for variable `", idx, "`.")
    else
        throw(MOI.InvalidIndex(idx))
    end
end

function MOI.get(
    mock::MockOptimizer, attr::MOI.CallbackVariablePrimal, idx::MOI.VariableIndex
)
    primal = get(mock.callback_variable_primal, xor_index(idx), nothing)
    if primal !== nothing
        return primal
    elseif MOI.is_valid(mock, idx)
        error("No mock callback primal is set for variable `", idx, "`.")
    else
        throw(MOI.InvalidIndex(idx))
    end
end

function MOI.get(
    mock::MockOptimizer, attr::MOI.ConstraintPrimal, idx::MOI.ConstraintIndex
)
    MOI.check_result_index_bounds(mock, attr)
    return get_fallback(mock, attr, idx)
end

function MOI.get(mock::MockOptimizer, attr::MOI.AbstractConstraintAttribute,
                 idx::MOI.ConstraintIndex)
    # If it is thrown by `mock.inner_model`, the index will be xor'ed.
    MOI.throw_if_not_valid(mock, idx)
    return MOI.get(mock.inner_model, attr, xor_index(idx))
end
function MOI.get(mock::MockOptimizer, attr::MOI.ConstraintFunction,
                 idx::MOI.ConstraintIndex)
    # If it is thrown by `mock.inner_model`, the index will be xor'ed.
    MOI.throw_if_not_valid(mock, idx)
    return xor_indices(MOI.get(mock.inner_model, attr, xor_index(idx)))
end

function MOI.get(
    mock::MockOptimizer, attr::MOI.ConstraintDual, idx::MOI.ConstraintIndex{F}
) where {F}
    MOI.check_result_index_bounds(mock, attr)
    if mock.eval_variable_constraint_dual &&
        (F == MOI.SingleVariable || F == MOI.VectorOfVariables)
        return get_fallback(mock, attr, idx)
    else
        dual = get(mock.condual, xor_index(idx), nothing)
        if dual === nothing
            if MOI.is_valid(mock, idx)
                error("No mock dual is set for constraint `", idx, "`.")
            else
                throw(MOI.InvalidIndex(idx))
            end
        end
        return dual
    end
end
MOI.get(mock::MockOptimizer, ::MockConstraintAttribute, idx::MOI.ConstraintIndex) = mock.conattribute[xor_index(idx)]
MOI.get(mock::MockOptimizer, ::MOI.ConstraintBasisStatus, idx::MOI.ConstraintIndex) = mock.con_basis[xor_index(idx)]

MOI.get(::MockOptimizer, ::MOI.SolverName) = "Mock"

function MOI.empty!(mock::MockOptimizer)
    MOI.empty!(mock.inner_model)
    mock.attribute = 0
    empty!(mock.varattribute)
    empty!(mock.conattribute)
    mock.solved = false
    mock.hasprimal = false
    mock.hasdual = false
    mock.terminationstatus = MOI.OPTIMIZE_NOT_CALLED
    mock.objective_value = NaN
    mock.dual_objective_value = NaN
    mock.primalstatus = MOI.NO_SOLUTION
    mock.dualstatus = MOI.NO_SOLUTION
    empty!(mock.varprimal)
    empty!(mock.callback_variable_primal)
    empty!(mock.condual)
    empty!(mock.con_basis)
    empty!(mock.optimizer_attributes)
    empty!(mock.model_attributes)
    empty!(mock.submitted)
    return
end

function MOI.is_empty(mock::MockOptimizer)
    # Assumes that variable and constraint attributes can't be set if
    # mock.inner_model is empty.
    # TODO: Default values are currently copied in three places, not good.
    return MOI.is_empty(mock.inner_model) && mock.attribute == 0 &&
        !mock.solved && !mock.hasprimal && !mock.hasdual &&
        mock.terminationstatus == MOI.OPTIMIZE_NOT_CALLED &&
        isnan(mock.objective_value) &&
        isnan(mock.dual_objective_value) &&
        mock.primalstatus == MOI.NO_SOLUTION &&
        mock.dualstatus == MOI.NO_SOLUTION &&
        isempty(mock.con_basis) && isempty(mock.optimizer_attributes) &&
        isempty(mock.model_attributes) && isempty(mock.submitted)
end

MOI.is_valid(mock::MockOptimizer, idx::MOI.Index) = MOI.is_valid(mock.inner_model, xor_index(idx))

function MOI.delete(mock::MockOptimizer, index::MOI.VariableIndex)
    if !mock.delete_allowed
        throw(MOI.DeleteNotAllowed(index))
    end
    if !MOI.is_valid(mock, index)
        # The index thrown by `mock.inner_model` would be xored
        throw(MOI.InvalidIndex(index))
    end
    MOI.delete(mock.inner_model, xor_index(index))
    delete!(mock.varprimal, index)
    delete!(mock.callback_variable_primal, index)
end
function MOI.delete(mock::MockOptimizer, indices::Vector{MOI.VariableIndex})
    if !mock.delete_allowed && !isempty(indices)
        throw(MOI.DeleteNotAllowed(first(indices)))
    end
    for index in indices
        # The index thrown by `mock.inner_model` would be xored
        MOI.throw_if_not_valid(mock, index)
    end
    MOI.delete(mock.inner_model, xor_index.(indices))
    for index in indices
        delete!(mock.varprimal, index)
        delete!(mock.callback_variable_primal, index)
    end
end
function MOI.delete(mock::MockOptimizer, index::MOI.ConstraintIndex)
    if !mock.delete_allowed
        throw(MOI.DeleteNotAllowed(index))
    end
    if !MOI.is_valid(mock, index)
        # The index thrown by `mock.inner_model` would be xored
        throw(MOI.InvalidIndex(index))
    end
    MOI.delete(mock.inner_model, xor_index(index))
    delete!(mock.condual, index)
    delete!(mock.con_basis, index)
end

function MOI.modify(mock::MockOptimizer, c::CI, change::MOI.AbstractFunctionModification)
    if !mock.modify_allowed
        throw(MOI.ModifyConstraintNotAllowed(c, change))
    end
    MOI.modify(mock.inner_model, xor_index(c), xor_indices(change))
end

function MOI.set(mock::MockOptimizer, ::MOI.ConstraintSet,
                 c::CI{<:MOI.AbstractFunction, S},
                 set::S) where S<:MOI.AbstractSet
    MOI.set(mock.inner_model, MOI.ConstraintSet(), xor_index(c), set)
end
function MOI.set(mock::MockOptimizer, ::MOI.ConstraintFunction, c::CI{F},
                 func::F) where F<:MOI.AbstractFunction
    MOI.set(mock.inner_model, MOI.ConstraintFunction(), xor_index(c),
            xor_indices(func))
end

function MOI.modify(mock::MockOptimizer, obj::MOI.ObjectiveFunction, change::MOI.AbstractFunctionModification)
    if !mock.modify_allowed
        throw(MOI.ModifyObjectiveNotAllowed(change))
    end
    MOI.modify(mock.inner_model, obj, xor_indices(change))
end

MOI.supports(::MockOptimizer, ::MOI.AbstractSubmittable) = true
function MOI.submit(mock::MockOptimizer, sub::MOI.AbstractSubmittable, args...)
    if !haskey(mock.submitted, sub)
        mock.submitted[sub] = Tuple[]
    end
    push!(mock.submitted[sub], args)
end

# TODO: transform

MOI.supports_constraint(mock::MockOptimizer, F::Type{<:MOI.AbstractFunction}, S::Type{<:MOI.AbstractSet}) = MOI.supports_constraint(mock.inner_model, F, S)
function MOI.copy_to(mock::MockOptimizer, src::MOI.ModelLike; kws...)
    automatic_copy_to(mock, src; kws...)
end
function supports_default_copy_to(mock::MockOptimizer, copy_names::Bool)
    return !mock.needs_allocate_load && supports_default_copy_to(mock.inner_model, copy_names)
end

# Allocate-Load Interface
function supports_allocate_load(mock::MockOptimizer, copy_names::Bool)
    return supports_allocate_load(mock.inner_model, copy_names)
end

function allocate_variables(mock::MockOptimizer, nvars)
    return xor_index.(allocate_variables(mock.inner_model, nvars))
end
allocate(mock::MockOptimizer, attr::MOI.AnyAttribute, value) = allocate(mock.inner_model, attr, xor_indices(value))
allocate(mock::MockOptimizer, attr::MOI.AnyAttribute, idx::MOI.Index, value) = allocate(mock.inner_model, attr, xor_index(idx), xor_indices(value))
allocate_constraint(mock::MockOptimizer, f::MOI.AbstractFunction, s::MOI.AbstractSet) = xor_index(allocate_constraint(mock.inner_model, xor_indices(f), s))

load_variables(mock::MockOptimizer, nvars) = load_variables(mock.inner_model, nvars)
load(mock::MockOptimizer, attr::MOI.AnyAttribute, value) = load(mock.inner_model, attr, xor_indices(value))
load(mock::MockOptimizer, attr::MOI.AnyAttribute, idx::MOI.Index, value) = load(mock.inner_model, attr, xor_index(idx), xor_indices(value))
load_constraint(mock::MockOptimizer, ci::CI, f::MOI.AbstractFunction, s::MOI.AbstractSet) = load_constraint(mock.inner_model, xor_index(ci), xor_indices(f), s)

"""
    set_mock_optimize!(mock::MockOptimizer, opt::Function...)

Sets multiple optimize! function. The first is to be used the first time `MOI.optimize!(mock)` is called, the second function is to be used the second time, ...
"""
function set_mock_optimize!(mock::MockOptimizer, opts::Function...)
    mock.optimize! = rec_mock_optimize(mock, opts...)
end
function rec_mock_optimize(mock::MockOptimizer, opt::Function, opts::Function...)
    (mock::MockOptimizer) -> (opt(mock); mock.optimize! = rec_mock_optimize(mock, opts...))
end
rec_mock_optimize(mock::MockOptimizer, opt::Function) = opt

"""
    mock_optimize!(mock::MockOptimizer, termstatus::MOI.TerminationStatusCode, (primstatus::MOI.ResultStatusCode, varprim::Vector), dualstatus::MOI.ResultStatusCode, conduals::Pair...)

Sets the termination status of `mock` to `termstatus` and the primal (resp. dual) status to `primstatus` (resp. `dualstatus`).
The primal values of the variables in the order returned by `ListOfVariableIndices` are set to `varprim`.
If `termstatus` is missing, it is assumed to be `MOI.OPTIMAL`.
If `primstatus` is missing, it is assumed to be `MOI.FEASIBLE_POINT`.
If `dualstatus` is missing, it is assumed to be `MOI.FEASIBLE_POINT` if there is a primal solution and `primstatus` is not `MOI.INFEASIBLE_POINT`, otherwise it is `MOI.INFEASIBILITY_CERTIFICATE`.
The dual values are set to the values specified by `conduals`. Each pair is of the form `(F,S)=>[...]` where `[...]` is the the vector of dual values for the constraints `F`-in-`S` in the order returned by `ListOfConstraintIndices{F,S}`.
The bases status are set to the status specified by `con_basis`. A vector of pairs, each of the form `(F,S)=>[...]`, where `[...]` is the the vector of basis status for the constraints `F`-in-`S` in the order returned by `ListOfConstraintIndices{F,S}`.
"""
function mock_optimize!(mock::MockOptimizer, termstatus::MOI.TerminationStatusCode, primal, dual...; con_basis = [])
    MOI.set(mock, MOI.TerminationStatus(), termstatus)
    MOI.set(mock, MOI.ResultCount(), 1)
    mock_primal!(mock, primal)
    mock_dual!(mock, dual...)
    for con_basis_pair in con_basis
        mock_basis_status!(mock, con_basis_pair)
    end
end
# Default termination status
mock_optimize!(mock::MockOptimizer, primdual...; kws...) = mock_optimize!(mock, MOI.OPTIMAL, primdual...; kws...)
function mock_optimize!(mock::MockOptimizer, termstatus::MOI.TerminationStatusCode)
    MOI.set(mock, MOI.TerminationStatus(), termstatus)
    MOI.set(mock, MOI.ResultCount(), 0)
end

# Primal
mock_primal!(mock, primal::Tuple) = mock_primal!(mock, primal...)
function mock_primal!(mock::MockOptimizer, primstatus::MOI.ResultStatusCode, varprim::Vector...)
    MOI.set(mock, MOI.PrimalStatus(), primstatus)
    mock_varprimal!(mock, varprim...)
end
# Default primal status
mock_primal!(mock::MockOptimizer, varprim::Vector) = mock_primal!(mock, MOI.FEASIBLE_POINT, varprim)
function mock_primal!(mock::MockOptimizer)
    # No primal solution
    mock.hasprimal = false
end

# Sets variable primal to varprim
function mock_varprimal!(mock::MockOptimizer) end
function mock_varprimal!(mock::MockOptimizer, varprim::Vector)
    MOI.set(mock, MOI.VariablePrimal(), MOI.get(mock, MOI.ListOfVariableIndices()), varprim)
end

# Dual
function mock_dual!(mock::MockOptimizer, dualstatus::MOI.ResultStatusCode, conduals::Pair...)
    MOI.set(mock, MOI.DualStatus(), dualstatus)
    mock_condual!(mock, conduals...)
end
# Default dual status
function mock_dual!(mock::MockOptimizer, conduals::Pair...)
    status = !mock.hasprimal || MOI.get(mock, MOI.PrimalStatus()) == MOI.INFEASIBLE_POINT ? MOI.INFEASIBILITY_CERTIFICATE : MOI.FEASIBLE_POINT
    mock_dual!(mock, status, conduals...)
end
function mock_dual!(mock::MockOptimizer)
    # No dual solution
    mock.hasdual = false
end

# Sets constraint dual to conduals
function mock_condual!(mock::MockOptimizer) end
function mock_condual!(mock::MockOptimizer, condual::Pair, conduals...)
    F, S = condual.first
    duals = condual.second
    for (i, ci) in enumerate(MOI.get(mock, MOI.ListOfConstraintIndices{F, S}()))
        MOI.set(mock, MOI.ConstraintDual(), ci, duals[i])
    end
    mock_condual!(mock, conduals...)
end
# Set the basis status of the provided constraints.
function mock_basis_status!(mock::MockOptimizer, con_basis::Pair)
    F, S = con_basis.first
    bases = con_basis.second
    for (i, ci) in enumerate(MOI.get(mock, MOI.ListOfConstraintIndices{F, S}()))
        MOI.set(mock, MOI.ConstraintBasisStatus(), ci, bases[i])
    end
end


text:
function build_parameter_space{T <: ScreenSetup}(::T, parameters::Dict{Symbol, Vector}, num_runs::Int)
    fields = collect(keys(parameters))
    n_fields = length(fields)
    runs = []
    for vals in IterTools.product([parameters[field] for field in fields]...)
        for run in 1:num_runs
            setup = T()
            for idx in 1:n_fields
                setfield!(setup, fields[idx], vals[idx])
            end
            push!(runs, (setup, run))
        end
    end
    runs
end

function build_parameter_space{T <: ScreenSetup}(::T, parameters::Dict{Symbol, Vector},
                                                 libs::Vector{Library}, num_runs::Int)
    fields = collect(keys(parameters))
    n_fields = length(fields)
    runs = []
    for vals in IterTools.product([parameters[field] for field in fields]...)
        for lib in libs
            for run in 1:num_runs
                setup = T()
                for idx in 1:n_fields
                    setfield!(setup, fields[idx], vals[idx])
                end
                push!(runs, (setup, lib, run))
            end
        end
    end
    runs
end

function grouped_param_space{T <: ScreenSetup}(::T, parameters::Dict{Symbol, Vector},
                                               libs::Vector{Library},
                                               dists::Vector{Symbol}, num_runs::Int)
    fields = collect(keys(parameters))
    n_fields = length(fields)
    deleteat!(fields, findin(fields, dists))
    runs = []
    grouped_params = zip([parameters[field] for field in fields]...)
    (length(dists) > 0) && push!(fields, dists...)
    for vals in IterTools.product(grouped_params, [parameters[dist] for dist in dists]...)
        vals = Any[vals[1]...; [vals[i+1] for i in 1:length(dists)]...]
        for lib in libs
            for run in 1:num_runs
                setup = T()
                for idx in 1:n_fields
                    setfield!(setup, fields[idx], vals[idx])
                end
                push!(runs, (setup, lib, run))
            end
        end
    end
    runs
end

function grouped_param_space{T <: ScreenSetup}(::T, parameters::Dict{Symbol, Vector}, dists::Vector{Symbol}, num_runs::Int)
    fields = collect(keys(parameters))
    n_fields = length(fields)
    deleteat!(fields, findin(fields, dists))
    runs = []
    grouped_params = zip([parameters[field] for field in fields]...)
    (length(dists) > 0) && push!(fields, dists...)
    for vals in IterTools.product(grouped_params, [parameters[dist] for dist in dists]...)
        vals = Any[vals[1]...; [vals[i+1] for i in 1:length(dists)]...]
        for run in 1:num_runs
            setup = T()
            for idx in 1:n_fields
                setfield!(setup, fields[idx], vals[idx])
            end
            push!(runs, (setup, run))
        end
    end
    runs
end

@everywhere function test_methods(genes, methods, measures, genetypes)
    local results = []
    for (method, measure, genetype) in IterTools.product(methods, measures, genetypes)
        if genetype != :all
            subgene = genes[genes[:behavior] .== genetype, :]
        else
            subgene = genes
        end
        local result = 0.0
        if measure == :incdec
            result = method(abs.(subgene[:pvalmeanprod_bin2_div_bin1]), subgene[:class], Set([:increasing, :decreasing]))
        elseif measure == :dec
            result = method(subgene[:pvalmeanprod_bin2_div_bin1], subgene[:class], Set([:decreasing]), rev=false)
        else
            result = method(subgene[:pvalmeanprod_bin2_div_bin1], subgene[:class], Set([:increasing]))
        end
        (typeof(result) <: Tuple) && (result = result[1])
        push!(results, result)
    end
    (results...)
end

@everywhere function test_methods_snr(bc_counts, genes, methods, measures, genetypes)
    (test_methods(genes, methods, measures, genetypes)..., signal(bc_counts), noise(bc_counts))
end

@everywhere function compute_snr(bc_counts::DataFrame, genes::DataFrame)
    sig, noi = signal(bc_counts), noise(bc_counts)
    (sig/noi, sig, noi)
end

function compute_name(filename::AbstractString)
    front, back = splitext(filename)
    # commit of the code that generated this data
    commit = strip(readstring(`git rev-parse --short HEAD`))
    # whether there are any uncommitted changes
    n = length(split(readstring(`git status --porcelain`), "\n"))
    status = n > 1 ? "dirty" : "clean"
    string(join([front; commit; status], "_"), back)
end

"""
construct_hierarchical_label(hierarchy::Array{Symbol, 2}, df::DataFrame, renames::Vector{Symbol})

Creates a hierarchical index in the given dataframe
"""
function construct_hierarchical_label(hierarchy::Array{Symbol, 2}, df::DataFrame, renames::Vector{Symbol})
    procs = []
    for i in 1:size(hierarchy, 1)
        row_labels = repeat(hierarchy[i:i, :], inner=[size(df, 1), 1])
        data = DataFrame(hcat(row_labels, df[i], Array(df[size(hierarchy, 1)+1:end])))
        names!(data, renames)
        push!(procs, data)
    end
    vcat(procs...)
end


text:
using ITensorMPOCompression
using Revise
using Test

function test_auto_vs_direct(sites,NNN::Int64,hx::Float64,Eexpected::Float64,eps::Float64)
    #
    #  Use autoMPO to make H
    #
    Hauto=make_transIsing_AutoMPO(sites,NNN,hx,lower) #make and MPO only to get the indices
    Eauto,psi=fast_GS(Hauto,sites)
    @test abs(Eauto-Eexpected)<eps
    Eauto1=inner(psi',Hauto,psi)
    @test abs(Eauto1-Eexpected)<eps

    #
    #  Make H directly ... should be lower triangular
    #
    Hdirect=make_transIsing_MPO(sites,NNN,hx,lower) #defaults to lower reg form
    @test order(Hdirect[1])==3
    @test abs(inner(psi',Hdirect,psi)-Eexpected)<eps
    Edirect,psidirect=fast_GS(Hdirect,sites)
    @test abs(Edirect-Eexpected)<eps
    overlap=abs(inner(psi',psidirect))
    @test abs(overlap-1.0)<eps
end

#using Printf
#Base.show(io::IO, f::Float64) = @printf(io, "%1.16f", f)
#println("-----------Start--------------")

@testset "MPOs with periodic boundary conditions" begin

    N=5
    hx=0.5
    eps=4e-14 #this is right at the lower limit for passing the tests.
    sites = siteinds("SpinHalf", N;conserve_qns=false)

    # It seems we need to jump through hoops to avoid the
    # "type Dense has no field blockoffsets" from inside DMRG errors
    # I tried to move these disables inside fast_GS with no success?!?!?
    db=ITensors.using_debug_checks()
    if db  ITensors.ITensors.disable_debug_checks() end
    test_auto_vs_direct(sites,1,hx,-1.5066685458330529,eps) #1st neighbour interactions
    test_auto_vs_direct(sites,2,hx,-1.4524087749432490,eps) #1&2 neighbour interactions
    test_auto_vs_direct(sites,3,hx,-1.4516941302867301,eps) #1->3 neighbour interactions
    test_auto_vs_direct(sites,4,hx,-1.4481111362390489,eps) #1->4 neighbour interactions
    if db  ITensors.ITensors.enable_debug_checks() end
end


text:
function VectorToList(args)
    res = []
    for t in args
        res = vcat(res, t)
    end
    return res
end
function myzip(xs, ys)
    n = min(length(xs),length(ys))
    return map(i->(xs[i],ys[i]), [i for i in 1:n])
end
function myunzip(xys)
    xs = map(pair -> pair[1], xys)
    ys = map(pair -> pair[2], xys)
    return xs,ys
end
function makeInterval(xstart, xend, stepp = 0.01)
    return [x for x in xstart:stepp:xend]
end

max_stars_repo_path: II rok/I semestr/ANM/Pracownia 2/prog/funkcje.jl

max_stars_repo_name: antonitomaszewski/Studia

max_issues_repo_name: antonitomaszewski/Studia

max_forks_repo_name: antonitomaszewski/Studia


text:
#=
animation_2d:
- Julia version: 1.5.0
- Author: shisa
- Date: 2020-08-12
=#

module Anime2D
    # packages
    using PyPlot: plt
    using PyCall
    @pyimport PIL.Image as Image

    # flag to switch show or not
    show_plot = true

    # methods
    function set_show_plot(flag)
        global show_plot = flag
    end

    function create_gif(im_num)
        images = []
        if im_num > 0
            for num in 1:im_num
                im_name = string(num, ".png")
                im = Image.open(im_name)
                push!(images, im)
            end
            images[1].save("animation_2d_sample.gif",
                            save_all=true,
                            append_images=images[1:end],
                            loop=0,
                            duration=60)
        end
    end

    function delete_png(im_num)
        if im_num > 0
            for num in 1:im_num
                im_name = string(num, ".png")
                rm(im_name)
            end
        end
    end

    function main()
        # data
        x = range(0, 2pi, length=100)
        y = sin.(x)

        im_num = 0

        # figure
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        pxy, = ax.plot([], [], ".", c="b", ms=10)
        ax.set_xlabel("X")
        ax.set_ylabel("Y")
        ax.set_xlim([0.0, 7.0])
        ax.set_ylim([-1.0, 1.0])
        ax.grid(true)

        # animation
        for i in 1:length(x)
            if show_plot == true
                pxy.set_data(x[1:i], y[1:i])
                im_num += 1
                plt.savefig(string(im_num, ".png"))
                plt.pause(0.001)
            end
        end

        create_gif(im_num)

        delete_png(im_num)

        if show_plot == true
            plt.show()
        end
    end
end

if abspath(PROGRAM_FILE) == @__FILE__
    using .Anime2D
    Anime2D.main()
end

max_stars_repo_name: ShisatoYano/JuliaPractice

max_issues_repo_name: ShisatoYano/JuliaPractice

max_forks_repo_name: ShisatoYano/JuliaPractice


text:
using DataFrames
using DecisionTree
using JLD

# Load our model.
model = load(ARGS[1], "model")

# Walk over the directory with input attribute files.
attributes = readdir(ARGS[2])
for file in attributes
  p = joinpath(ARGS[2], file)
  if isdir(p)
    continue
  elseif isfile(p)
    df = readtable(p, header = false)
    open(joinpath(ARGS[3], file), "a") do x
      for r in eachrow(df)
        prediction = DecisionTree.predict(model, convert(Array, r))
        write(x, string(prediction[1], "\n"))
      end
    end
  end
end

max_stars_repo_name: carlsonp/pachyderm

max_issues_repo_name: carlsonp/pachyderm

max_forks_repo_name: carlsonp/pachyderm


text:
using Plots
using Zygote
using LaTeXStrings

vecindario(;x₀, ϵ=2.0, Δ=0.05) = x₀ - ϵ:Δ:x₀ + ϵ

f(x) = sin(5x) - cos(3x)

x₀ = 10
x = vecindario(x₀=x₀);

f₁ = f'(x₀)
f₂ = f''(x₀)

y = f.(x);
y = hcat(y, ones(length(y)) .* f(x₀))
y = hcat(y, @. y[:, end] + (x - x₀) * f₁)
y = hcat(y, @. y[:, end] + (x - x₀)^2 * f₂)

gr(size=(800, 800))
p = plot(x, y[:,1], label=L"f(x)")
plot!(p, x, y[:,2], label="Orden cero")
plot!(p, x, y[:,3], label="Primer orden")
plot!(p, x, y[:,4], label="Segundo orden")
plot!(p, [x₀], [f(x₀)], mark=:cirle, label=L"x_0")
title!("Aproximación por series de Taylor")
xlabel!(p, L"x")
ylabel!(p, L"f(x)")
xlims!(p, (x[1], x[end]))

savefig(p, "Taylor_borrar.png")


text:
# CauchyWeight enriches a TensorSpace with a singular diagonal

export CauchyWeight

immutable CauchyWeight{O,SV,T} <: AbstractProductSpace{SV,T,2}
    space::TensorSpace{SV,T,2}
end

CauchyWeight{SV,T}(space::TensorSpace{SV,T,2},O) = CauchyWeight{O,SV,T}(space)

order{O}(C::CauchyWeight{O}) = O
domain(C::CauchyWeight) = domain(C.space)
Base.getindex(C::CauchyWeight,k::Integer) = C.space[k]
ApproxFun.columnspace(C::CauchyWeight,::) = C[1]
Base.getindex{O,PWS1<:PiecewiseSpace,PWS2<:PiecewiseSpace}(C::CauchyWeight{O,Tuple{PWS1,PWS2}},i,j) =
    CauchyWeight(C.space[i,j],O)
Base.transpose{O}(C::CauchyWeight{O}) = CauchyWeight(transpose(C.space),O)

cauchyweight(O,x,y) = O == 0 ? logabs(y-x)/π : (y-x).^(-O)/π
cauchyweight{O}(C::CauchyWeight{O},x,y) = cauchyweight(O,tocanonical(C,x,y)...)

## BivariateFun constructors in a CauchyWeight space

## TODO: for different domains, there should not be (x,y)->f(x,y)*cauchyweight(O,x,y)
## This will change for v0.0.2 with the switch to ChebyshevDirichlet{1,1} bases

for Func in (:ProductFun,:convolutionProductFun)
    @eval begin
        function $Func{O}(f::Function,cwsp::CauchyWeight{O};kwds...)
            F = domain(cwsp[1]) == domain(cwsp[2]) ? $Func(f,cwsp[1],cwsp[2];kwds...) : $Func((x,y)->f(x,y)*cauchyweight(O,x,y),cwsp[1],cwsp[2];kwds...)
            return ProductFun(F.coefficients,cwsp)
        end
    end
end

function LowRankFun{O}(f::Function,cwsp::CauchyWeight{O};retmax::Bool=false,kwds...)
    if retmax
        F,maxabsf = domain(cwsp[1]) == domain(cwsp[2]) ? LowRankFun(f,cwsp[1],cwsp[2];retmax=retmax,kwds...) : LowRankFun((x,y)->f(x,y)*cauchyweight(O,x,y),cwsp[1],cwsp[2];retmax=retmax,kwds...)
        LowRankFun(F.A,F.B,cwsp),maxabsf
    else
        F = domain(cwsp[1]) == domain(cwsp[2]) ? LowRankFun(f,cwsp[1],cwsp[2];kwds...) : LowRankFun((x,y)->f(x,y)*cauchyweight(O,x,y),cwsp[1],cwsp[2];kwds...)
        LowRankFun(F.A,F.B,cwsp)
    end
end

## Definite (Line) Integration over BivariateFuns in a CauchyWeight space

## TODO: for different domains, should be OffOp instead of ⨍
## This will change for v0.0.2 with the switch to ChebyshevDirichlet{1,1} bases

for (Func,Op) in ((:(ApproxFun.DefiniteIntegral),:Hilbert),
                    (:(ApproxFun.DefiniteLineIntegral),:SingularIntegral))
    @eval begin
        function Base.getindex{S,V,O,T,V1,T1,T2}(⨍::$Func{V1,T1},f::ProductFun{S,V,CauchyWeight{O,Tuple{S,V},T2},T})
            if domain(f.space[1]) == domain(f.space[2])
                $Op(domainspace(⨍),O)[f]
            else
                ⨍[ProductFun(f.coefficients,f.space.space)]
            end
        end
        function Base.getindex{S,M,O,T,V1,T1,T2}(⨍::$Func{V1,T1},f::LowRankFun{S,M,CauchyWeight{O,Tuple{S,M},T2},T})
            if domain(f.space[1]) == domain(f.space[2])
                $Op(domainspace(⨍),O)[f]
            else
                ⨍[LowRankFun(f.A,f.B,f.space.space)]
            end
        end
    end
end

## Evaluation of bivariate functions in a CauchyWeight space

evaluate{S<:UnivariateSpace,V<:UnivariateSpace,O,T1,T2}(f::ProductFun{S,V,CauchyWeight{O,Tuple{S,V},T1},T2},x::Range,y::Range) = evaluate(f,[x],[y])
evaluate{S<:UnivariateSpace,V<:UnivariateSpace,O,T1,T2}(f::ProductFun{S,V,CauchyWeight{O,Tuple{S,V},T1},T2},x,y) = evaluate(ProductFun(f.coefficients,space(f).space),x,y).*cauchyweight(space(f),x,y)

+{S<:UnivariateSpace,V<:UnivariateSpace,O,T1,T2}(F::ProductFun{S,V,CauchyWeight{O},T1},G::ProductFun{S,V,CauchyWeight{O},T2}) = ProductFun(ProductFun(F.coefficients,F.space.space)+ProductFun(G.coefficients,G.space.space),G.space)
-{S<:UnivariateSpace,V<:UnivariateSpace,O,T1,T2}(F::ProductFun{S,V,CauchyWeight{O},T1},G::ProductFun{S,V,CauchyWeight{O},T2}) = ProductFun(ProductFun(F.coefficients,F.space.space)-ProductFun(G.coefficients,G.space.space),G.space)

evaluate{S<:Space,M<:Space,O,SV,TT,T<:Number}(f::LowRankFun{S,M,CauchyWeight{O,SV,TT},T},::Colon,::Colon) = error("Not callable.")
evaluate{S<:Space,M<:Space,O,SV,TT,T<:Number}(f::LowRankFun{S,M,CauchyWeight{O,SV,TT},T},x::Number,::Colon) = error("Not callable.")
evaluate{S<:Space,M<:Space,O,SV,TT,T<:Number,TTT<:Number}(f::LowRankFun{S,M,CauchyWeight{O,SV,TT},T},x::Vector{TTT},::Colon) = error("Not callable.")
evaluate{S<:Space,M<:Space,O,SV,TT,T<:Number}(f::LowRankFun{S,M,CauchyWeight{O,SV,TT},T},::Colon,y::Number) = error("Not callable.")
evaluate{S<:Space,M<:Space,O,SV,TT,T<:Number,TTT<:Number}(f::LowRankFun{S,M,CauchyWeight{O,SV,TT},T},::Colon,y::Vector{TTT}) = error("Not callable.")
evaluate{S<:Space,M<:Space,O,SV,TT,T<:Number}(f::LowRankFun{S,M,CauchyWeight{O,SV,TT},T},x,y) = evaluate(f.A,f.B,x,y).*cauchyweight(space(f),x,y)

+{S<:Space,M<:Space,O,T1<:Number,T2<:Number}(F::LowRankFun{S,M,CauchyWeight{O},T1},G::LowRankFun{S,M,CauchyWeight{O},T2}) = LowRankFun([F.A,G.A],[F.B,G.B],F.space)
-{S<:Space,M<:Space,O,T1<:Number,T2<:Number}(F::LowRankFun{S,M,CauchyWeight{O},T1},G::LowRankFun{S,M,CauchyWeight{O},T2}) = LowRankFun([F.A,-G.A],[F.B,G.B],F.space)


text:
# Range: 1 : 100,000
# Time:  14m26.060s

# Written by Alex Vear in 2019
# Public domain.  No rights reserved.

startval = 1
endval = 100000

for num in startval:endval
  sqr = 2(num^2)
  for i in startval:endval
    tri = i*(i+1)
    if sqr == tri
      sqr = sqr/2
      tri = tri/2
      println("Square Number: $sqr Triangle Number: $tri Squared: $num Triangled: $i")
    end
  end
end

max_stars_repo_name: axvr/codedump

max_issues_repo_name: axvr/codedump

max_forks_repo_name: axvr/codedump


text:
function Allreduce(src::Number, op, comm::Comm)
    src_arr = [src]
    Allreduce!(src_arr, +, comm)
    return src_arr[1]
end

Allreduce!(dst::A, op, comm::Comm) where {T, A<:DenseArray{T}} =
    Allreduce!(dst, dst, op, comm)

function Allreduce!(dst::A, src::A, op, comm::Comm) where {T, A<:DenseArray{T}}
    id = Comm_rank(comm)

    sz = size(src)

    if id == 1
        # pass to the other threads the dst (reduced array)
        comm.passthrough[id] = convert(UInt, pointer(dst))

        dst !== src && copyto!(dst, src)

        # wait for everyone to have written their data
        sync(comm.barrier)

        # sum everything in place
        for (t_id, addr) in enumerate(comm.passthrough)
            t_id == id && continue

            ptr = convert(Ptr{T}, addr)
            arr = UnsafeArray(ptr, sz)
            broadcast!(op, dst, dst, arr)
        end

        sync(comm.barrier)
    else
        # pass to the master thread the src array
        comm.passthrough[id] = convert(UInt, pointer(src))

        # report to thread 1 that you set the pointer
        sync(comm.barrier)

        # wait for thread 1 to compute the sum
        sync(comm.barrier)

        ptr = convert(Ptr{T}, comm.passthrough[1])
        arr = UnsafeArray(ptr, sz)
        copyto!(dst, arr)

    end

    sync(comm.barrier)
    return dst
end

Allgatherv!(dst::A, counts, comm::Comm) where {T, A<:DenseArray{T}} =
     Allgatherv!(dst, dst, counts, comm)

function Allgatherv!(dst::A, src::B, counts, comm::Comm) where {T, A<:DenseArray{T}, B<:DenseArray{T}}
    sz = length(dst)
    id = Comm_rank(comm)

    sum(counts) <= length(dst) || throw(error("Destination buffer too small"))

    # Share among all threads the destination pointer
    comm.passthrough[id] = convert(UInt, pointer(dst))
    sync(comm.barrier)

    # Compute the offset to write to in the destination
    Δ = 1
    for i=1:id-1
        Δ += counts[i]
    end

    Δ_src = 1
    if src === dst
        Δ_src = Δ
    end

    # Write
    for (i, addr) in enumerate(comm.passthrough)
        dst === src && i == id && continue

        ptr = convert(Ptr{T}, addr)
        dst = UnsafeArray(ptr, (length(dst), ))

        copyto!(dst, Δ, src, Δ_src, counts[id])
    end

    sync(comm.barrier)

    return dst
end


text:
include("network.jl")

struct Generator
    initial
    downblocks
    resblocks
    upblocks
    final
end

@functor Generator
function Generator(
    in_channels::Int,
    num_features::Int = 64,
    num_residual::Int = 9,
)
return Generator(
    Chain(
        Conv((7,7), in_channels => num_features; stride=1, pad=3),
        InstanceNorm(num_features),
        x -> relu.(x)
    ),
    [
        ConvBlock(3, num_features, num_features*2, true, true;stride=2 ,pad=1),
        ConvBlock(3, num_features*2, num_features*4, true, true;stride=2 ,pad=1),
    ],
    Chain([ResidualBlock(num_features*4) for _ in range(1, length=num_residual)]...),
    [
        ConvBlock(3, num_features*4, num_features*2,true,false; stride=2 ,pad=SamePad()),
        ConvBlock(3, num_features*2, num_features,true,false; stride=2 ,pad=SamePad()),
    ],
    Conv((7,7),num_features=>in_channels; stride=1,pad=3)
)  |> gpu
end

function (net::Generator)(x)
    input = net.initial(x)
    for layer in net.downblocks
        input = layer(input)
    end
    input = net.resblocks(input)
    for layer in net.upblocks
        input = layer(input)
    end
    return tanh.(net.final(input))
end

using Random
function test()
    img_channels = 3
    img_size = 180
    ## need to explicity type to avoid Slow fallback implementation
    ## https://discourse.julialang.org/t/flux-con-warning/49456
    x = randn(Float32, (img_size, img_size, img_channels, 2))
    gen = Generator(img_channels, 9)
    println(size(gen(x)))
end

#test()


text:
@testset "LocalField" begin

  @testset "Creation" begin
    Qx, x = FlintQQ["x"]
    f = x^2-2*x+2
    K, a = local_field(f, 2, 10, "a", Hecke.EisensteinLocalField, check = false)
    @test precision(K) == 20
    @test characteristic(K) == 0
    @test prime(K) == 2

    Kt, t = PolynomialRing(K, "t")
    g = t^2+2
    L, b = local_field(g, "b", Hecke.EisensteinLocalField, check = false)
    @test precision(L) == 2*precision(g)
    @test precision(b) == precision(L)
    @test degree(L) == 2
    @test absolute_degree(L) == 4
    @test prime(L) == 2

    Q2 = PadicField(2, 10)
    Q2s, s = PolynomialRing(Q2, "s")
    f = s^2+s+1
    Ku, c = local_field(f, "s", Hecke.UnramifiedLocalField, check = false)
    @test precision(Ku) == precision(f)
    @test precision(f) == precision(c)
    @test degree(Ku) == 2
    @test absolute_degree(Ku) == 2
    @test inertia_degree(Ku) == 2
    @test ramification_index(Ku) == 1
    @test absolute_ramification_index(Ku) == 1
    @test absolute_inertia_degree(Ku) == 2

    Lu, u = PolynomialRing(L, "u")
    Lu, d = local_field(u^2+u+1, "s", Hecke.UnramifiedLocalField, check = false)
    @test absolute_degree(Lu) == 8
    @test ramification_index(Lu, K) == 2
    @test inertia_degree(Lu, K) == 2

  end

  @testset "Norm" begin
    K = QadicField(3, 4, 10)[1]
    Kx, x = PolynomialRing(K, "x")
    L = eisenstein_extension(x^20+3)[1]
    b = @inferred basis(L)
    for i = 1:10
      r = 1+2*uniformizer(L)^i * sum([rand(1:10)*b[i] for i in 1:5])
      M = @inferred representation_matrix(r)
      n = @inferred norm(r)
      @test n == det(M)
      @test trace(r) == trace(M)
    end
  end

  @testset "Completions" begin
    K, gK = cyclotomic_field(15)
    OK = maximal_order(K)
    lP = prime_decomposition(OK, 3)
    P = lP[1][1]
    Kp, mKp = @inferred Hecke.generic_completion(K, P, 100)
    @test isone(valuation(mKp\(uniformizer(Kp)), P))
    @test valuation(mKp(elem_in_nf(uniformizer(P)))) == fmpq(1, 2)
    @test valuation(mKp(gen(K)))*2 == valuation(gen(K), P)
    @test iszero(defining_polynomial(K)(mKp(gen(K))))

    P = prime_decomposition(OK, 7)[1][1]
    Kp, mKp = @inferred Hecke.unramified_completion(K, P, 100)
    @test isone(valuation(mKp\(uniformizer(Kp)), P))
    @test isone(valuation(mKp(elem_in_nf(uniformizer(P)))))
    @test valuation(mKp(gen(K))) == valuation(gen(K), P)
    @test iszero(defining_polynomial(K)(mKp(gen(K))))

    K, gK = cyclotomic_field(9)
    OK = maximal_order(K)
    lP = prime_decomposition(OK, 3)
    P = lP[1][1]
    Kp, mKp = @inferred Hecke.totally_ramified_completion(K, P, 100)
    @test valuation(mKp(elem_in_nf(uniformizer(P)))) == fmpq(1, 6)
    @test isone(valuation(mKp\(uniformizer(Kp)), P))
    @test valuation(mKp(gen(K)))*2 == valuation(gen(K), P)
    @test iszero(defining_polynomial(K)(mKp(gen(K))))

    K, gK = cyclotomic_field(55)
    OK = maximal_order(K)
    lP = prime_decomposition(OK, 11)
    P = lP[1][1]
    Kp, mKp = @inferred Hecke.generic_completion(K, P, 100)
    @test isone(valuation(mKp\(uniformizer(Kp)), P))
    @test valuation(mKp(elem_in_nf(uniformizer(P)))) == fmpq(1, 10)
    @test valuation(mKp(gen(K)))*10 == valuation(gen(K), P)
    @test iszero(defining_polynomial(K)(mKp(gen(K))))

    lP = prime_decomposition(OK, 7)
    P = lP[1][1]
    Kp, mKp = @inferred Hecke.unramified_completion(K, P, 100)
    @test isone(valuation(mKp(elem_in_nf(uniformizer(P)))))
    @test isone(valuation(mKp\(uniformizer(Kp)), P))
    @test valuation(mKp(gen(K))) == valuation(gen(K), P)
    @test iszero(defining_polynomial(K)(mKp(gen(K))))

    Qx, x = PolynomialRing(FlintQQ, "x", cached = false)
    f = x^10 + 5*x^9 - 633*x^8 + 38157*x^7 + 1360601*x^6 - 39808345*x^5 - 464252491*x^4 - 17622187401*x^3 + 2826886632714*x^2 - 96335539805104*x + 1313743135204448
    K, a = number_field(f, check = false, cached = false)
    OK = maximal_order(K)
    P = prime_decomposition(OK, 2)[1][1]
    Kp, mKp = @inferred Hecke.unramified_completion(K, P, 100)
    @test isone(valuation(mKp(elem_in_nf(uniformizer(P)))))
    @test isone(valuation(mKp\(uniformizer(Kp)), P))
    @test valuation(mKp(gen(K))) == valuation(gen(K), P)
    @test iszero(defining_polynomial(K)(mKp(gen(K))))

    lP = prime_decomposition(OK, 11)
    if lP[1][2] == 5
      P = lP[1][1]
    else
      P = lP[2][1]
    end
    Kp, mKp = @inferred Hecke.totally_ramified_completion(K, P, 100)
    @test valuation(mKp(elem_in_nf(uniformizer(P)))) == fmpq(1, 5)
    @test isone(valuation(mKp\(uniformizer(Kp)), P))
    @test valuation(mKp(gen(K)))*5 == valuation(gen(K), P)
    #@test iszero(defining_polynomial(K)(mKp(gen(K))))

  end

  @testset "Exp and Log" begin
    K = PadicField(2, 100)
    Kx, x = PolynomialRing(K, "x", cached = false)
    L, b = Hecke.eisenstein_extension(x^7+2, "a")
    pi = uniformizer(L)
    @test iszero(log(pi))
    B = basis(L)
    for i = 15:20
      el = sum([rand(FlintZZ, 0:10)*B[j] for j = 1:7])*pi^i
      explog = exp(log(1+el))
      logexp = log(exp(el))
      @test iszero(setprecision(explog, precision(explog)-35) - 1 - el)
      @test iszero(setprecision(logexp, precision(logexp)-35)-el)
    end
  end

  @testset "Maps" begin
    # FlintQadicField -> FlintQadicField
    Qq, a = QadicField(2, 3, 100)
    rt = roots(map_coefficients(Qq, defining_polynomial(Qq)))

    i = findfirst(x -> x == a, rt)
    img = rt[mod(i-2, 3)+1]
    invimg = rt[mod(i, 3)+1]

    f = @inferred hom(Qq, Qq, img)
    @test f(a) == img
    @test f\(f(a)) == a
    @test f(f(a)) == invimg

    k, mk = ResidueField(Qq)
    for i in 1:10
      z = mk\(rand(k))
      @test z == f\(f(z))
      fl, w = @inferred haspreimage(f, z)
      @test fl
      @test f(w) == z
    end

    @test_throws ErrorException hom(Qq, Qq, Qq(2))

    f = @inferred hom(Qq, Qq, img, inverse = (invimg))
    @test f(a) == img
    @test f\a == invimg
    @test_throws ErrorException hom(Qq, Qq, Qq(2), inverse = a + 1)
    @test_throws ErrorException hom(Qq, Qq, a, inverse = Qq(2))

    g = @inferred inv(f)

    for i in 1:10
      z = mk\(rand(k))
      @test f(g(z)) == z
      @test g(f(z)) == z
    end

    # FlintQadicField -> LocalField
    Qqt, t = Qq["t"]
    L, b = eisenstein_extension(t^3 + 2, "b")
    f = @inferred hom(Qq, L, L(gen(Qq)))

    @test f(a) == L(gen(Qq))
    @test_throws ErrorException hom(Qq, L, b)
    @test f\(L(gen(Qq))) == gen(Qq)
    fl, z = @inferred haspreimage(f, b^3)
    @test fl
    @test f(z) == L(-2)

    # LocalField -> FlintQadicField
    Qp = PadicField(2, 100)
    Qpx, x = PolynomialRing(Qp)
    K, a = Hecke.unramified_extension(x^2+x+1)
    Qq, gQq = QadicField(2, 2, 100)
    rt = roots(map_coefficients(Qq, defining_polynomial(K)))

    f = @inferred hom(K, Qq, rt[1])
    g = @inferred inv(f)
    k, mk = ResidueField(Qq)
    for i in 1:10
      w = mk\(rand(k))
      @test f(g(w)) == w
    end
  end

  @testset "Automorphisms" begin
    K = PadicField(2, 200)
    Kt, t = PolynomialRing(K)
    L, b = Hecke.eisenstein_extension(t^2+2, "a")
    @test length(automorphisms(L)) == 2
    Qq, a = QadicField(2, 2, 100)
    @test length(automorphisms(Qq)) == 2
    Qqx, x = PolynomialRing(Qq)
    L, b = Hecke.eisenstein_extension(x^3+2, "a")
    @test length(automorphisms(L)) == 3
    @test length(absolute_automorphisms(L)) == 6
    G, mG = absolute_automorphism_group(L)
    @test order(G) == 6
    @test !isabelian(G)
  end

  @testset "Unramified extension" begin
    Qx,x = FlintQQ["x"]
    f = Qx([ 1, 8, -40, -46, 110, 71, -113, -43, 54, 11, -12, -1, 1 ])
    L = number_field(f)[1];
    P = prime_decomposition(maximal_order(L),7)[1][1];
    lp, mp = Hecke.generic_completion(L,P);
    Qy,y = PolynomialRing(lp,"y")
    f, mf = ResidueField(lp)
    N = Hecke.unramified_extension(y^3+preimage(mf,(gen(f))) +4 )[1]
    F, mF = ResidueField(N)
    @test order(F) == 7^6
    G, mG = automorphism_group(N)
    @test order(G) == 3
    @test mG(G[1]^2) == mG(G[1])^2
  end

  @testset "Ali-Inverse" begin
    Qx,x = FlintQQ["x"]
    L = number_field(x^6-6*x^4+9*x^2+23)[1]
    P = prime_decomposition(maximal_order(L),23)[1][1]
    lp,mp = Hecke.generic_completion(L,P)
    a = uniformizer(lp)
    Qy,y = PolynomialRing(lp,"y")
    N = Hecke.unramified_extension(y^2+13*y+4)[1]
    r = N(53)*basis(N)[1] + N(165)*basis(N)[2]
    @test isone(r*r^-1)
  end
end


text:
using SafeTestsets, Test

@time begin @testset "Boltz.jl" begin @time @safetestset "Vision Models" begin include("vision.jl") end end end