text:
abstract type RiverProfile end
abstract type TerraceProfile end

mutable struct Profile{T}
    x::Vector{Float64}
    z::Vector{Float64}
    e2n::Matrix{Int64}
    nnod::Int64
    Δx::Float64
end

struct ScratchFEM{F,I}
    K::SparseMatrixCSC{F, I}
    M::SparseMatrixCSC{F, I}
    iMC::Matrix{I}
    jMC::Matrix{I}
end

struct ScratchTerraceFEM{F,I}
    κ::Vector{F}
    bc_rhs::Vector{F}
    rhs::Vector{F}
    T::Vector{F}
    KK::SparseMatrixCSC{F, I}

    function ScratchTerraceFEM{F,I}(nn, K) where {F,I}
        κ = Vector{F}(undef, nn)
        bc_rhs, rhs, T = similar(κ), similar(κ), similar(κ)
        KK = similar(K)
        new{F,I}( κ, bc_rhs, rhs, T, KK)
    end

end

function femsolver(Δt,Δx,nnod, River::Profile{RiverProfile},hsea,
    Scratch_FEM::ScratchFEM,
    HillSlopePhysics::HillSlopeParameters,
    SubmarinePhysics::SubmarineParameters)

    # unpack from structures
    κa, alpha_dif, diffusion = HillSlopePhysics.κa, HillSlopePhysics.alpha_dif, HillSlopePhysics.diffusion
    K_s, λ = SubmarinePhysics.K_s, SubmarinePhysics.λ
    K, M, iMC, jMC = Scratch_FEM.K, Scratch_FEM.M, Scratch_FEM.iMC, Scratch_FEM.jMC

    x = River.x
    z = River.z
    e2n = River.e2n
    nel = size(e2n,2)

    # Diffusion equation ---------------------------
    isea        = z .> hsea
    imarine     = isea .== false
    L           = riverlength(view(x,isea), view(z,isea), sum(isea))
    κ_aerial    = @. diffusion + κa * alpha_dif * L
    # ----------------------------------------------

    hw          = @. abs(hsea-z)
    κ           = @. K_s*exp(-λ*hw)
    κ[isea]    .= κ_aerial
    α           = 1/2
        #  alpha = 1/2 --> Crank Nicholson (IMPLICIT)
        #  alpha = 1   --> backward difference (FULL IMPLICIT)
        #  alpha = 0   --> forward difference (EXPLICIT) // not stable for now
    TOL         = 1e-3
    bc_rhs      = fill(0.0,nnod)
    rhs         = similar(z)
    tmp         = similar(z)
    T0          = copy(z)
    T           = copy(z)
    Tdummy      = copy(T)

    bcdof       = [1, nnod]
    bcval       = [z[1], z[nnod]]
    ifree       = 2:nnod-1

    for it = 1:40
        # ASSEMBLE MATRICES ---------------------------------------------------
        fill!(K, 0.0)
        fill!(M, 0.0)
        K,M = matrixassembly(e2n,nnod, nel, κ, Δx, K, M, iMC,jMC)
        # K,M   = matrixassembly_threaded(e2n,nnod, nel, κ, Δx, K, M, iMC,jMC)
        KK = @. (Δt*α)*K + M

        # DIRICHLET BOUNDARY CONDITIONS ----------------------------------------
        fill!(bc_rhs,0.0)
        KK, bc_rhs = dirichlet(KK,bc_rhs,bcdof,bcval)

        # RIGHT HAND SIDE VECTOR -----------------------------------------------
        tmp .= (@. - Δt*(1-α)*K + M) * T0
        @. rhs = tmp - bc_rhs

        # SOLVE SYSTEM ---------------------------------------------------------
        if @isdefined F
            factorize!(F,KK[ifree,ifree])
        else
            F = factorize(KK[ifree,ifree])
        end
        @time T[ifree] = F\rhs[ifree];
        @time T[ifree] .= F\rhs[ifree];

        # UPDATE SUBMARINE HEIGHT ------------------------------------------------------
        hw = hsea .- @views T[imarine]
        @views κ[imarine] .= @. K_s*exp(-λ*hw)
        @views κ[isea].= κ_aerial
        if it > 1 && norm2(T,Tdummy) < TOL;break;end
        Tdummy      = copy(T)
    end

    return T

end

function fill_κ!(κ, x, z, idx, HillSlopePhysics)
    κa, α, diffusion = HillSlopePhysics.κa, HillSlopePhysics.alpha_dif, HillSlopePhysics.diffusion
    L = x[1]
    @fastmath for i in 2:idx
        @inbounds L += pow32( (x[i]-x[i-1])^2  + (z[i]-z[i-1])^2, 0.5) # River length from origin to i-th node
        @inbounds κ[i] = diffusion + κa * α * L
    end
end

function femsolver(
    Δt,
    Terrace::Profile{TerraceProfile},
    hsea,
    ScratchTerrace_FEM::ScratchTerraceFEM,
    Scratch_FEM::ScratchFEM,
    HillSlopePhysics::HillSlopeParameters
    )

    # unpack stuff
    K, M, iMC, jMC =
        Scratch_FEM.K, Scratch_FEM.M, Scratch_FEM.iMC, Scratch_FEM.jMC
    x, z, nnod, Δx, e2n =
        Terrace.x, Terrace.z, Terrace.nnod, Terrace.Δx, Terrace.e2n
    κ, bc_rhs, rhs, T, KK =
        ScratchTerrace_FEM.κ, ScratchTerrace_FEM.bc_rhs,  ScratchTerrace_FEM.rhs, ScratchTerrace_FEM.T, ScratchTerrace_FEM.KK
    fill!(bc_rhs, 0.0)
    copyto!(T, z)
    nel = size(e2n,2)

    # Diffusion equation
    isea = z .> hsea
    fill_κ!(κ, x, z, sum(isea), HillSlopePhysics)
    α = 1/2
        #  alpha = 1/2 --> Crank Nicholson (IMPLICIT)
        #  alpha = 1   --> backward difference (FULL IMPLICIT)
        #  alpha = 0   --> forward difference (EXPLICIT) // not stable

    # Boundary conditions
    bcdof       = (1, nnod)
    bcval       = (z[1], z[nnod])
    ifree       = 2:nnod-1

    # ASSEMBLE MATRICES
    fill!(K, 0.0)
    fill!(M, 0.0)
    K, M = matrixassembly(e2n, nnod, nel, κ, Δx, K, M, iMC,jMC)
    KK .= @. (Δt*α)*K + M

    # DIRICHLET BOUNDARY CONDITIONS
    KK, bc_rhs = dirichlet(KK, bc_rhs, bcdof, bcval)

    # RIGHT HAND SIDE VECTOR
    rhs .= (@. - Δt*(1-α)*K + M) * z - bc_rhs

    # SOLVE SYSTEM
    T[ifree] .= KK[ifree,ifree]\rhs[ifree]
    z[isea] .= T[isea]

    return z

end

# function femsolver(Δt,Δx,e2n,nel, nn,Terrace::Profile{TerraceProfile},hsea,
#     K,M,iMC,jMC,
#     D)

#     isea        = 1:find_shore_id(hsea, Terrace.z, nn)
#     x           = Terrace.x
#     z           = Terrace.z
#     nnod        = length(x)

#     κ           = fill(0.0,nnod)
#     κ[isea]    .= D
#     α           = 1/2
#         #  alpha = 1/2 --> Crank Nicholson (IMPLICIT)
#         #  alpha = 1   --> backward difference (FULL IMPLICIT)
#         #  alpha = 0   --> forward difference (EXPLICIT) // not stable for now
#     TOL         = 1e-3
#     bc_rhs      = fill(0.0,nnod)
#     bcdof       = [1, nnod]
#     bcval       = [z[1], z[nnod]]
#     ifree       = 2:nnod-1

#     fill!(K,0.0)
#     fill!(M,0.0)
#     K,M         = matrixassembly(e2n,nnod, nel, κ, Δx, K, M, iMC,jMC)
#     # K,M         = matrixassembly_threaded(e2n,nnod, nel, κ, Δx, K, M, iMC,jMC)
#     KK          = @.(Δt*α*K + M)

#     # DIRICHLET BOUNDARY CONDITIONS ----------------------------------------
#     fill!(bc_rhs,0.0)
#     KK,bc_rhs   = dirichlet(KK,bc_rhs,bcdof,bcval)

#     # RIGHT HAND SIDE VECTOR -----------------------------------------------
#     rhs         = (@. - Δt*(1-α)*K + M) * z - bc_rhs
#     rhs[bcdof] .= bcval

#     # SOLVE SYSTEM ---------------------------------------------------------
#     z[isea]    .= KK[isea,isea]\view(rhs,isea)

#     return z

# end

function meshgen1d(x0::Float64,z0::Float64,xf::Float64,zf::Float64,
    nnod::Int64)

    x    = Array{Float64}(undef,nnod,1)
    z    = Array{Float64}(undef,nnod,1)
    dx   = (xf-x0) / (nnod-1)
    dz   = (zf-z0) / (nnod-1)
    x[1] = x0;
    z[1] = z0;

    # Create coordinate arrays
    @avx for ii = 2:nnod
        x[ii] = x[ii-1] + dx
        z[ii] = z[ii-1] + dz
    end

    # Create connectivity matrix
    nel = nnod - 1
    e2n = Array{Int64}(undef,2,nel)
    @simd for ii = 1:nel
        e2n[1,ii] = ii
        e2n[2,ii] = ii+1
    end

    return x,z,nel,e2n

end
function connectivitymatrix(nnod::Int64)

    # Create connectivity matrix
    nel = nnod - 1
    e2n = Array{Int64}(undef,2,nel)
    @simd for ii = 1:nel
        e2n[1,ii] = ii
        e2n[2,ii] = ii+1
    end

    # Output
    return nel,e2n

end

function shapefunctions(element_order::Int64)

   if element_order == 1
       # local ip coordinates
       ipx = (sqrt(1/3), -sqrt(1/3))
       w = 1
       N1 = @SVector [0.5 * (1 - ipx[i]) for i in 1:2]
       N2 = @SVector [0.5 * (1 + ipx[i]) for i in 1:2]
       N = (N1', N2')
       ∇N_temp = @SVector [-1/2, 1/2]
       ∇N = (∇N_temp', ∇N_temp')
   end

   return w, N, ∇N

end

function matrixassembly(e2n::Array{Int64,2},nnod::Int64,
    nel::Int64,dx::Float64)

    # Variables
    nnodel  = 2
    matel   = nnodel * nnodel
    nip     = nnodel
    κ       = fill(1.0,nnod)
    detJ    = dx/2; # when using  N
    invJ    = 2/dx; # when using ∇N
    kappaEl = Array{Float64}(undef,nnodel,1)
    qEl     = Array{Float64}(undef,nnodel,1)
    q       = fill(0.0,nnod)
    q[1]    = 1.0

    # Calculate K and M bandwith
    bandwith = nnodel + 1
    nfill    = bandwith * nnod - 2 # number of nonzeros

    # Get shape functions
    weight,N,∇N  = shapefunctions(1)

    # Allocate FEM matrices
    # K      = Array{Float64,2}(undef,nnod,nnod) # conductivity matrix
    # M      = Array{Float64,2}(undef,nnod,nnod) # mass matrix
    # Q      = Array{Float64,1}(undef,nnod,1)    # flux vector (i.e. Neumann BC)

    # Allocate FEM element matrices
    Kel     = Array{Float64}(undef,nnodel,nnodel); fill!(Kel,0.0)
    Mel     = Array{Float64}(undef,nnodel,nnodel); fill!(Mel,0.0)
    Qel     = Array{Float64}(undef,nnodel,1); fill!(Qel,0.0)

    # Allocate FEM sparse matrices
    # K       = Array{Float64}(undef,nfill,1) # conductivity matrix
    # M       = Array{Float64}(undef,nfill,1) # mass matrix

    # Temporal allocations
    Kv      = Array{Float64}(undef,nel,nnodel*nnodel);  # storage for conductivity matrix coefficients
    Mv      = Array{Float64}(undef,nel,nnodel*nnodel);  # storage for mass matrix coefficients
    Q_all   = Array{Float64}(undef,nel,nnodel);         # storage for mass matrix coefficients
    iMC     = Array{Int64}(undef,nel,nnodel*nnodel);    # storage for the matrix i indices
    jMC     = Array{Int64}(undef,nel,nnodel*nnodel);    # storage for the matrix j indices

    # Other allocations
    I1      = SVector(1,1)'
    ij      = Array{Int64}(undef,nnodel,1)
    rows    = Array{Int64}(undef,nnodel,nnodel)
    cols    = Array{Int64}(undef,nnodel,nnodel)
    kappaEl = Array{Float64}(undef,2,1) # zeros(MVector{2})
    qEl     = Array{Float64}(undef,2,1) # zeros(MVector{2})

    # Assembly loop
    # Threads.@threads for iel = 1 : nel
    @inbounds for iel = 1 : nel
        # global Kel, Mel,Qel

        # Conductivity and Sediment flux at the nodes of i-th element
        @avx for ii = 1: nnodel
            ij[ii]      = e2n[ii,iel]
            kappaEl[ii] = κ[ij[ii]]
            qEl[ii]     = q[ij[ii]]
        end

        # Numerical integration loop
        for ip = 1 : nip
            # kappa at i-th integration point
            KappaEl  = kappaEl' * N[ip]';
            # kappa at i-th integration point
            QEl      = qEl' * N[ip]';
            # Conductivity elemental matrix
            Kel     += ∇N[ip]' * KappaEl .* ∇N[ip] .* weight .* invJ
            # Mass elemental matrix
            Mel     += N[ip]' *  N[ip] .* weight .* detJ
            # Sediment input force vector
            Qel     += N[ip]' .* qEl;
        end

        rows          .= ij * I1
        cols          .= rows'
        Kv[iel,:]      = Kel[:]
        Mv[iel,:]      = Mel[:]
        Q_all[iel,:]   = Qel[:]
        iMC[iel,:]     = rows[:]
        jMC[iel,:]     = cols[:]

        # c = 1
        # for i in 1:nnodel,j in 1:nnodel
        #     # rows[c]     = EL2NOD[j,iel]    # row location in global matrices
        #     # cols[c]     = EL2NOD[i,iel]    # row location in global matrices
        #     Kv[c,iel]   = Kel[j,i]
        #     Mv[c,iel]   = Mel[j,i]
        #     Q_all[c,iel]= Qel[j,i]
        #     iMC[c,iel]  = e2n[j,iel]
        #     jMC[c,iel]  = e2n[i,iel]
        #     c       +=1
        # end

        # Reset element matrices
        fill!(Kel , 0.0)
        fill!(Mel , 0.0)
        fill!(Qel , 0.0)

    end

    M   = sparse(iMC[:],jMC[:],Mv[:])
    K   = sparse(iMC[:],jMC[:],Kv[:])
    # Q   = accumarray(e2n[:], Q_all[:])
    Q   = accumQ(e2n[:], Q_all[:] , nnod)

    return K,M,Q

end #### END matrixassembly FUNCTION ###########################################

#### START matrixassembly FUNCTION #############################################
function matrixassembly(e2n::Array{Int64,2},nnod::Int64,
    nel::Int64,κ,dx::Float64,K,M,iMC,jMC)

    # Random variables
    nnodel  = 2
    matel   = nnodel * nnodel
    nip     = nnodel
    # κ       = fill(1.0,nnod)
    detJ    = dx/2; # when using  N
    invJ    = 2/dx; # when using ∇N
    kappaEl = Array{Float64}(undef,nnodel,1)
    # qEl     = Array{Float64}(undef,nnodel,1)
    # q       = fill(0.0,nnod)
    # q[1]    = 1.0

    # Get shape functions
    weight,N,∇N  = shapefunctions(1)

    # Allocate FEM element matrices
    # Kel     = Array{Float64}(undef,nnodel,nnodel); fill!(Kel,0.0)
    # Mel     = Array{Float64}(undef,nnodel,nnodel); fill!(Mel,0.0)
    # Qel     = Array{Float64}(undef,nnodel,1); fill!(Qel,0.0)

    # Temporal allocations
    # Q_all   = Array{Float64}(undef,nel,nnodel);         # storage for mass matrix coefficients

    # Other allocations
    # kappaEl = Array{Float64}(undef,2,1) # zeros(MVector{2})
    # qEl     = Array{Float64}(undef,2,1) # zeros(MVector{2})
    # KappaEl = Array{Float64}(undef,1,1) # zeros(MVector{2})
    # QEl     = Array{Float64}(undef,1,1) # zeros(MVector{2})
    ij      = Array{Int64}(undef,nnodel,1)

    A       = [∇N[ip]' * ∇N[ip] * weight * invJ for ip = 1:2]
    B       = [N[ip]'  * N[ip]  * weight * detJ for ip = 1:2]
    Mel     = B[1]+B[2]

    # Assembly loop
    @inbounds for iel = 1 : nel

        kappaEl = @SVector [κ[e2n[ii,iel]] for ii = 1 : 2]
        Kel     = @SMatrix zeros(nnodel,nnodel)

        # Numerical integration loop
        @views for ip = 1 : nip
            Kel += A[ip] * (N[ip] * kappaEl)
            # # Sediment input force vector
            # @. Qel  += A[ip]' .* qEl
        end

        for ii in 1:nnodel*nnodel
            i       = iMC[ii,iel]
            j       = jMC[ii,iel]
            K[i,j] += Kel[ii]
            M[i,j] += Mel[ii]
            # if ii < nnodel +1
            #     Q_all[iel,ii] = Qel[ii]
            # end
        end

        # Reset element matrices
        # fill!(Kel , 0.0)
        # fill!(Mel , 0.0)
        # fill!(Qel , 0.0)

    end

    # Q   = accumQ(e2n[:], Q_all[:] , nnod)

    return K,M

end

function sparsitymatrix(e2n::Array{Int64,2},nel::Int64, nnodel::Int64)

    # Temporal allocations
    iMC     = Matrix{Int64}(undef,nel,nnodel*nnodel);    # storage for the matrix i indices
    jMC     = Matrix{Int64}(undef,nel,nnodel*nnodel);    # storage for the matrix j indices

    # Other allocations
    # ij      = @MVector ones(Int32,nnodel)
    I1  = @SMatrix [1 1]

    # Assembly loop
    @inbounds for iel = 1 : nel
        ij = @SVector [e2n[ii,iel] for ii in 1:2]
        rows = ij * I1
        @views iMC[iel,:] = vec(rows)
        @views jMC[iel,:] = vec(rows')
    end

    M   = sparse(vec(iMC),vec(jMC),zeros(length(jMC)))
    K   = copy(M)

    ScratchFEM(
        K, M, Matrix(iMC'), Matrix(jMC')
    )

end #### END matrixassembly FUNCTION ###########################################

@inline function accumQ(idx, V, nnod)
    Q   = fill(0.0,nnod)
    @inbounds @simd for ii = 1 : nnod
        Q[idx[ii]] += V[ii]
    end
    return Q
end

#### START dirichlet FUNCTION ##################################################
function dirichlet(KK,bc_rhs,bcdof,bcval)

    @inbounds for i = 1:length(bcdof)
        @views bc_rhs .+= Array(KK[:,bcdof[i]] * bcval[i])
        @views KK[bcdof[i],:] .= 0
        @views KK[:,bcdof[i]] .= 0
        KK[bcdof[i],bcdof[i]] = 1
    end

    return KK, bc_rhs

end #### END dirichlet FUNCTION ################################################

## START accumarray FUNCTION ###################################################
@inline function accumarray(subs,M)
    C   = Vector{Float64}(undef,n)
    @avx for i in 1:length(subs)
        idx     = subs[i]
        C[idx] += M[i]
    end

end

@inline function norm2(A::Vector{T}, B::Vector{T}) where T
    norm = zero(T)
    @tturbo for i in eachindex(A)
         norm += (A[i] - B[i])^2
    end
    √(norm)
end

@inline function norm2(A::Vector{T}, B::Vector{T}, indices::NamedTuple) where T
    norm = zero(T)
    i1, i2 = indices.i1, indices.i2
    @tturbo for i in i1:i2
         norm += (A[i] - B[i])^2
    end
    √(norm)
end

function mesher(Δx, slope, type::String)
    if type == "linear"
        x,z,dx2,nn,nel,e2n = linearmesh(Δx,slope)
    elseif type == "quadratic"
        x,z,dx2,nn,nel,e2n = quadraticmesh(Δx,slope)
    end

    return x,z,dx2,nn,nel,e2n
end

function linearmesh(Δx,slope)
    # -- Mesh
    x       = collect(0:Δx:200e3)
    z       = @. slope * x + 1e3    # 2e3 is the intercept
    dx2     = Δx * Δx
    nn      = length(x)

    # -- Connectivity matrix
    nel = nn - 1
    e2n = Array{Int64}(undef,2,nel)
    @simd for ii = 1:nel
        e2n[1,ii] = ii
        e2n[2,ii] = ii+1
    end

    # Output
    return x,z,dx2,nn,nel,e2n

end

function quadraticmesh(Δx,slope)
    # -- Mesh
    x       = collect(0:Δx/2:200e3)
    z       = @. slope * x + 2e3    # 2e3 is the intercept
    dx2     = Δx * Δx
    nn      = length(x)

    # -- Connectivity matrix
    nel     = Int(nn/2 - 1)
    e2n     = Array{Int64}(undef,3,nel)
    idx     = 1:2:nn
    @simd for ii = 1:nel
        e2n[1,ii] = idx[ii]
        e2n[2,ii] = idx[ii]+1
        e2n[3,ii] = idx[ii]+2
    end

    # -- Output
    return x,z,dx2,nn,nel,e2n

end


text:
for (f, T) in Base.Iterators.product((:add, :mul, :sub), (Float32, Float64))
    name = Symbol("$(f)_float_contract")
    if T === Float32
        llvmt = "float"
    elseif T === Float64
        llvmt = "double"
    end

    #XXX Use LLVM.jl
    ir = """
        %x = f$f contract $llvmt %0, %1
        ret $llvmt %x
    """
    @eval begin
        # the @pure is necessary so that we can constant propagate.
        Base.@pure function $name(a::$T, b::$T)
            @Base._inline_meta
            Base.llvmcall($ir, $T, Tuple{$T, $T}, a, b)
        end
    end
end

ext: jl


text:
using Pkg: Pkg

"""
    find_registry(registry_name::AbstractString = "QuantumRegistry")

Return the registry `registry_name`. If the registry is not installed, return
`nothing`.
"""
function find_registry(registry_name::AbstractString = "QuantumRegistry")::Union{Pkg.Registry.RegistryInstance,Nothing}
    result = Pkg.Registry.find_installed_registries(stdout, [Pkg.RegistrySpec(registry_name)])
    isempty(result) && return nothing
    return only(result)
end

"""
    is_dependency_installed(package_name::AbstractString)

Return `true` if the direct dependency `package_name` of the current project is found
in the current dependency graph. There is no check made that `package_name` is
actually a dependency.
"""
is_dependency_installed(package_name::AbstractString)::Bool =
    any(x -> x.name == package_name && x.is_direct_dep, values(Pkg.dependencies()))


text:
function _make_save_gui()

    save_grid=Grid()

    save_entry=Entry()
    #Gtk.GAccessor.text(save_entry,r.save.folder)
    save_grid[1,1]=Label("Save Folder: ")
    save_grid[2,1]=save_entry

    save_check_volt=CheckButton("Analog Voltage")
    save_grid[1,2]=save_check_volt

    save_check_lfp=CheckButton("LFP")
    save_grid[1,3]=save_check_lfp

    save_check_ttlin=CheckButton("TTL input")
    save_grid[1,4]=save_check_ttlin

    save_check_ts=CheckButton("Spike Time Stamps")
    save_grid[1,5]=save_check_ts

    save_check_adc=CheckButton("ADC Input")
    save_grid[1,6]=save_check_adc

    save_pref_win=Window(save_grid)
    setproperty!(save_pref_win, :title, "Saving Preferences")

    Gtk.showall(save_pref_win)
    visible(save_pref_win,false)

    save_widgets=Save_Widgets(save_pref_win,save_check_volt,save_check_lfp,save_check_ttlin,save_check_ts,save_check_adc,save_entry)
end

function add_save_callbacks(w,handles,r,fpga)

    #This should be a longer callback where the save preference checkboxes are loaded
    #automatically
    signal_connect(w.win, :delete_event) do widget, event
        visible(w.win, false)
        true
    end
    signal_connect(save_volt_cb,w.volt,"clicked",Void,(),false,(handles,r))
    signal_connect(save_lfp_cb,w.lfp,"clicked",Void,(),false,(handles,r))
    signal_connect(save_ttlin_cb,w.ttlin,"clicked",Void,(),false,(handles,r))
    signal_connect(save_ts_cb,w.ts,"clicked",Void,(),false,(handles,r))
    signal_connect(save_entry_cb,w.input,"activate",Void,(),false,(handles,r))
    signal_connect(save_adc_cb,w.adc,"clicked",Void,(),false,(handles,r))

    nothing
end

function saving_pref_cb(widget::Ptr,user_data::Tuple{Gui_Handles,RHD2000})

    han, rhd = user_data

    visible(han.save_widgets.win,true)
    nothing
end

function save_volt_cb(widget::Ptr,user_data::Tuple{Gui_Handles,RHD2000})
    han,rhd = user_data

    rhd.save.save_full=getproperty(han.save_widgets.volt,:active,Bool)

    if rhd.save.save_full
        prepare_v_header(rhd)
    end

    nothing
end

function save_lfp_cb(widget::Ptr,user_data::Tuple{Gui_Handles,RHD2000})

    han,rhd = user_data

    rhd.save.lfp_s=getproperty(han.save_widgets.lfp,:active,Bool)

    if rhd.save.lfp_s
        prepare_lfp_header(rhd)
    end

    nothing
end

function save_ttlin_cb(widget::Ptr,user_data::Tuple{Gui_Handles,RHD2000})
    han,rhd = user_data
    rhd.save.ttl_s=getproperty(han.save_widgets.ttlin,:active,Bool)

    if rhd.save.ttl_s
        prepare_ttl_header(rhd)
    end

    nothing
end

function save_ts_cb(widget::Ptr,user_data::Tuple{Gui_Handles,RHD2000})
    han,rhd = user_data
    rhd.save.ts_s = getproperty(han.save_widgets.ts,:active,Bool)

    if rhd.save.ts_s
        prepare_stamp_header(rhd)
    end

    nothing
end

function save_adc_cb(w::Ptr,user_data::Tuple{Gui_Handles,RHD2000})
    han,rhd=user_data
    rhd.save.adc_s = getproperty(han.save_widgets.adc,:active,Bool)

    if rhd.save.adc_s
        prepare_adc_header(rhd)
    end

    nothing
end

function save_entry_cb(widget::Ptr,user_data::Tuple{Gui_Handles,RHD2000})

    han,rhd = user_data

    base_path = getproperty(han.save_widgets.input,:text,String)
    backup_path = string(base_path,"/.backup/")
    rhd.save.folder=base_path
    rhd.save.backup=backup_path
    rhd.save.v=string(base_path,"/v.bin")
    rhd.save.ts=string(base_path,"/ts.bin")
    rhd.save.ttl=string(base_path,"/ttl.bin")
    rhd.save.ttl_out=string(base_path,"/ttl_out.bin")
    rhd.save.lfp=string(base_path,"/lfp.bin")
    rhd.save.adc=string(base_path,"/adc.bin")

    prepare_save_folder(rhd)

    if rhd.save.save_full
        prepare_v_header(rhd)
    end
    if rhd.save.ts_s
        prepare_stamp_header(rhd)
    end
    if rhd.save.adc_s
        prepare_adc_header(rhd)
    end
    if rhd.save.ttl_s
        prepare_ttl_header(rhd) #TTL in
        prepare_ttl_header(rhd,rhd.save.ttl_out) #TTl out
    end
    if rhd.save.lfp_s
        prepare_lfp_header(rhd)
    end

    nothing
end

#Prepare saving headers
function prepare_save_folder(r)
    mkdir(r.save.folder)
    mkdir(r.save.backup)
    mkdir(string(r.save.backup,"thres"))
    mkdir(string(r.save.backup,"gain"))
    mkdir(string(r.save.backup,"cluster"))

    f=open(string(r.save.backup,"backup.bin"),"w")
        write(f,1)
    close(f)
end


text:
using Plots
using ContinuousPOMDPTreeSearchExperiments

gr()

pomdp = SimpleLightDark()

tmax = 80
smin = -10
smax = 20
T = linspace(0.0, tmax)
S = linspace(-1.0, 21.0)
inv_grays = cgrad([RGB(1.0, 1.0, 1.0),RGB(0.0,0.0,0.0)])

p = contour(T, S, (t,s)->abs(s-pomdp.light_loc),
        bg_inside=:black,
        fill=true,
        xlim=(0, tmax),
        ylim=(smin, smax),
        color=inv_grays,
        # xlabel="Time",
        # ylabel="State",
        cbar=false,
        legend=:topright,
       )

plot!(p, [0, tmax], [0, 0], linewidth=2, color="green", label="", line=:dash)
@show fname = tempname()*".svg"
savefig(p, fname)
run(`inkscape $fname`)


text:
import sbp
using sbp.Operator: read_operator, write_operator, OperatorData, equals
using sbp.Operator: read_array, write_array, write_stencil, read_stencil
using sbp.Operator: version, parse_version, Version, check_version, to_matrix,
                    to_vector
using Test

@testset "Version" begin
        u = Version(1,2,3)
        v = parse_version("v1.2.3")
        @test u == v
        u = Version(version.major, version.minor, version.patch)
        check_version(u)
end

@testset "Array" begin
        m = 4
        n = 3
        a = zeros(m, n)
        f = open("array.txt", "w")
        write_array(f, "array", a)
        close(f)

        f = open("array.txt")
        label, b = read_array(f)
        @test label == "array"
        @test a == b
        close(f)
        rm("array.txt")

end

@testset "Stencil" begin
        f = open("stencil.txt", "w")
        stencil = zeros(5)
        offset = 2
        write_stencil(f, "stencil", stencil, offset)
        close(f)

        f = open("stencil.txt")
        label, st, off = read_stencil(f)
        @test label == "stencil"
        @test off == offset
        @test st == stencil
        close(f)
        rm("stencil.txt")

end

@testset "Operator" begin

        left = zeros(1,2)
        left[1,1] = -1.0
        left[end,end] = 1.0
        right = zeros(1,2)
        right[1,1] = -1.0
        right[end,end] = 1.0
        interior = zeros(3)
        interior[1] = -0.5
        interior[end] = 0.5
        offset = -1

        Op = OperatorData(version, left, right, interior, offset)
        write_operator("test.txt", Op)
        Op2 = read_operator("test.txt")
        @test equals(Op, Op2)
        rm("test.txt")

        @testset "to_matrix" begin
                @test_throws ErrorException("Too few rows") D = to_matrix(Op, 1, 1)
                m = 3
                n = 3
                D = to_matrix(Op, m, n, false)
                ans = zeros(m, n)
                ans[1,1] = -1.0
                ans[1,2] = 1.0
                ans[2,1] = -0.5
                ans[2,3] = 0.5
                ans[end,end-1] = -1.0
                ans[end,end] = 1.0
                @test isapprox(D, ans)
                Dsparse = to_matrix(Op, m, n, true)
                @test isapprox(Dsparse, ans)
        end

        @testset "to_vector" begin
                left = zeros(1, 2)
                interior = zeros(1)
                left[1] = -1.0
                left[2] = 1.0
                right = zeros(1, 2)
                right[1] = -1.0
                right[2] = 1.0
                interior[1] = 2.0
                offset = 0
                Op = OperatorData(version, left, right, interior, offset)
                @test_throws ErrorException("Too few elements") D = to_vector(Op, 3)
                m = 5
                ans = zeros(m)
                ans[1] = -1.0
                ans[2] = 1.0
                ans[3] = 2.0
                ans[end-1] = -1.0
                ans[end] = 1.0
                u = to_vector(Op, m)
                @test isapprox(u, ans)

        end

end

max_stars_repo_name: ooreilly/sbpjl

max_issues_repo_name: ooreilly/sbpjl

max_forks_repo_name: ooreilly/sbpjl


text:
module ConstrainedLeastSquares

using Espresso:      subs
using LinearAlgebra: Diagonal
using NamedArrays:   NamedArray
using PrettyTables:  pretty_table
using Zygote:        jacobian

include("input.jl")
include("output.jl")
include("model.jl")
include("solve.jl")

export
    LSQInput,
    LSQOutput,
    @withinput_debug,
    @withinput,
    correlation_β,
    covariance_β,
    names_z,
    names_β,
    print_corr_β,
    print_cov_β,
    set_covariance!,
    solve,
    uncertainty_β

end # module


text:
#
#   Differential Operators 1D of order 2 (Q = 4)
#

function Diff_Operator_1D(  derivative_order::Int , dx::T , N::Int ) where T

    #Check dimension of array
    if(N < 4)
        print("ERROR: Dimension of operator must be greater than 3")
        return
    end

    #Create operator
    Opp = zeros(T , N,N)

    #1st order derivative
    if( derivative_order == 1)

        d1_1 = Array{T}([ -11.0/6.0  , 	3.0	, -3.0/2.0 , 	1.0/3.0	]/dx)
        d1_2 = Array{T}([ -1.0/4.0  , -5.0/6.0	, 3.0/2.0 , 	-1.0/2.0	 , 1.0/12.0	]/dx)
        d1_c = Array{T}([ 1.0/12.0  , 	-2.0/3.0	, 0 , 	2.0/3.0	 , -1.0/12.0	]/dx)

        #Fill first line  and last
        for i in 1:length(d1_1)

            #First row (left to right)
            Opp[ 1 , i ]        = d1_1[i]

            #Last row (right to left)
            Opp[ N , N-(i-1) ]  = -d1_1[i]
        end

        #Fill second line and second lasts
        for i in 1:length(d1_2)

            #Second row (left to right)
            Opp[ 2 , i ]        = d1_2[i]

            #Last row (right to left)
            Opp[ N-1 , N-(i-1) ]  = -d1_2[i]
        end

        #Fill remaining lines
        for i in 3:(N-2)
            for j in 1:length(d1_c)
                Opp[i , i+j-3 ] = d1_c[j]
            end
        end

        #Return operator
        return Opp

    end

    #2nd order derivative
    if( derivative_order == 2)

        blah = 1/ (dx^2)
        d2_1 = Array{T}([ 35.0 / 12.0 , 	-26.0/3.0	, 19.0/2.0 , 	-14.0/3.0 , 11.0/12.0	] * blah)
        d2_2 = Array{T}([ 5.0 / 6.0 , 	-5.0/4.0	, -1.0/3.0 , 	7.0/6.0 , -1.0/2.0 , 1.0/12.0	] * blah )
        d2_c = Array{T}([ -1.0/12.0  , 	4.0/3.0	, -5.0/2.0 , 	4.0/3.0	 , -1.0/12.0	]* blah )

        #Fill first and last line
        for i in 1:length(d2_1)

            #First row (left to right)
            Opp[ 1 , i ]        = d2_1[i]

            #Last row (right to left)
            Opp[ N , N-(i-1) ]  = d2_1[i]
        end

        #Fill second and second last line
        for i in 1:length(d2_2)

            #First row (left to right)
            Opp[ 2 , i ]        = d2_2[i]

            #Last row (right to left)
            Opp[ N-1 , N-(i-1) ]  = d2_2[i]
        end

        #Fill remaining lines
        for i in 3:(N-2)
            for j in 1:length(d2_c)
                Opp[i , i+j-3 ] = d2_c[j]
            end
        end

        #Return operator
        return Opp

    end

    #Higher derivatives not avaliable
    if(derivative_order > 2 )
        print("ERROR: Derivative Order still not implementd")
        return
    end

end

function Diff_Operator_1D_Periodic(  derivative_order::Int , dx::T , N::Int )  where T

    #Check dimension of array
    if(N < 4)
        print("ERROR: Dimension of operator must be greater than 3")
        return
    end

    #Create operator
    Opp = spzeros(T , N,N)

    #1st order derivative
    if( derivative_order == 1)

        #Higher Order Derivative ( Q = 16)
        for i in 1:N , j in 1:N
            i-j==1   && (Opp[i,j] =  -2.0 / 3.0)
            j-i==1   && (Opp[i,j] =   2.0 / 3.0)
            j-i==N-1 && (Opp[i,j] = - 2.0 / 3.0)
            i-j==N-1 && (Opp[i,j] =   2.0 / 3.0)

            i-j==2   && (Opp[i,j] =   1.0 / 12.0)
            j-i==2   && (Opp[i,j] =  -1.0 / 12.0)
            j-i==N-2 && (Opp[i,j] =   1.0 / 12.0)
            i-j==N-2 && (Opp[i,j] =  -1.0 / 12.0)

        end

        return Opp/dx
    end

    #2nd order derivative
    if( derivative_order == 2)

        #Higher order derivative ( Q = 16)
        for i in 1:N , j in 1:N
            abs(i-j)==2   && (Opp[i,j] = -1.0 / 12.0 )
            abs(i-j)==1   && (Opp[i,j] =  4.0 / 3.0  )
            i == j        && (Opp[i,j] = -5.0 / 2.0  )
            abs(i-j)==N-1 && (Opp[i,j] =  4.0 / 3.0  )
            abs(i-j)==N-2 && (Opp[i,j] = -1.0 / 12.0)

        end

        return Opp/dx^2
    end

    #Higher derivatives not avaliable
    if(derivative_order > 2 )
        print("ERROR: Derivative Order still not implementd")
        return
    end

end

#
#   Differential Operators 2D
#

function Diff_Operator_2D( derivative_order::Int , index::Int , delta , dim)

    if index == 1
        A = Diff_Operator_1D(derivative_order , delta[1] , dim[1] )
        return kron(sparse( I, dim[2], dim[2] ) , A)
    end

    if index == 2
        A = Diff_Operator_1D(derivative_order , delta[2] , dim[2] )
        return kron(A, sparse( I, dim[1], dim[1] ))
    end

    #Derivative order 3
    if(index > 2 )
        print("ERROR: Out of bounds")
        return
    end
end

function Diff_Operator_2D_Periodic( derivative_order::Int , index::Int , delta , dim)

    if index == 1
        A = Diff_Operator_1D_Periodic(derivative_order , delta[1] , dim[1] )
        return kron(sparse( I, dim[2], dim[2] ) , A)
    end

    if index == 2
        A = Diff_Operator_1D_Periodic(derivative_order , delta[2] , dim[2] )
        return kron(A, sparse( I, dim[1], dim[1] ))
    end

    #Derivative order 3
    if(index > 2 )
        print("ERROR: Out of bounds")
        return
    end
end


text:
"""
Simple script to grab and install these packages into the global Julia install (easiest way
of handling this).
"""

using Pkg

Pkg.add("Distributions")
Pkg.add("Random" )
Pkg.add("Statistics" )
Pkg.add("LinearAlgebra")
Pkg.add("ProgressBars")
Pkg.add("DataStructures")

Pkg.add("FileIO")
Pkg.add("CSV")
Pkg.add("DataFrames")
Pkg.add("Plots")
Pkg.add("Measures")
Pkg.add("Pyplot")
Pkg.add("Pipe")

Pkg.add("DelimitedFiles")
Pkg.add("Dates" )


text:
@assert zeros(Int64, 3) == [0, 0, 0]
@assert zeros(Int64, 2, 2) == [0 0; 0 0]
@assert ones(Int64, 3, 2) == [1 1; 1 1; 1 1]
@assert eye(Int32, 3) == [1 0 0; 0 1 0; 0 0 1]
@assert fill(5, 1, 4) == [5 5 5 5]
@assert transpose([1 3; 2 4]) == [1 2; 3 4]
@assert [1 3; 2 4]' == [1 2; 3 4]            # postfix ' transposes
@assert fill(10, 3, 1) == [10 10 10]'        # 2d column array!
@assert [2x for x in 1:5] == [2,4,6,8,10]


text:
using GPUCompiler
using LLVM, LLVM.Interop

struct WASMCompilerParams <: AbstractCompilerParams end
const WASMCompilerJob = CompilerJob{WASMCompilerTarget,WASMCompilerParams}

function wasmfunction(f::Core.Function, tt::Type=Tuple{})
  source = FunctionSpec(f, tt, false)
  target = WASMCompilerTarget()
  params = WASMCompilerParams()

  job = CompilerJob(target, source, params)
  GPUCompiler.cached_compilation(wasmfunction_cache, job,
                                 wasmfunction_compile,
                                 wasmfunction_link)
end

const wasmfunction_cache = Dict{UInt,Any}()

# actual compilation
function wasmfunction_compile(@nospecialize(job::WASMCompilerJob))

  # compile to WASM
  method_instance, world = GPUCompiler.emit_julia(job)
  ir, kernel = GPUCompiler.emit_llvm(job, method_instance, world; libraries=true)
  print(ir)
  code = GPUCompiler.emit_asm(job, ir, kernel; format=LLVM.API.LLVMObjectFile, validate=false)
  return collect(codeunits(code))
end
wasmfunction_link(@nospecialize(job::WASMCompilerJob), exe) = exe

module WASMRuntime
  import ..GPUCompiler
  GPUCompiler.reset_runtime()
  @generated function js_error(arg)
    quote
      ccall("extern js_error", llvmcall, Nothing, ($arg,), arg)
    end
  end

  function report_exception(ex)
    js_error(reinterpret(Core.LLVMPtr{UInt8, 0}, ex))
    return
  end

  function signal_exception()
    return
  end
end

GPUCompiler.runtime_module(::WASMCompilerJob) = WASMRuntime


text:
function linInter1D(tk::R,T::R,Θ::Tuple{AbstractArray{R},AbstractArray{R}}) where R <: Real
    Θ1 = linInter1D(tk,T,Θ[1])
    Θ2 = linInter1D(tk,T,Θ[2])
    return (Θ1,Θ2)
end

function linInter1D(tk::R,T::R,Θ::Tuple) where R <: Real
    Θk = (linInter1D(tk,T,Θk) for Θk in Θ)
    return tuple(Θk...)
end

function linInter1D(tk::R,T::R,Θ::AbstractArray{R,2}) where R <: Real
    Nt   = size(Θ,2)
    H   = T/(Nt-1)  # assume nodal discretization for Θ
    idl = Int64(floor(tk/H))+1
    w   = ((H*idl)-tk)/H

    if idl==0
        return Θ[:,idl+1]
    elseif idl==Nt
        return Θ[:,idl]
    else
        return w .* Θ[:,idl] + (1-w).*Θ[:,idl+1]
    end
end

function linInter1D(tk::R,T::R,Θ::AbstractArray{R,3}) where R <: Real
    Nt   = size(Θ,3)
    H   = T/(Nt-1)  # assume nodal discretization for Θ
    idl = Int64(floor(tk/H))+1
    w   = ((H*idl)-tk)/H

    if idl==0
        Θk = Θ[:,:,idl+1]
    elseif idl==Nt
        Θk = Θ[:,:,idl]
    else
        Θk =  w .* Θ[:,:,idl] + (1-w).*Θ[:,:,idl+1]
    end
    return Θk
end

max_stars_repo_name: EmoryMLIP/MFGnet

max_issues_repo_name: EmoryMLIP/MFGnet

max_forks_repo_name: EmoryMLIP/MFGnet


text:
module SurfaceMesh
  export build_3d_mesh, distance_to_gradient_operator

  function build_3d_mesh(bbox_min, bbox_max, cube_size, distance_in_point, gradient_in_point)
    points = []
    faces = []
    for z in bbox_min[3]:cube_size:bbox_max[3]
      for y in bbox_min[2]:cube_size:bbox_max[2]
        for x in bbox_min[1]:cube_size:bbox_max[1]
          # detect border, create walls
          cube_center = (x + cube_size / 2., y + cube_size / 2., z + cube_size / 2.)
          neighbor100 = (x - cube_size / 2., y + cube_size / 2., z + cube_size / 2.)
          neighbor010 = (x + cube_size / 2., y - cube_size / 2., z + cube_size / 2.)
          neighbor001 = (x + cube_size / 2., y + cube_size / 2., z - cube_size / 2.)
          d = distance_in_point(cube_center)
          d100 = distance_in_point(neighbor100)
          d010 = distance_in_point(neighbor010)
          d001 = distance_in_point(neighbor001)

          # x-wall
          if(sign(d) != sign(d100))
            start_index = length(points) + 1
            push!(points, (x, y, z))
            push!(points, (x, y + cube_size, z))
            push!(points, (x, y + cube_size, z + cube_size))
            push!(points, (x, y, z + cube_size))
            if (d > d100)
              push!(faces, (start_index, start_index + 1, start_index + 2))
              push!(faces, (start_index, start_index + 2, start_index + 3))
            else
              push!(faces, (start_index, start_index + 2, start_index + 1))
              push!(faces, (start_index, start_index + 3, start_index + 2))
            end
          end

          # y-wall
          if(sign(d) != sign(d010))
            start_index = length(points) + 1
            push!(points, (x, y, z))
            push!(points, (x + cube_size, y, z))
            push!(points, (x + cube_size, y, z + cube_size))
            push!(points, (x, y, z + cube_size))
            if (d < d010)
              push!(faces, (start_index, start_index + 1, start_index + 2))
              push!(faces, (start_index, start_index + 2, start_index + 3))
            else
              push!(faces, (start_index, start_index + 2, start_index + 1))
              push!(faces, (start_index, start_index + 3, start_index + 2))
            end
          end

          # z-wall
          if(sign(d) != sign(d001))
            start_index = length(points) + 1
            push!(points, (x, y, z))
            push!(points, (x + cube_size, y, z))
            push!(points, (x + cube_size, y + cube_size, z))
            push!(points, (x, y + cube_size, z))
            if (d > d001)
              push!(faces, (start_index, start_index + 1, start_index + 2))
              push!(faces, (start_index, start_index + 2, start_index + 3))
            else
              push!(faces, (start_index, start_index + 2, start_index + 1))
              push!(faces, (start_index, start_index + 3, start_index + 2))
            end
          end
        end
      end
    end

    # remove the redundant points
    xyz_to_is = Dict()
    for (i, point) in enumerate(points)
      if haskey(xyz_to_is, point)
        push!(xyz_to_is[point], i)
      else
        xyz_to_is[point] = [i]
      end
    end
    less_points = []
    old_is_to_i = Dict()
    for (i, xyz_is) in enumerate(xyz_to_is)
      push!(less_points, xyz_is[1])
      for j in xyz_is[2]
        old_is_to_i[j] = i
      end
    end
    new_faces = []
    for face in faces
      push!(new_faces, tuple([old_is_to_i[i] for i in face]...))
    end

    # shift the points to match the target surface better
    better_points = []
    for point in less_points
      gradient_shift = vscale(gradient_in_point(point), -distance_in_point(point))
      # limiter gives worse approximation quality, but nicer mesh
      # let's try limiting shift if necessary by renormalizing the whole thing
#      max_axial_shift = max([abs(di) for di in gradient_shift]...)
#      if max_axial_shift > cube_size  # let's limit to the cube size since there are cases where this is the case. Doesn't exclude intersects though
#        gradient_shift = vscale(gradient_shift, cube_size / max_axial_shift)
#      end
      better_point = vsum(point, gradient_shift)
      push!(better_points, better_point)
    end

    return (better_points, new_faces)
  end

  function distance_to_gradient_operator(distance_in_point)
    eps = 1e-5 # warning! arbitrary number
    return function(point)
      d = distance_in_point(point)
      d100 = distance_in_point(vsum(point, (eps, 0., 0.)))
      d010 = distance_in_point(vsum(point, (0., eps, 0.)))
      d001 = distance_in_point(vsum(point, (0., 0., eps)))
      return ((d100 - d)/eps, (d010 - d)/eps, (d001 - d)/eps)
    end
  end

  function vlimit(a, min_ai, max_ai)
    return tuple([min(max(min_ai, ai), max_ai) for ai in a]...)
  end

  function vsum(a, b)
    return tuple([ai + bi for (ai, bi) in zip(a, b)]...)
  end

  function vscale(a, x)
    return tuple([ai * x for ai in a]...)
  end

  function vdot(a, b)
    return sum([ai * bi for (ai, bi) in zip(a, b)])
  end

  function vnormalized(a)
    d = sqrt(sum(vdot(a, a)))
    return vscale(a, 1. / d)
  end

  function tests()
    if vsum((1,2,3), (4,5,6)) != (5,7,9)
      println("vsum is broken")
    end
    if vlimit((1, 2, 3), 1.5, 2.5) != (1.5, 2, 2.5)
      println("vlimit is broken")
    end
    distance_function = function(x) return sqrt(x[1]^2 + x[2]^2 + x[3]^2) - 1 end
    gradient_function = distance_to_gradient_operator(distance_function)
    points, faces = build_3d_mesh((-1, -1, -1), (1, 1, 1), 0.25, distance_function, gradient_function)
    for face in faces
      for i in 1:3
        j = i == 3 ? 1 : i + 1
        edge_to_normal = vdot(
            points[face[i]],
            vnormalized(
              vsum(
                points[face[i]],
                vscale(points[face[j]], -1.))))
        if edge_to_normal < 0 || edge_to_normal > 0.2
          println("Mesh generator is broken ", edge_to_normal)
        end
      end
    end
  end
end


text:
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,jl:hydrogen
#     text_representation:
#       extension: .jl
#       format_name: hydrogen
#       format_version: '1.3'
#       jupytext_version: 1.11.2
#   kernelspec:
#     display_name: Julia 1.8.0-DEV
#     language: julia
#     name: julia-1.8
# ---

# %%
f(x::Int)::Int = x > 0 ? x / 2 : x
g(x::Int) = x > 0 ? typeassert(convert(Int, x / 2), Int) : typeassert(convert(Int, x), Int)

# %%
@code_warntype f(1)

# %%
@code_warntype g(1)

# %%
@code_typed f(1)

# %%
@code_typed g(1)

# %%

max_stars_repo_path: 0011/declaration of return type.jl

max_stars_repo_name: genkuroki/public

max_issues_repo_path: 0011/declaration of return type.jl

max_issues_repo_name: genkuroki/public

max_forks_repo_path: 0011/declaration of return type.jl

max_forks_repo_name: genkuroki/public


text:
int_rules_5_3_7 = @theory begin

    #= ::Subsection::Closed:: =#
    #= 5.3.7*Miscellaneous*inverse*tangent =#
    @apply_utils Antiderivative(atan(~a + ~(b') * (~x) ^ ~n), ~x) => ~x * atan(~a + ~b * (~x) ^ ~n) - ~b * ~n * Antiderivative((~x) ^ ~n / (1 + (~a) ^ 2 + 2 * ~a * ~b * (~x) ^ ~n + (~b) ^ 2 * (~x) ^ (2 * ~n)), ~x) <-- FreeQ([~a, ~b, ~n], ~x)
    @apply_utils Antiderivative(acot(~a + ~(b') * (~x) ^ ~n), ~x) => ~x * acot(~a + ~b * (~x) ^ ~n) + ~b * ~n * Antiderivative((~x) ^ ~n / (1 + (~a) ^ 2 + 2 * ~a * ~b * (~x) ^ ~n + (~b) ^ 2 * (~x) ^ (2 * ~n)), ~x) <-- FreeQ([~a, ~b, ~n], ~x)
    @apply_utils Antiderivative(atan(~(a') + ~(b') * (~x) ^ ~n) / ~x, ~x) => (im / 2) * Antiderivative(log((1 - im * ~a) - im * ~b * (~x) ^ ~n) / ~x, ~x) - (im / 2) * Antiderivative(log(1 + im * ~a + im * ~b * (~x) ^ ~n) / ~x, ~x) <-- FreeQ([~a, ~b, ~n], ~x)
    @apply_utils Antiderivative(acot(~(a') + ~(b') * (~x) ^ ~n) / ~x, ~x) => (im / 2) * Antiderivative(log(1 - im / (~a + ~b * (~x) ^ ~n)) / ~x, ~x) - (im / 2) * Antiderivative(log(1 + im / (~a + ~b * (~x) ^ ~n)) / ~x, ~x) <-- FreeQ([~a, ~b, ~n], ~x)
    @apply_utils Antiderivative((~x) ^ ~(m') * atan(~a + ~(b') * (~x) ^ ~n), ~x) => ((~x) ^ (~m + 1) * atan(~a + ~b * (~x) ^ ~n)) / (~m + 1) - ((~b * ~n) / (~m + 1)) * Antiderivative((~x) ^ (~m + ~n) / (1 + (~a) ^ 2 + 2 * ~a * ~b * (~x) ^ ~n + (~b) ^ 2 * (~x) ^ (2 * ~n)), ~x) <-- FreeQ([~a, ~b], ~x) && (RationalQ(~m, ~n) && (~m + 1 != 0 && ~m + 1 != ~n))
    @apply_utils Antiderivative((~x) ^ ~(m') * acot(~a + ~(b') * (~x) ^ ~n), ~x) => ((~x) ^ (~m + 1) * acot(~a + ~b * (~x) ^ ~n)) / (~m + 1) + ((~b * ~n) / (~m + 1)) * Antiderivative((~x) ^ (~m + ~n) / (1 + (~a) ^ 2 + 2 * ~a * ~b * (~x) ^ ~n + (~b) ^ 2 * (~x) ^ (2 * ~n)), ~x) <-- FreeQ([~a, ~b], ~x) && (RationalQ(~m, ~n) && (~m + 1 != 0 && ~m + 1 != ~n))
    @apply_utils Antiderivative(atan(~(a') + ~(b') * (~f) ^ (~(c') + ~(d') * ~x)), ~x) => (im / 2) * Antiderivative(log((1 - im * ~a) - im * ~b * (~f) ^ (~c + ~d * ~x)), ~x) - (im / 2) * Antiderivative(log(1 + im * ~a + im * ~b * (~f) ^ (~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~f], ~x)
    @apply_utils Antiderivative(acot(~(a') + ~(b') * (~f) ^ (~(c') + ~(d') * ~x)), ~x) => (im / 2) * Antiderivative(log(1 - im / (~a + ~b * (~f) ^ (~c + ~d * ~x))), ~x) - (im / 2) * Antiderivative(log(1 + im / (~a + ~b * (~f) ^ (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~f], ~x)
    @apply_utils Antiderivative((~x) ^ ~(m') * atan(~(a') + ~(b') * (~f) ^ (~(c') + ~(d') * ~x)), ~x) => (im / 2) * Antiderivative((~x) ^ ~m * log((1 - im * ~a) - im * ~b * (~f) ^ (~c + ~d * ~x)), ~x) - (im / 2) * Antiderivative((~x) ^ ~m * log(1 + im * ~a + im * ~b * (~f) ^ (~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~f], ~x) && (IntegerQ(~m) && ~m > 0)
    @apply_utils Antiderivative((~x) ^ ~(m') * acot(~(a') + ~(b') * (~f) ^ (~(c') + ~(d') * ~x)), ~x) => (im / 2) * Antiderivative((~x) ^ ~m * log(1 - im / (~a + ~b * (~f) ^ (~c + ~d * ~x))), ~x) - (im / 2) * Antiderivative((~x) ^ ~m * log(1 + im / (~a + ~b * (~f) ^ (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~f], ~x) && (IntegerQ(~m) && ~m > 0)
    @apply_utils Antiderivative(~(u') * atan(~(c') / (~(a') + ~(b') * (~x) ^ ~(n'))) ^ ~(m'), ~x) => Antiderivative(~u * acot(~a / ~c + (~b * (~x) ^ ~n) / ~c) ^ ~m, ~x) <-- FreeQ([~a, ~b, ~c, ~n, ~m], ~x)
    @apply_utils Antiderivative(~(u') * acot(~(c') / (~(a') + ~(b') * (~x) ^ ~(n'))) ^ ~(m'), ~x) => Antiderivative(~u * atan(~a / ~c + (~b * (~x) ^ ~n) / ~c) ^ ~m, ~x) <-- FreeQ([~a, ~b, ~c, ~n, ~m], ~x)
    @apply_utils Antiderivative(atan((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)), ~x) => ~x * atan((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2)) - ~c * Antiderivative(~x / sqrt(~a + ~b * (~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c], ~x) && EqQ(~b + (~c) ^ 2, 0)
    @apply_utils Antiderivative(acot((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)), ~x) => ~x * acot((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2)) + ~c * Antiderivative(~x / sqrt(~a + ~b * (~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c], ~x) && EqQ(~b + (~c) ^ 2, 0)
    @apply_utils Antiderivative(atan((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)) / ~x, ~x) => atan((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2)) * log(~x) - ~c * Antiderivative(log(~x) / sqrt(~a + ~b * (~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c], ~x) && EqQ(~b + (~c) ^ 2, 0)
    @apply_utils Antiderivative(acot((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)) / ~x, ~x) => acot((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2)) * log(~x) + ~c * Antiderivative(log(~x) / sqrt(~a + ~b * (~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c], ~x) && EqQ(~b + (~c) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * ~x) ^ ~(m') * atan((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)), ~x) => ((~d * ~x) ^ (~m + 1) * atan((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2))) / (~d * (~m + 1)) - (~c / (~d * (~m + 1))) * Antiderivative((~d * ~x) ^ (~m + 1) / sqrt(~a + ~b * (~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~m], ~x) && (EqQ(~b + (~c) ^ 2, 0) && NeQ(~m, -1))
    @apply_utils Antiderivative((~(d') * ~x) ^ ~(m') * acot((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)), ~x) => ((~d * ~x) ^ (~m + 1) * acot((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2))) / (~d * (~m + 1)) + (~c / (~d * (~m + 1))) * Antiderivative((~d * ~x) ^ (~m + 1) / sqrt(~a + ~b * (~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~m], ~x) && (EqQ(~b + (~c) ^ 2, 0) && NeQ(~m, -1))
    @apply_utils Antiderivative(1 / (sqrt(~(a') + ~(b') * (~x) ^ 2) * atan((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2))), ~x) => (1 / ~c) * log(atan((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2))) <-- FreeQ([~a, ~b, ~c], ~x) && EqQ(~b + (~c) ^ 2, 0)
    @apply_utils Antiderivative(1 / (sqrt(~(a') + ~(b') * (~x) ^ 2) * acot((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2))), ~x) => (-1 / ~c) * log(acot((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2))) <-- FreeQ([~a, ~b, ~c], ~x) && EqQ(~b + (~c) ^ 2, 0)
    @apply_utils Antiderivative(atan((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)) ^ ~(m') / sqrt(~(a') + ~(b') * (~x) ^ 2), ~x) => atan((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2)) ^ (~m + 1) / (~c * (~m + 1)) <-- FreeQ([~a, ~b, ~c, ~m], ~x) && (EqQ(~b + (~c) ^ 2, 0) && NeQ(~m, -1))
    @apply_utils Antiderivative(acot((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)) ^ ~(m') / sqrt(~(a') + ~(b') * (~x) ^ 2), ~x) => -(acot((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2)) ^ (~m + 1)) / (~c * (~m + 1)) <-- FreeQ([~a, ~b, ~c, ~m], ~x) && (EqQ(~b + (~c) ^ 2, 0) && NeQ(~m, -1))
    @apply_utils Antiderivative(atan((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)) ^ ~(m') / sqrt(~(d') + ~(e') * (~x) ^ 2), ~x) => (sqrt(~a + ~b * (~x) ^ 2) / sqrt(~d + ~e * (~x) ^ 2)) * Antiderivative(atan((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2)) ^ ~m / sqrt(~a + ~b * (~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m], ~x) && (EqQ(~b + (~c) ^ 2, 0) && EqQ(~b * ~d - ~a * ~e, 0))
    @apply_utils Antiderivative(acot((~(c') * ~x) / sqrt(~(a') + ~(b') * (~x) ^ 2)) ^ ~(m') / sqrt(~(d') + ~(e') * (~x) ^ 2), ~x) => (sqrt(~a + ~b * (~x) ^ 2) / sqrt(~d + ~e * (~x) ^ 2)) * Antiderivative(acot((~c * ~x) / sqrt(~a + ~b * (~x) ^ 2)) ^ ~m / sqrt(~a + ~b * (~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m], ~x) && (EqQ(~b + (~c) ^ 2, 0) && EqQ(~b * ~d - ~a * ~e, 0))
    @apply_utils Antiderivative(~(u') * atan(~v + ~(s') * sqrt(~w)), ~x) => ((pi * ~s) / 4) * Antiderivative(~u, ~x) + (1 / 2) * Antiderivative(~u * atan(~v), ~x) <-- EqQ((~s) ^ 2, 1) && EqQ(~w, (~v) ^ 2 + 1)
    @apply_utils Antiderivative(~(u') * acot(~v + ~(s') * sqrt(~w)), ~x) => ((pi * ~s) / 4) * Antiderivative(~u, ~x) - (1 / 2) * Antiderivative(~u * atan(~v), ~x) <-- EqQ((~s) ^ 2, 1) && EqQ(~w, (~v) ^ 2 + 1)
    If(TrueQ($LoadShowSteps), Antiderivative((~u)*(~v)^(~n'), ~x) := With([tmp = InverseFunctionOfLinear(u, x)], ShowStep("", "Antiderivative(f(x,atan(a+b*x))/(1+(a+b*x)^2),x)", "Subst(Antiderivative(f(-a/b+tan(x)/b,x),x),x,atan(a+b*x))/b", Hold( (-Discriminant(v, x)/(4*Coefficient(v, x, 2)))^n/ Coefficient(tmp((1)), x, 1)* Subst( Antiderivative(SimplifyIntegrand( SubstForInverseFunction(u, tmp, x)*sec(x)^(2*(n + 1)), x), x), x, tmp))) <-- Not(FalseQ(tmp)) && EqQ(Head(tmp), atan) && EqQ(Discriminant(v, x)*tmp((1))^2 + D(v, x)^2, 0)) <-- SimplifyFlag && QuadraticQ(v, x) && ILtQ(n, 0) && NegQ(Discriminant(v, x)) && MatchQ(u, (~r')*(~f)^(~w) <-- FreeQ(f, x)), Antiderivative((~u)*(~v)^(~n'), ~x) := With([tmp = InverseFunctionOfLinear(u, x)], (-Discriminant(v, x)/(4*Coefficient(v, x, 2)))^n/ Coefficient(tmp((1)), x, 1)* Subst( Antiderivative(SimplifyIntegrand( SubstForInverseFunction(u, tmp, x)*sec(x)^(2*(n + 1)), x), x), x, tmp) <-- Not(FalseQ(tmp)) && EqQ(Head(tmp), atan) && EqQ(Discriminant(v, x)*tmp((1))^2 + D(v, x)^2, 0)) <-- QuadraticQ(v, x) && ILtQ(n, 0) && NegQ(Discriminant(v, x)) && MatchQ(u, (~r')*(~f)^(~w) <-- FreeQ(f, x)))
    If(TrueQ($LoadShowSteps), Antiderivative((~u)*(~v)^(~n'), ~x) := With([tmp = InverseFunctionOfLinear(u, x)], ShowStep("", "Antiderivative(f(x,acot(a+b*x))/(1+(a+b*x)^2),x)", "-Subst(Antiderivative(f(-a/b+cot(x)/b,x),x),x,acot(a+b*x))/b", Hold( -(-Discriminant(v, x)/(4*Coefficient(v, x, 2)))^n/ Coefficient(tmp((1)), x, 1)* Subst( Antiderivative(SimplifyIntegrand( SubstForInverseFunction(u, tmp, x)*csc(x)^(2*(n + 1)), x), x), x, tmp))) <-- Not(FalseQ(tmp)) && EqQ(Head(tmp), acot) && EqQ(Discriminant(v, x)*tmp((1))^2 + D(v, x)^2, 0)) <-- SimplifyFlag && QuadraticQ(v, x) && ILtQ(n, 0) && NegQ(Discriminant(v, x)) && MatchQ(u, (~r')*(~f)^(~w) <-- FreeQ(f, x)), Antiderivative((~u)*(~v)^(~n'), ~x) := With([tmp = InverseFunctionOfLinear(u, x)], -(-Discriminant(v, x)/(4*Coefficient(v, x, 2)))^n/ Coefficient(tmp((1)), x, 1)* Subst( Antiderivative(SimplifyIntegrand( SubstForInverseFunction(u, tmp, x)*csc(x)^(2*(n + 1)), x), x), x, tmp) <-- Not(FalseQ(tmp)) && EqQ(Head(tmp), acot) && EqQ(Discriminant(v, x)*tmp((1))^2 + D(v, x)^2, 0)) <-- QuadraticQ(v, x) && ILtQ(n, 0) && NegQ(Discriminant(v, x)) && MatchQ(u, (~r')*(~f)^(~w) <-- FreeQ(f, x)))
    @apply_utils Antiderivative(atan(~(c') + ~(d') * tan(~(a') + ~(b') * ~x)), ~x) => ~x * atan(~c + ~d * tan(~a + ~b * ~x)) - im * ~b * Antiderivative(~x / (~c + im * ~d + ~c * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && EqQ((~c + im * ~d) ^ 2, -1)
    @apply_utils Antiderivative(acot(~(c') + ~(d') * tan(~(a') + ~(b') * ~x)), ~x) => ~x * acot(~c + ~d * tan(~a + ~b * ~x)) + im * ~b * Antiderivative(~x / (~c + im * ~d + ~c * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && EqQ((~c + im * ~d) ^ 2, -1)
    @apply_utils Antiderivative(atan(~(c') + ~(d') * cot(~(a') + ~(b') * ~x)), ~x) => ~x * atan(~c + ~d * cot(~a + ~b * ~x)) - im * ~b * Antiderivative(~x / ((~c - im * ~d) - ~c * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && EqQ((~c - im * ~d) ^ 2, -1)
    @apply_utils Antiderivative(acot(~(c') + ~(d') * cot(~(a') + ~(b') * ~x)), ~x) => ~x * acot(~c + ~d * cot(~a + ~b * ~x)) + im * ~b * Antiderivative(~x / ((~c - im * ~d) - ~c * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && EqQ((~c - im * ~d) ^ 2, -1)
    @apply_utils Antiderivative(atan(~(c') + ~(d') * tan(~(a') + ~(b') * ~x)), ~x) => (~x * atan(~c + ~d * tan(~a + ~b * ~x)) - ~b * (1 + im * ~c + ~d) * Antiderivative((~x * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / (((1 + im * ~c) - ~d) + (1 + im * ~c + ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x)) + ~b * ((1 - im * ~c) - ~d) * Antiderivative((~x * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / ((1 - im * ~c) + ~d + ((1 - im * ~c) - ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~c + im * ~d) ^ 2, -1)
    @apply_utils Antiderivative(acot(~(c') + ~(d') * tan(~(a') + ~(b') * ~x)), ~x) => (~x * acot(~c + ~d * tan(~a + ~b * ~x)) + ~b * (1 + im * ~c + ~d) * Antiderivative((~x * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / (((1 + im * ~c) - ~d) + (1 + im * ~c + ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x)) - ~b * ((1 - im * ~c) - ~d) * Antiderivative((~x * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / ((1 - im * ~c) + ~d + ((1 - im * ~c) - ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~c + im * ~d) ^ 2, -1)
    @apply_utils Antiderivative(atan(~(c') + ~(d') * cot(~(a') + ~(b') * ~x)), ~x) => (~x * atan(~c + ~d * cot(~a + ~b * ~x)) + ~b * ((1 + im * ~c) - ~d) * Antiderivative((~x * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / ((1 + im * ~c + ~d) - ((1 + im * ~c) - ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x)) - ~b * ((1 - im * ~c) + ~d) * Antiderivative((~x * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / (((1 - im * ~c) - ~d) - ((1 - im * ~c) + ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~c + im * ~d) ^ 2, -1)
    @apply_utils Antiderivative(acot(~(c') + ~(d') * cot(~(a') + ~(b') * ~x)), ~x) => (~x * acot(~c + ~d * cot(~a + ~b * ~x)) - ~b * ((1 + im * ~c) - ~d) * Antiderivative((~x * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / ((1 + im * ~c + ~d) - ((1 + im * ~c) - ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x)) + ~b * ((1 - im * ~c) + ~d) * Antiderivative((~x * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / (((1 - im * ~c) - ~d) - ((1 - im * ~c) + ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~c - im * ~d) ^ 2, -1)
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(~(c') + ~(d') * tan(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * atan(~c + ~d * tan(~a + ~b * ~x))) / (~f * (~m + 1)) - ((im * ~b) / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) / (~c + im * ~d + ~c * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~c + im * ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(~(c') + ~(d') * tan(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * acot(~c + ~d * tan(~a + ~b * ~x))) / (~f * (~m + 1)) + ((im * ~b) / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) / (~c + im * ~d + ~c * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~c + im * ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(~(c') + ~(d') * cot(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * atan(~c + ~d * cot(~a + ~b * ~x))) / (~f * (~m + 1)) - ((im * ~b) / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) / ((~c - im * ~d) - ~c * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~c - im * ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(~(c') + ~(d') * cot(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * acot(~c + ~d * cot(~a + ~b * ~x))) / (~f * (~m + 1)) + ((im * ~b) / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) / ((~c - im * ~d) - ~c * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~c - im * ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(~(c') + ~(d') * tan(~(a') + ~(b') * ~x)), ~x) => (((~e + ~f * ~x) ^ (~m + 1) * atan(~c + ~d * tan(~a + ~b * ~x))) / (~f * (~m + 1)) - ((~b * (1 + im * ~c + ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / (((1 + im * ~c) - ~d) + (1 + im * ~c + ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x)) + ((~b * ((1 - im * ~c) - ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / ((1 - im * ~c) + ~d + ((1 - im * ~c) - ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~c + im * ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(~(c') + ~(d') * tan(~(a') + ~(b') * ~x)), ~x) => (((~e + ~f * ~x) ^ (~m + 1) * acot(~c + ~d * tan(~a + ~b * ~x))) / (~f * (~m + 1)) + ((~b * (1 + im * ~c + ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / (((1 + im * ~c) - ~d) + (1 + im * ~c + ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x)) - ((~b * ((1 - im * ~c) - ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / ((1 - im * ~c) + ~d + ((1 - im * ~c) - ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~c + im * ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(~(c') + ~(d') * cot(~(a') + ~(b') * ~x)), ~x) => (((~e + ~f * ~x) ^ (~m + 1) * atan(~c + ~d * cot(~a + ~b * ~x))) / (~f * (~m + 1)) + ((~b * ((1 + im * ~c) - ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / ((1 + im * ~c + ~d) - ((1 + im * ~c) - ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x)) - ((~b * ((1 - im * ~c) + ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / (((1 - im * ~c) - ~d) - ((1 - im * ~c) + ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~c - im * ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(~(c') + ~(d') * cot(~(a') + ~(b') * ~x)), ~x) => (((~e + ~f * ~x) ^ (~m + 1) * acot(~c + ~d * cot(~a + ~b * ~x))) / (~f * (~m + 1)) - ((~b * ((1 + im * ~c) - ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / ((1 + im * ~c + ~d) - ((1 + im * ~c) - ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x)) + ((~b * ((1 - im * ~c) + ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)) / (((1 - im * ~c) - ~d) - ((1 - im * ~c) + ~d) * ℯ ^ (2 * im * ~a + 2 * im * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~c - im * ~d) ^ 2, -1))
    @apply_utils Antiderivative(atan(tanh(~(a') + ~(b') * ~x)), ~x) => ~x * atan(tanh(~a + ~b * ~x)) - ~b * Antiderivative(~x * sech(2 * ~a + 2 * ~b * ~x), ~x) <-- FreeQ([~a, ~b], ~x)
    @apply_utils Antiderivative(acot(tanh(~(a') + ~(b') * ~x)), ~x) => ~x * acot(tanh(~a + ~b * ~x)) + ~b * Antiderivative(~x * sech(2 * ~a + 2 * ~b * ~x), ~x) <-- FreeQ([~a, ~b], ~x)
    @apply_utils Antiderivative(atan(coth(~(a') + ~(b') * ~x)), ~x) => ~x * atan(coth(~a + ~b * ~x)) + ~b * Antiderivative(~x * sech(2 * ~a + 2 * ~b * ~x), ~x) <-- FreeQ([~a, ~b], ~x)
    @apply_utils Antiderivative(acot(coth(~(a') + ~(b') * ~x)), ~x) => ~x * acot(coth(~a + ~b * ~x)) - ~b * Antiderivative(~x * sech(2 * ~a + 2 * ~b * ~x), ~x) <-- FreeQ([~a, ~b], ~x)
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(tanh(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * atan(tanh(~a + ~b * ~x))) / (~f * (~m + 1)) - (~b / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) * sech(2 * ~a + 2 * ~b * ~x), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && IGtQ(~m, 0)
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(tanh(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * acot(tanh(~a + ~b * ~x))) / (~f * (~m + 1)) + (~b / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) * sech(2 * ~a + 2 * ~b * ~x), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && IGtQ(~m, 0)
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(coth(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * atan(coth(~a + ~b * ~x))) / (~f * (~m + 1)) + (~b / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) * sech(2 * ~a + 2 * ~b * ~x), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && IGtQ(~m, 0)
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(coth(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * acot(coth(~a + ~b * ~x))) / (~f * (~m + 1)) - (~b / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) * sech(2 * ~a + 2 * ~b * ~x), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && IGtQ(~m, 0)
    @apply_utils Antiderivative(atan(~(c') + ~(d') * tanh(~(a') + ~(b') * ~x)), ~x) => ~x * atan(~c + ~d * tanh(~a + ~b * ~x)) - ~b * Antiderivative(~x / ((~c - ~d) + ~c * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && EqQ((~c - ~d) ^ 2, -1)
    @apply_utils Antiderivative(acot(~(c') + ~(d') * tanh(~(a') + ~(b') * ~x)), ~x) => ~x * acot(~c + ~d * tanh(~a + ~b * ~x)) + ~b * Antiderivative(~x / ((~c - ~d) + ~c * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && EqQ((~c - ~d) ^ 2, -1)
    @apply_utils Antiderivative(atan(~(c') + ~(d') * coth(~(a') + ~(b') * ~x)), ~x) => ~x * atan(~c + ~d * coth(~a + ~b * ~x)) - ~b * Antiderivative(~x / ((~c - ~d) - ~c * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && EqQ((~c - ~d) ^ 2, -1)
    @apply_utils Antiderivative(acot(~(c') + ~(d') * coth(~(a') + ~(b') * ~x)), ~x) => ~x * acot(~c + ~d * coth(~a + ~b * ~x)) + ~b * Antiderivative(~x / ((~c - ~d) - ~c * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && EqQ((~c - ~d) ^ 2, -1)
    @apply_utils Antiderivative(atan(~(c') + ~(d') * tanh(~(a') + ~(b') * ~x)), ~x) => (~x * atan(~c + ~d * tanh(~a + ~b * ~x)) + im * ~b * ((im - ~c) - ~d) * Antiderivative((~x * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / ((im - ~c) + ~d + ((im - ~c) - ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x)) - im * ~b * (im + ~c + ~d) * Antiderivative((~x * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im + ~c) - ~d) + (im + ~c + ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~c - ~d) ^ 2, -1)
    @apply_utils Antiderivative(acot(~(c') + ~(d') * tanh(~(a') + ~(b') * ~x)), ~x) => (~x * acot(~c + ~d * tanh(~a + ~b * ~x)) - im * ~b * ((im - ~c) - ~d) * Antiderivative((~x * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / ((im - ~c) + ~d + ((im - ~c) - ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x)) + im * ~b * (im + ~c + ~d) * Antiderivative((~x * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im + ~c) - ~d) + (im + ~c + ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~c - ~d) ^ 2, -1)
    @apply_utils Antiderivative(atan(~(c') + ~(d') * coth(~(a') + ~(b') * ~x)), ~x) => (~x * atan(~c + ~d * coth(~a + ~b * ~x)) - im * ~b * ((im - ~c) - ~d) * Antiderivative((~x * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im - ~c) + ~d) - ((im - ~c) - ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x)) + im * ~b * (im + ~c + ~d) * Antiderivative((~x * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im + ~c) - ~d) - (im + ~c + ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~c - ~d) ^ 2, -1)
    @apply_utils Antiderivative(acot(~(c') + ~(d') * coth(~(a') + ~(b') * ~x)), ~x) => (~x * acot(~c + ~d * coth(~a + ~b * ~x)) + im * ~b * ((im - ~c) - ~d) * Antiderivative((~x * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im - ~c) + ~d) - ((im - ~c) - ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x)) - im * ~b * (im + ~c + ~d) * Antiderivative((~x * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im + ~c) - ~d) - (im + ~c + ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~c - ~d) ^ 2, -1)
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(~(c') + ~(d') * tanh(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * atan(~c + ~d * tanh(~a + ~b * ~x))) / (~f * (~m + 1)) - (~b / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) / ((~c - ~d) + ~c * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~c - ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(~(c') + ~(d') * tanh(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * acot(~c + ~d * tanh(~a + ~b * ~x))) / (~f * (~m + 1)) + (~b / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) / ((~c - ~d) + ~c * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~c - ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(~(c') + ~(d') * coth(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * atan(~c + ~d * coth(~a + ~b * ~x))) / (~f * (~m + 1)) - (~b / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) / ((~c - ~d) - ~c * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~c - ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(~(c') + ~(d') * coth(~(a') + ~(b') * ~x)), ~x) => ((~e + ~f * ~x) ^ (~m + 1) * acot(~c + ~d * coth(~a + ~b * ~x))) / (~f * (~m + 1)) + (~b / (~f * (~m + 1))) * Antiderivative((~e + ~f * ~x) ^ (~m + 1) / ((~c - ~d) - ~c * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~c - ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(~(c') + ~(d') * tanh(~(a') + ~(b') * ~x)), ~x) => (((~e + ~f * ~x) ^ (~m + 1) * atan(~c + ~d * tanh(~a + ~b * ~x))) / (~f * (~m + 1)) + ((im * ~b * ((im - ~c) - ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / ((im - ~c) + ~d + ((im - ~c) - ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x)) - ((im * ~b * (im + ~c + ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im + ~c) - ~d) + (im + ~c + ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~c - ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(~(c') + ~(d') * tanh(~(a') + ~(b') * ~x)), ~x) => (((~e + ~f * ~x) ^ (~m + 1) * acot(~c + ~d * tanh(~a + ~b * ~x))) / (~f * (~m + 1)) - ((im * ~b * ((im - ~c) - ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / ((im - ~c) + ~d + ((im - ~c) - ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x)) + ((im * ~b * (im + ~c + ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im + ~c) - ~d) + (im + ~c + ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~c - ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * atan(~(c') + ~(d') * coth(~(a') + ~(b') * ~x)), ~x) => (((~e + ~f * ~x) ^ (~m + 1) * atan(~c + ~d * coth(~a + ~b * ~x))) / (~f * (~m + 1)) - ((im * ~b * ((im - ~c) - ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im - ~c) + ~d) - ((im - ~c) - ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x)) + ((im * ~b * (im + ~c + ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im + ~c) - ~d) - (im + ~c + ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~c - ~d) ^ 2, -1))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * acot(~(c') + ~(d') * coth(~(a') + ~(b') * ~x)), ~x) => (((~e + ~f * ~x) ^ (~m + 1) * acot(~c + ~d * coth(~a + ~b * ~x))) / (~f * (~m + 1)) + ((im * ~b * ((im - ~c) - ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im - ~c) + ~d) - ((im - ~c) - ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x)) - ((im * ~b * (im + ~c + ~d)) / (~f * (~m + 1))) * Antiderivative(((~e + ~f * ~x) ^ (~m + 1) * ℯ ^ (2 * ~a + 2 * ~b * ~x)) / (((im + ~c) - ~d) - (im + ~c + ~d) * ℯ ^ (2 * ~a + 2 * ~b * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~c - ~d) ^ 2, -1))
    @apply_utils Antiderivative(atan(~u), ~x) => ~x * atan(~u) - Antiderivative(SimplifyIntegrand((~x * D(~u, ~x)) / (1 + (~u) ^ 2), ~x), ~x) <-- InverseFunctionFreeQ(~u, ~x)
    @apply_utils Antiderivative(acot(~u), ~x) => ~x * acot(~u) + Antiderivative(SimplifyIntegrand((~x * D(~u, ~x)) / (1 + (~u) ^ 2), ~x), ~x) <-- InverseFunctionFreeQ(~u, ~x)
    @apply_utils Antiderivative((~(c') + ~(d') * ~x) ^ ~(m') * (~(a') + ~(b') * atan(~u)), ~x) => ((~c + ~d * ~x) ^ (~m + 1) * (~a + ~b * atan(~u))) / (~d * (~m + 1)) - (~b / (~d * (~m + 1))) * Antiderivative(SimplifyIntegrand(((~c + ~d * ~x) ^ (~m + 1) * D(~u, ~x)) / (1 + (~u) ^ 2), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~m], ~x) && (NeQ(~m, -1) && (InverseFunctionFreeQ(~u, ~x) && (Not(FunctionOfQ((~c + ~d * ~x) ^ (~m + 1), ~u, ~x)) && FalseQ(PowerVariableExpn(~u, ~m + 1, ~x)))))
    @apply_utils Antiderivative((~(c') + ~(d') * ~x) ^ ~(m') * (~(a') + ~(b') * acot(~u)), ~x) => ((~c + ~d * ~x) ^ (~m + 1) * (~a + ~b * acot(~u))) / (~d * (~m + 1)) + (~b / (~d * (~m + 1))) * Antiderivative(SimplifyIntegrand(((~c + ~d * ~x) ^ (~m + 1) * D(~u, ~x)) / (1 + (~u) ^ 2), ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~m], ~x) && (NeQ(~m, -1) && (InverseFunctionFreeQ(~u, ~x) && (Not(FunctionOfQ((~c + ~d * ~x) ^ (~m + 1), ~u, ~x)) && FalseQ(PowerVariableExpn(~u, ~m + 1, ~x)))))
    @apply_utils Antiderivative(~v * (~(a') + ~(b') * atan(~u)), ~x) => With([w = IntHide(~v, ~x)], Dist(~a + ~b * atan(~u), w, ~x) - ~b * Antiderivative(SimplifyIntegrand((w * D(~u, ~x)) / (1 + (~u) ^ 2), ~x), ~x) <-- InverseFunctionFreeQ(w, ~x)) <-- FreeQ([~a, ~b], ~x) && (InverseFunctionFreeQ(~u, ~x) && (Not(MatchQ(~v, (~(c') + ~(d') * ~x) ^ ~(m') <-- FreeQ([c, d, m], ~x))) && FalseQ(FunctionOfLinear(~v * (~a + ~b * atan(~u)), ~x))))
    @apply_utils Antiderivative(~v * (~(a') + ~(b') * acot(~u)), ~x) => With([w = IntHide(~v, ~x)], Dist(~a + ~b * acot(~u), w, ~x) + ~b * Antiderivative(SimplifyIntegrand((w * D(~u, ~x)) / (1 + (~u) ^ 2), ~x), ~x) <-- InverseFunctionFreeQ(w, ~x)) <-- FreeQ([~a, ~b], ~x) && (InverseFunctionFreeQ(~u, ~x) && (Not(MatchQ(~v, (~(c') + ~(d') * ~x) ^ ~(m') <-- FreeQ([c, d, m], ~x))) && FalseQ(FunctionOfLinear(~v * (~a + ~b * acot(~u)), ~x))))
    @apply_utils Antiderivative((atan(~v) * log(~w)) / (~(a') + ~(b') * ~x), ~x) => (im / 2) * Antiderivative((log(1 - im * ~v) * log(~w)) / (~a + ~b * ~x), ~x) - (im / 2) * Antiderivative((log(1 + im * ~v) * log(~w)) / (~a + ~b * ~x), ~x) <-- FreeQ([~a, ~b], ~x) && (LinearQ(~v, ~x) && (LinearQ(~w, ~x) && (EqQ(Simplify(D(~v / (~a + ~b * ~x), ~x)), 0) && EqQ(Simplify(D(~w / (~a + ~b * ~x), ~x)), 0))))
    @apply_utils Antiderivative(atan(~v) * log(~w), ~x) => (~x * atan(~v) * log(~w) - Antiderivative(SimplifyIntegrand((~x * log(~w) * D(~v, ~x)) / (1 + (~v) ^ 2), ~x), ~x)) - Antiderivative(SimplifyIntegrand((~x * atan(~v) * D(~w, ~x)) / ~w, ~x), ~x) <-- InverseFunctionFreeQ(~v, ~x) && InverseFunctionFreeQ(~w, ~x)
    @apply_utils Antiderivative(acot(~v) * log(~w), ~x) => (~x * acot(~v) * log(~w) + Antiderivative(SimplifyIntegrand((~x * log(~w) * D(~v, ~x)) / (1 + (~v) ^ 2), ~x), ~x)) - Antiderivative(SimplifyIntegrand((~x * acot(~v) * D(~w, ~x)) / ~w, ~x), ~x) <-- InverseFunctionFreeQ(~v, ~x) && InverseFunctionFreeQ(~w, ~x)
    @apply_utils Antiderivative(~u * atan(~v) * log(~w), ~x) => With([z = IntHide(~u, ~x)], (Dist(atan(~v) * log(~w), z, ~x) - Antiderivative(SimplifyIntegrand((z * log(~w) * D(~v, ~x)) / (1 + (~v) ^ 2), ~x), ~x)) - Antiderivative(SimplifyIntegrand((z * atan(~v) * D(~w, ~x)) / ~w, ~x), ~x) <-- InverseFunctionFreeQ(z, ~x)) <-- InverseFunctionFreeQ(~v, ~x) && InverseFunctionFreeQ(~w, ~x)
    @apply_utils Antiderivative(~u * acot(~v) * log(~w), ~x) => With([z = IntHide(~u, ~x)], (Dist(acot(~v) * log(~w), z, ~x) + Antiderivative(SimplifyIntegrand((z * log(~w) * D(~v, ~x)) / (1 + (~v) ^ 2), ~x), ~x)) - Antiderivative(SimplifyIntegrand((z * acot(~v) * D(~w, ~x)) / ~w, ~x), ~x) <-- InverseFunctionFreeQ(z, ~x)) <-- InverseFunctionFreeQ(~v, ~x) && InverseFunctionFreeQ(~w, ~x)
end

max_stars_repo_path: src/rules/5 Inverse trig functions/5.3 Inverse tangent/5.3.7 Miscellaneous inverse tangent.jl


text:
module BackendModels
    using DataStructures
    export Device, Results
    export UndirectedGraphModel, StateVectorModel, TensorNetworkStatesModel
    export StateVectorResults, TensorNetworkStatesResults

    abstract type Device end
    abstract type Results end

    struct UndirectedGraphModel <: Device
    end

    function UndirectedGraphModel(x)
        return UndirectedGraphModel()
    end

    struct StateVectorModel <: Device
        zero_state::Bool
        init_state::Array{ComplexF64, 1}
    end

    function StateVectorModel(init_state)
        if length(init_state) == 0
            return StateVectorModel(true, [0im])
        else
            return StateVectorModel(false, init_state)
        end
    end

    struct StateVectorResults <: Results
        states::Array{Any, 1}
        cregs::Array{Any, 1}
    end

    struct TensorNetworkStatesModel <: Device
        zero_state::Bool
        init_state::Array{ComplexF64, 1}
        param::Number
    end

    function TensorNetworkStatesModel(x)
        if length(x) == 1
            return TensorNetworkStatesModel(true, [0im], x[1])
        else
            return TensorNetworkStatesModel(false, x[2], x[1])
        end
    end

    struct TensorNetworkStatesResults <: Results
        states::Array{ComplexF64, 1}
        info::OrderedDict{Any,Any}
    end

end

max_stars_repo_name: ryuNagai/blueqat-julia

max_issues_repo_name: ryuNagai/blueqat-julia

max_forks_repo_name: ryuNagai/blueqat-julia


text:
module TestCat
    using Base.Test
    using DataFrames

    #
    # hcat
    #

    nvint = NullableArray(Nullable{Int}[1, 2, Nullable(), 4])
    nvstr = NullableArray(Nullable{String}["one", "two", Nullable(), "four"])

    df2 = DataFrame(Any[nvint, nvstr])
    df3 = DataFrame(Any[nvint])
    df4 = convert(DataFrame, [1:4 1:4])
    df5 = DataFrame(Any[NullableArray([1,2,3,4]), nvstr])

    dfh = hcat(df3, df4)
    @test size(dfh, 2) == 3
    @test names(dfh) == [:x1, :x1_1, :x2]
    @test isequal(dfh[:x1], df3[:x1])
    @test isequal(dfh, [df3 df4])
    @test isequal(dfh, DataFrames.hcat!(DataFrame(), df3, df4))

    dfh3 = hcat(df3, df4, df5)
    @test names(dfh3) == [:x1, :x1_1, :x2, :x1_2, :x2_1]
    @test isequal(dfh3, hcat(dfh, df5))
    @test isequal(dfh3, DataFrames.hcat!(DataFrame(), df3, df4, df5))

    @test isequal(df2, DataFrames.hcat!(df2))

    #
    # vcat
    #

    null_df = DataFrame(Int, 0, 0)
    df = DataFrame(Int, 4, 3)

    # Assignment of rows
    df[1, :] = df[1, :]
    df[1:2, :] = df[1:2, :]
    df[[true,false,false,true], :] = df[2:3, :]

    # Scalar broadcasting assignment of rows
    df[1, :] = 1
    df[1:2, :] = 1
    df[[true,false,false,true], :] = 3

    # Vector broadcasting assignment of rows
    df[1:2, :] = [2,3]
    df[[true,false,false,true], :] = [2,3]

    # Assignment of columns
    df[1] = zeros(4)
    df[:, 2] = ones(4)

    # Broadcasting assignment of columns
    df[:, 1] = 1
    df[1] = 3
    df[:x3] = 2

    # assignment of subframes
    df[1, 1:2] = df[2, 2:3]
    df[1:2, 1:2] = df[2:3, 2:3]
    df[[true,false,false,true], 2:3] = df[1:2,1:2]

    # scalar broadcasting assignment of subframes
    df[1, 1:2] = 3
    df[1:2, 1:2] = 3
    df[[true,false,false,true], 2:3] = 3

    # vector broadcasting assignment of subframes
    df[1:2, 1:2] = [3,2]
    df[[true,false,false,true], 2:3] = [2,3]

    vcat([])
    vcat(null_df)
    vcat(null_df, null_df)
    vcat(null_df, df)
    vcat(df, null_df)
    vcat(df, df)
    vcat(df, df, df)
    @test vcat(DataFrame[]) == DataFrame()

    alt_df = deepcopy(df)
    vcat(df, alt_df)

    # Don't fail on non-matching types
    df[1] = zeros(Int, nrow(df))
    vcat(df, alt_df)

    # Don't fail on non-matching names
    names!(alt_df, [:A, :B, :C])
    vcat(df, alt_df)

    dfr = vcat(df4, df4)
    @test size(dfr, 1) == 8
    @test names(df4) == names(dfr)
    @test isequal(dfr, [df4; df4])

    dfr = vcat(df2, df3)
    @test size(dfr) == (8,2)
    @test names(df2) == names(dfr)
    @test isnull(dfr[8,:x2])

    # Eltype promotion
    # Fails on Julia 0.4 since promote_type(Nullable{Int}, Nullable{Float64}) gives Nullable{T}
    if VERSION >= v"0.5.0-dev"
        @test eltypes(vcat(DataFrame(a = [1]), DataFrame(a = [2.1]))) == [Nullable{Float64}]
        @test eltypes(vcat(DataFrame(a = NullableArray(Int, 1)), DataFrame(a = [2.1]))) == [Nullable{Float64}]
    else
        @test eltypes(vcat(DataFrame(a = [1]), DataFrame(a = [2.1]))) == [Nullable{Any}]
        @test eltypes(vcat(DataFrame(a = NullableArray(Int, 1)), DataFrame(a = [2.1]))) == [Nullable{Any}]
    end

    # Minimal container type promotion
    dfa = DataFrame(a = CategoricalArray([1, 2, 2]))
    dfb = DataFrame(a = CategoricalArray([2, 3, 4]))
    dfc = DataFrame(a = NullableArray([2, 3, 4]))
    dfd = DataFrame(Any[2:4], [:a])
    dfab = vcat(dfa, dfb)
    dfac = vcat(dfa, dfc)
    @test isequal(dfab[:a], Nullable{Int}[1, 2, 2, 2, 3, 4])
    @test isequal(dfac[:a], Nullable{Int}[1, 2, 2, 2, 3, 4])
    @test isa(dfab[:a], NullableCategoricalVector{Int})
    # Fails on Julia 0.4 since promote_type(Nullable{Int}, Nullable{Float64}) gives Nullable{T}
    if VERSION >= v"0.5.0-dev"
        @test isa(dfac[:a], NullableCategoricalVector{Int})
    else
        @test isa(dfac[:a], NullableCategoricalVector{Any})
    end
    # ^^ container may flip if container promotion happens in Base/DataArrays
    dc = vcat(dfd, dfc)
    @test isequal(vcat(dfc, dfd), dc)

    # Zero-row DataFrames
    dfc0 = similar(dfc, 0)
    @test isequal(vcat(dfd, dfc0, dfc), dc)
    @test eltypes(vcat(dfd, dfc0)) == eltypes(dc)

    # Missing columns
    rename!(dfd, :a, :b)
    dfda = DataFrame(b = NullableArray(Nullable{Int}[2, 3, 4, Nullable(), Nullable(), Nullable()]),
                     a = NullableCategoricalVector(Nullable{Int}[Nullable(), Nullable(), Nullable(), 1, 2, 2]))
    @test isequal(vcat(dfd, dfa), dfda)

    # Alignment
    @test isequal(vcat(dfda, dfd, dfa), vcat(dfda, dfda))

    # vcat should be able to concatenate different implementations of AbstractDataFrame (PR #944)
    @test isequal(vcat(sub(DataFrame(A=1:3),2),DataFrame(A=4:5)), DataFrame(A=[2,4,5]))
end


text:
immutable con_powerlaw <: ContinuousUnivariateDistribution
    α::Float64
    θ::Float64

    function con_powerlaw(α::Real, θ::Real)
        @check_args(con_powerlaw, α > zero(α) && θ > zero(θ))
        new(α, θ)
    end
    con_powerlaw(α::Real) = con_powerlaw(α, 1.0)
    con_powerlaw() = new(1.0, 1.0)
end
@distr_support con_powerlaw d.θ Inf
#### Parameters

shape(d::con_powerlaw) = d.α
scale(d::con_powerlaw) = d.θ
params(d::con_powerlaw) = (d.α, d.θ)
#### Statistics

mean(d::con_powerlaw) = ((α, θ) = params(d); α > 2.0 ? θ *((α - 1.0)/(α - 2.0)) : Inf)

median(d::con_powerlaw) = ((α, θ) = params(d);α > 1.0 ? 2.0^(1.0/(α - 1.0)) * θ : NaN)
mode(d::con_powerlaw) = d.θ
function var(d::con_powerlaw)
    (α, θ) = params(d)
    α > 3.0 ? (θ^2 * (α-1)) / ((α - 2.0)^2 * (α - 3.0)) : Inf
end

function skewness(d::con_powerlaw)
    α = shape(d)
    α > 4.0 ? ((2.0 * (α)) / (α - 4.0)) * sqrt((α - 3.0) / (α-1)) : NaN
end

function kurtosis(d::con_powerlaw)
    α = shape(d)
    α > 5.0 ? (6.0 * ((α-1)^3 + (α-1)^2 - 6.0 * (α-1) - 2.0)) / ((α-1) * (α - 4.0) * (α - 5.0)) : NaN
end

entropy(d::con_powerlaw) = ((α, θ) = params(d); log(θ / (α-1)) + 1.0 / (α-1) + 1.0)

#### Evaluation

function pdf(d::con_powerlaw, x::Float64)
    (α, θ) = params(d)
    x >= θ ? ((α-1.0)/θ) * ((x/θ)^(-α)) : 0.0
end

function pdf(d::con_powerlaw, x::AbstractArray)
    (α, θ) = params(d)
    cons = ((α-1.0)/θ)
    pdfs = Array(Float64,0)
    for num in x
        push!(pdfs,(num >= θ ? cons * ((x/θ)^(-α)) : 0.0))
    end
    return pdfs
end

function logpdf(d::con_powerlaw, x::Float64)
    (α, θ) = params(d)
    x >= θ ? log(α-1.0) - log(θ) - α * log(x/θ) : -Inf
end

function logpdf(d::con_powerlaw, x::AbstractArray)
    (α, θ) = params(d)
    l_const = log(α-1.0) - log(θ)
    lpdfs = Array(Float64,0)
    for num in x
        push!(lpdfs,(num >= θ ? l_const - α * log(num/θ) : -Inf))
    end
    return lpdfs
end

function ccdf(d::con_powerlaw, x::Float64)
    (α, θ) = params(d)
    x >= θ ? (x/θ)^(-α +1.0) : 1.0
end

cdf(d::con_powerlaw, x::Float64) = 1.0 - ccdf(d, x)

logccdf(d::con_powerlaw, x::Float64) = log(ccfd(d,x))

logcdf(d::con_powerlaw, x::Float64) = log(cdf(d, x))

cquantile(d::con_powerlaw, p::Float64) = d.θ *((p) ^ (-1.0 / (d.α - 1.0)))
quantile(d::con_powerlaw, p::Float64) = cquantile(d, 1.0 - p)

#### Sampling

rand(d::con_powerlaw) = quantile(d,rand())

## Fitting

function fit_mle{T <: Real}(::Type{con_powerlaw}, x::AbstractArray{T})
    θ = minimum(x)

    n = length(x)
    lθ = log(θ)
    temp1 = zero(T)
    for i=1:n
        temp1 += log(x[i]) - lθ
    end
    α = 1.0+n*(temp1)^(-1.0)

    return con_powerlaw(α, θ)
end


text:
@testset "types.jl" begin

@test HTTP.schemetype(TCPSocket) == HTTP.http
@test HTTP.schemetype(HTTP.TLS.SSLContext) == HTTP.https

@test HTTP.not(nothing)
@test !HTTP.not(1)

@test HTTP.status(HTTP.Response(300)) == 300
@test String(HTTP.body(HTTP.Response("hello world"))) == "hello world"
@test HTTP.status(HTTP.Response(300, HTTP.Headers(), "")) == 300

@test HTTP.Response(200) == HTTP.Response(200)

@test string(HTTP.Response(200)) == "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"

io = IOBuffer()
showcompact(io, HTTP.Response(200))
@test String(take!(io)) == "Response(200 OK, 0 headers, 0 bytes in body)"

@test string(HTTP.Request()) == "GET / HTTP/1.1\r\n\r\n"

showcompact(io, HTTP.Request())
@test String(take!(io)) == "Request(\"\", 0 headers, 0 bytes in body)"

end


text:
Base.@pure function nondatavaluenamedtuple(::Type{NT}) where {NT <: NamedTuple{names}} where {names}
    TT = Tuple{Any[ DataValueInterfaces.nondatavaluetype(fieldtype(NT, i)) for i = 1:fieldcount(NT) ]...}
    return NamedTuple{names, TT}
end

Base.@pure function datavaluenamedtuple(::Tables.Schema{names, types}) where {names, types}
    TT = Tuple{Any[ DataValueInterfaces.datavaluetype(fieldtype(types, i)) for i = 1:fieldcount(types) ]...}
    return NamedTuple{names, TT}
end

# IteratorWrapper takes an input Row iterators, it will unwrap any DataValue elements as plain Union{T, Missing}
struct IteratorWrapper{S}
    x::S
end

nondatavaluerows(x) = IteratorWrapper(IteratorInterfaceExtensions.getiterator(x))
Tables.istable(::Type{<:IteratorWrapper}) = true
Tables.rowaccess(::Type{<:IteratorWrapper}) = true
Tables.rows(x::IteratorWrapper) = x

function Tables.schema(dv::IteratorWrapper{S}) where {S}
    eT = eltype(dv.x)
    (!(eT <: NamedTuple) || eT === Union{}) && return schema(dv.x)
    return Tables.Schema(nondatavaluenamedtuple(eT))
end

Base.IteratorEltype(::Type{IteratorWrapper{S}}) where {S} = Base.IteratorEltype(S)
Base.eltype(x::IteratorWrapper{S}) where {S} = IteratorRow{eltype(x.x)}
Base.eltype(::Type{IteratorWrapper{S}}) where {S} = IteratorRow{eltype(S)}
Base.IteratorSize(::Type{IteratorWrapper{S}}) where {S} = Base.IteratorSize(S)
Base.length(rows::IteratorWrapper) = length(rows.x)
Base.size(rows::IteratorWrapper) = size(rows.x)

@noinline invalidtable(::T, ::S) where {T, S} = throw(ArgumentError("'$T' iterates '$S' values, which don't satisfy the Tables.jl Row-iterator interface"))

@inline function Base.iterate(rows::IteratorWrapper)
    x = iterate(rows.x)
    x === nothing && return nothing
    row, st = x
    propertynames(row) === () && invalidtable(rows.x, row)
    return IteratorRow(row), st
end

@inline function Base.iterate(rows::IteratorWrapper, st)
    x = iterate(rows.x, st)
    x === nothing && return nothing
    row, st = x
    return IteratorRow(row), st
end

struct IteratorRow{T}
    row::T
end

unwrap(::Type{T}, x) where {T} = convert(T, x)
unwrap(::Type{Any}, x) = x.hasvalue ? x.value : missing

function Base.getproperty(d::IteratorRow, ::Type{T}, col::Int, nm) where {T}
    x = getproperty(getfield(d, 1), T, col, nm)
    TT = typeof(x)
    TTT = DataValueInterfaces.nondatavaluetype(TT)
    return TT == TTT ? x : unwrap(TTT, x)
end
function Base.getproperty(d::IteratorRow, nm::Symbol)
    x = getproperty(getfield(d, 1), nm)
    TT = typeof(x)
    TTT = DataValueInterfaces.nondatavaluetype(TT)
    return TT == TTT ? x : unwrap(TTT, x)
end
function Base.getproperty(d::IteratorRow, nm::Int)
    x = getproperty(getfield(d, 1), nm)
    TT = typeof(x)
    TTT = DataValueInterfaces.nondatavaluetype(TT)
    return TT == TTT ? x : unwrap(TTT, x)
end
Base.propertynames(d::IteratorRow) = propertynames(getfield(d, 1))

# DataValueRowIterator wraps a Row iterator and will wrap `Union{T, Missing}` typed fields in DataValues
struct DataValueRowIterator{NT, S}
    x::S
end

function datavaluerows(x)
    r = Tables.rows(x)
    s = Tables.schema(r)
    s === nothing && error("Schemaless sources cannot be passed to datavaluerows.")
    return DataValueRowIterator{datavaluenamedtuple(s), typeof(r)}(r)
end

Base.eltype(rows::DataValueRowIterator{NT, S}) where {NT, S} = NT
Base.IteratorSize(::Type{DataValueRowIterator{NT, S}}) where {NT, S} = Base.IteratorSize(S)
Base.length(rows::DataValueRowIterator) = length(rows.x)
Base.size(rows::DataValueRowIterator) = size(rows.x)

function Base.iterate(rows::DataValueRowIterator{NT, S}, st=()) where {NT <: NamedTuple{names}, S} where {names}
    if @generated
        vals = Tuple(:(convert($(fieldtype(NT, i)), getproperty(row, $(DataValueInterfaces.nondatavaluetype(fieldtype(NT, i))), $i, $(Meta.QuoteNode(names[i]))))) for i = 1:fieldcount(NT))
        q = quote
            x = iterate(rows.x, st...)
            x === nothing && return nothing
            row, st = x
            return $NT(($(vals...),)), (st,)
        end
        # @show q
        return q
    else
        x = iterate(rows.x, st...)
        x === nothing && return nothing
        row, st = x
        return NT(Tuple(convert(fieldtype(NT, i), getproperty(row, DataValueInterfaces.nondatavaluetype(fieldtype(NT, i)), i, names[i])) for i = 1:fieldcount(NT))), (st,)
    end
end


text:
@info "Starting precompile exec"

ENV["PYTHON"] = "/srv/conda/envs/notebook/bin/python"

using LinearAlgebra, Statistics, DataFrames, Plots, SymPy, StatsPlots, Distributions

mean(randn(100))
randn(10, 10) \ randn(10)

df = DataFrame(a=[1,2,3], b=[4,5,6])
@df df scatter(:a, :b)

@vars x
expand((x+1)^10)

mean(Normal(0, 1))

max_stars_repo_name: prismia-chat/flux-binder

max_issues_repo_name: prismia-chat/flux-binder

max_forks_repo_name: prismia-chat/flux-binder