text:
export WrappedMethod, WrappedConstructor, WrappedClass, WrappedHeader,
analyze

using QuickTypes
using Clang
using Clang.wrap_cpp
using Clang.cindex
import Clang.wrap_cpp: WrappedMethod, analyze_method, get_args, get_proxy

immutable WrappedConstructor
    name::String
    constructor::Constructor
    parent::ClassDecl
    args::Array{Any,1}
end

immutable WrappedClass
    name::String
    constructors::Vector{WrappedConstructor}
    methods::Vector{WrappedMethod}
    class::ClassDecl
end

immutable WrappedHeader
    topcursor::TranslationUnit
    classnodes::Vector{WrappedClass}
end

import Clang.cindex: name, spelling
name(x) = x.name

raw(x::WrappedClass) = x.class
raw(x::WrappedMethod) = x.method
raw(x::WrappedConstructor) = x.constructor
raw(x::WrappedHeader) = x.topcursor
spelling(x) = x |> raw |> spelling

identity_str(s::String) = s # for debug we use this instead of identity
function jlext(path)
    stem, ext = splitext(path)
    stem + ".jl"
end

"""
    Renamer(;kw...)

Captures renaming schemes for methods, files, ... for the translation C++ -> Julia.
"""
@qimmutable Renamer(;
    header=jlext,
    method=identity_str,
    class=identity_str,
    destructor::String="delete",
    )

immutable WrapperConfig
    rename::Renamer
    #header_paths::Vector{String} # paths to headers that should be wrapped
end
WrapperConfig() = WrapperConfig(Renamer())

type WrapperState
    # method list
    # operator list for Base import
    # exports
    # single vs multifile
end


text:
function ir_element(x, code::Vector)
    while isa(x, Core.SSAValue)
        x = code[x.id]
    end
    return x
end

##
# Forces inlining on everything that is not marked `@noinline`
# avoids overdubbing of pure functions
# avoids overdubbing of IntrinsicFunctions and Builtins
##
function transform(ctx, ref)
    CI = ref.code_info
    noinline = any(@nospecialize(x) ->
                       Core.Compiler.isexpr(x, :meta) &&
                       x.args[1] == :noinline,
                   CI.code)
    CI.inlineable = !noinline

    # don't overdub pure functions
    if CI.pure
        n_method_args = Int(ref.method.nargs)
        if ref.method.isva
            Cassette.insert_statements!(CI.code, CI.codelocs,
                (x, i) -> i == 1 ?  3 : nothing,
                (x, i) -> i == 1 ? [
                    # this could run into troubles when the function is @pure f(x...) since then n_method_args==2, but this seems to work sofar.
                    Expr(:call, Expr(:nooverdub, GlobalRef(Core, :tuple)), (Core.SlotNumber(i) for i in 2:(n_method_args-1))...),
                    Expr(:call, Expr(:nooverdub, GlobalRef(Core, :_apply)), Core.SlotNumber(1), Core.SSAValue(i), Core.SlotNumber(n_method_args)),
                    Expr(:return, Core.SSAValue(i+1))] : nothing)
        else
            Cassette.insert_statements!(CI.code, CI.codelocs,
                (x, i) -> i == 1 ?  2 : nothing,
                (x, i) -> i == 1 ? [
                    Expr(:call, Expr(:nooverdub, Core.SlotNumber(1)), (Core.SlotNumber(i) for i in 2:n_method_args)...)
                    Expr(:return, Core.SSAValue(i))] : nothing)
        end
        CI.ssavaluetypes = length(CI.code)
        return CI
    end

    # overdubbing IntrinsicFunctions removes our ability to profile code
    newstmt = (x, i) -> begin
        isassign = Base.Meta.isexpr(x, :(=))
        stmt = isassign ? x.args[2] : x
        if Base.Meta.isexpr(stmt, :call)
            applycall = Cassette.is_ir_element(stmt.args[1], GlobalRef(Core, :_apply), CI.code)
            if applycall
                f = stmt.args[2]
            else
                f = stmt.args[1]
            end
            f = ir_element(f, CI.code)
            if f isa GlobalRef
                mod = f.mod
                name = f.name
                if Base.isbindingresolved(mod, name) && Base.isdefined(mod, name)
                    ff = getfield(f.mod, f.name)
                    if ff isa Core.IntrinsicFunction || ff isa Core.Builtin
                        if applycall
                            stmt.args[2] = Expr(:nooverdub, f)
                        else
                            stmt.args[1] = Expr(:nooverdub, f)
                        end
                    end
                end
            end
        end
        return [x]
    end

    Cassette.insert_statements!(CI.code, CI.codelocs, (x, i) -> 1, newstmt)
    CI.ssavaluetypes = length(CI.code)
    # Core.Compiler.validate_code(CI)
    return CI
end

const CompilerPass = Cassette.@pass transform

ext: jl


text:
__precompile__(true)

module NGSIM

using AutomotiveDrivingModels
using DataFrames
using Distributions

export
    NGSIMRoadway,
    RoadwayInputParams,

    ROADWAY_80,
    ROADWAY_101,

    NGSIMTrajdata,
    VehicleSystem,
    FilterTrajectoryResult,

    NGSIM_TIMESTEP,
    NGSIM_TRAJDATA_PATHS,
    TRAJDATA_PATHS,

    carsinframe,
    load_ngsim_trajdata,
    get_corresponding_roadway,
    filter_trajectory!,
    symmetric_exponential_moving_average!,
    load_trajdata,
    convert_raw_ngsim_to_trajdatas

include("roadway.jl")
include("ngsim_trajdata.jl")
include("trajdata.jl")

end # module


text:
# Minimal example that demonstrates robot-robot and robot-target range limits.

using SubmodularMaximization
using POMDPs
using MCTS
using PyPlot
using Base.Iterators
using Printf
using Statistics

close()

steps = 100
horizon = SubmodularMaximization.default_horizon

show_observations = false
sparse = false

num_partitions = 4

communication_range = 20
robot_target_range_limit = 12

# Use a larger range limit for weights to ensure accurate results
weights_range_limit=20

print("Enter number of robots: ")
num_robots = parse(Int64, readline())

num_targets = default_num_targets(num_robots)

grid = Grid(num_robots=num_robots)

configs = MultiRobotTargetTrackingConfigs(grid=grid,
                                          horizon=horizon,
                                          robot_target_range_limit=
                                            robot_target_range_limit
                                         )

robot_states = map(x->random_state(grid), 1:num_robots)
target_states = map(x->random_state(grid), 1:num_targets)

if sparse
  global histogram_filters = map(x->SparseFilter(grid, x, threshold=1e-3),
                                 target_states)
else
  global histogram_filters = map(x->Filter(grid, x), target_states)
end

solver = x->solve_communication_range_limit(x, threaded=true,
                                            num_partitions=num_partitions,
                                            communication_range=
                                            communication_range)

plot_state_space(grid)
xlim([0, grid.width+1])
ylim([0, grid.height+1])

for ii = 2:steps
  println("Step ", ii)

  prior_robot_states = Array(robot_states)

  @time solution = iterate_target_tracking!(robot_states=robot_states,
                                            target_states=target_states,
                                            target_filters=histogram_filters,
                                            configs=configs,
                                            solver=solver)

  global robot_states = solution.robot_states
  global target_states = solution.target_states
  trajectories = solution.trajectories
  range_observations = solution.range_observations

  # Compute weights
  problem = MultiRobotTargetTrackingProblem(robot_states, histogram_filters,
                                            configs)
  @time weight = total_weight(compute_weight_matrix(problem,
                                                    threaded=true,
                                                    robot_target_range_limit=
                                                    weights_range_limit))

  @printf("Weight per robot: %0.3f\n", weight / num_robots )

  #
  # Plot results
  #

  plots=[]
  for robot in robot_states
    append!(plots, plot_quadrotor(robot, color=:blue))
  end

  for trajectory in trajectories
    append!(plots, plot_states(trajectory, color=:blue, linestyle=":"))
  end

  # Plot motion
  for (prior, current) in zip(prior_robot_states, robot_states)
    append!(plots, plot_states([prior, current], color=:blue, linestyle="-"))
  end

  if show_observations
    for (robot, observations) in zip(robot_states, range_observations)
      for observation in observations
        append!(plots, plot_observation(robot, observation, color=:blue))
      end
    end
  end

  for target in target_states
    append!(plots, plot_target(target))
  end

  append!(plots, visualize_filters(histogram_filters))

  #
  # Print a summary of the problem state
  #
  println("Objective: ", solution.objective,
          " (", solution.objective / num_robots, " per robot)")
  e = entropy(histogram_filters)
  println("Entropy: ", e, " (", e / num_targets, " per target)")

  foreach(drop_below_threshold!, histogram_filters)

  if sparse
    @printf("Sparsity: %0.2f\n", mean(sparsity, histogram_filters))
  end

  line = readline()

  if line == "q"
    break
  end

  if ii < steps
    foreach(x->x.remove(), plots)
  end
end

max_stars_repo_name: mcorah/MultiAgentSensing

max_issues_repo_name: mcorah/MultiAgentSensing

max_forks_repo_name: mcorah/MultiAgentSensing


text:
module PwDynamicDefinition
using ValidatedNumerics
using ..DynamicDefinition
using ..Contractors
using TaylorSeries: Taylor1

using ..DynamicDefinition: derivative, orientation

export PwMap, preim, nbranches, plottable

"""
Dynamic based on a piecewise monotonic map.

The map is defined as T(x) = Ts[k](x) if x ∈ [endpoints[k], endpoints[k+1]).

`y_endpoints` (kx2 matrix) contains the result of applying Ts to the endpoints of each interval. These can be filled in automatically from `endpoints`,
but sometimes they are known to higher accuracy, for instance for `x -> mod(3x, 1)` we know that it is full-branch exactly.
"""
struct PwMap{FT} <: Dynamic
	Ts::FT
	endpoints::Vector{Interval{Float64}}
	y_endpoints::Matrix{Interval{Float64}}
	increasing::Vector{Bool} # these will be filled in automatically, usually
end

Base.show(io::IO, D::PwMap) = print(io, "Piecewise-defined dynamic with $(nbranches(D)) branches")

DynamicDefinition.domain(S::PwMap) = hull(S.endpoints[1], S.endpoints[end])

PwMap(Ts, endpoints) = PwMap(Ts, endpoints, hcat([Ts[k](Interval(endpoints[k])) for k in 1:length(Ts)], [Ts[k](Interval(endpoints[k+1])) for k in 1:length(Ts)]))
PwMap(Ts, endpoints, y_endpoints) = PwMap{typeof(Ts)}(Ts, map(Interval, endpoints), y_endpoints, [unique_increasing(y_endpoints[k,1], y_endpoints[k,2]) for k=1:length(Ts)])

DynamicDefinition.nbranches(D::PwMap) = length(D.endpoints)-1
DynamicDefinition.endpoints(D::PwMap) = D.endpoints

DynamicDefinition.orientation(D::PwMap, k) = D.increasing[k] ? 1. : -1.

DynamicDefinition.is_full_branch(D::PwMap) = all(r == [0.,1.] || r == [1.,0.] for r in eachrow(D.y_endpoints))  # TODO: this assumes domain == [0,1] unnecessarily

function DynamicDefinition.preim(D::PwMap, k, y, ϵ = 1e-15)
	@assert 1 <= k <= nbranches(D)
	domain = hull(D.endpoints[k], D.endpoints[k+1])
	return preimage(y, D.Ts[k], domain, ϵ)
end

"""
Intersect an Interval or TaylorSeries with I
"""
restrict(I, x) = I ∩ x
restrict(I, x::Taylor1) = Taylor1([I ∩ x[0]; x[1:end]], x.order)

"""
function that evaluates the k-th branch of a dynamic on a point x
	(assuming it's in its domain, otherwise ∅)
"""
function DynamicDefinition.branch(D::PwMap, k)
	return x -> D.Ts[k](restrict(hull(D.endpoints[k], D.endpoints[k+1]), x))
end

# Unused as of now
# """
# hull of an iterable of intervals
# """
# common_hull(S) = interval(minimum(x.lo for x in S), maximum(x.hi for x in S))

# Rather than defining derivatives of a PwMap, we define Taylor1 expansions directly
# and let the generic functions in DynamicDefinition to the work
"""
Function call, and Taylor expansion, of a PwMap.
Note that this ignores discontinuities; users are free to shoot themselves
in the foot and call this on a non-smooth piecewise map. No better solutions for now.
"""
function (D::PwMap)(x::Taylor1)
	fx = fill(∅, x.order+1)
	x_restricted = deepcopy(x)
	for i = 1:length(D.endpoints)-1
		x_restricted[0] = x[0] ∩ hull(D.endpoints[i],D.endpoints[i+1])
		if !isempty(x_restricted[0])
			fx_restricted = D.Ts[i](x_restricted)
			fx = fx .∪ fx_restricted.coeffs
		end
	end
	@debug "Piecewise f($(x)) = $(Taylor1(fx, x.order))"
	return Taylor1(fx, x.order)
end

function DynamicDefinition.plottable(D::PwMap, x)
	@assert 0 <= x <= 1
	for k in 1:nbranches(D)
		domain = hull(D.endpoints[k], D.endpoints[k+1])
		if x in domain
			return D.Ts[k](x)
		end
	end
end

using RecipesBase
@recipe f(::Type{PM}, D::PM) where {PM <: PwMap} = x -> plottable(D, x)

end


text:
"""
    SaveRestartCallback(; interval=0,
                          save_final_restart=true,
                          output_directory="out")

Save the current numerical solution in a restart file every `interval` time steps.
"""
mutable struct SaveRestartCallback
  interval::Int
  save_final_restart::Bool
  output_directory::String
end

function Base.show(io::IO, cb::DiscreteCallback{<:Any, <:SaveRestartCallback})
  @nospecialize cb # reduce precompilation time

  restart_callback = cb.affect!
  print(io, "SaveRestartCallback(interval=", restart_callback.interval, ")")
end

function Base.show(io::IO, ::MIME"text/plain", cb::DiscreteCallback{<:Any, <:SaveRestartCallback})
  @nospecialize cb # reduce precompilation time

  if get(io, :compact, false)
    show(io, cb)
  else
    save_restart_callback = cb.affect!

    setup = [
             "interval" => save_restart_callback.interval,
             "save final solution" => save_restart_callback.save_final_restart ? "yes" : "no",
             "output directory" => abspath(normpath(save_restart_callback.output_directory)),
            ]
    summary_box(io, "SaveRestartCallback", setup)
  end
end

function SaveRestartCallback(; interval=0,
                               save_final_restart=true,
                               output_directory="out")

  restart_callback = SaveRestartCallback(interval, save_final_restart,
                                         output_directory)

  DiscreteCallback(restart_callback, restart_callback, # the first one is the condition, the second the affect!
                   save_positions=(false,false),
                   initialize=initialize!)
end

function initialize!(cb::DiscreteCallback{Condition,Affect!}, u, t, integrator) where {Condition, Affect!<:SaveRestartCallback}
  restart_callback = cb.affect!

  mpi_isroot() && mkpath(restart_callback.output_directory)

  semi = integrator.p
  mesh, _, _, _ = mesh_equations_solver_cache(semi)
  @timeit_debug timer() "I/O" begin
    if mesh.unsaved_changes
      mesh.current_filename = save_mesh_file(mesh, restart_callback.output_directory)
      mesh.unsaved_changes = false
    end
  end

  return nothing
end

# this method is called to determine whether the callback should be activated
function (restart_callback::SaveRestartCallback)(u, t, integrator)
  @unpack interval, save_final_restart = restart_callback

  return interval > 0 && (
    (integrator.iter % interval == 0) || (save_final_restart && isfinished(integrator)))
end

# this method is called when the callback is activated
function (restart_callback::SaveRestartCallback)(integrator)
  u_ode = integrator.u
  @unpack t, dt, iter = integrator
  semi = integrator.p
  mesh, _, _, _ = mesh_equations_solver_cache(semi)

  @timeit_debug timer() "I/O" begin
    if mesh.unsaved_changes
      mesh.current_filename = save_mesh_file(mesh, restart_callback.output_directory, iter)
      mesh.unsaved_changes = false
    end

    save_restart_file(u_ode, t, dt, iter, semi, restart_callback)
  end

  # avoid re-evaluating possible FSAL stages
  u_modified!(integrator, false)
  return nothing
end

@inline function save_restart_file(u_ode::AbstractVector, t, dt, iter,
                                   semi::AbstractSemidiscretization, restart_callback)
  mesh, equations, solver, cache = mesh_equations_solver_cache(semi)
  u = wrap_array(u_ode, mesh, equations, solver, cache)
  save_restart_file(u, t, dt, iter, mesh, equations, solver, cache, restart_callback)
end

"""
    load_time(restart_file::AbstractString)

Load the time saved in a `restart_file`.
"""
function load_time(restart_file::AbstractString)
  h5open(restart_file, "r") do file
    read(attributes(file)["time"])
  end
end

function load_restart_file(semi::AbstractSemidiscretization, restart_file)
  load_restart_file(mesh_equations_solver_cache(semi)..., restart_file)
end

include("save_restart_dg.jl")


text:
abstract type AbstractGeometryItem{Tv<:Number, Ti <:Integer} end

##################################################################
"""
$(TYPEDEF)

Structure holding local boundary  node information.

$(TYPEDFIELDS)
"""
mutable struct BNode{Tv, Ti} <: AbstractGeometryItem{Tv, Ti}

    """
    Index in grid
    """
    index::Ti

    """
    BFace number it is called from
    """
    ibface::Ti

    """
    local node number
    """
    ibnode::Ti

    """
    Boundary region number
    """
    region::Ti

    """
    Number of species defined in node
    """
    nspec::Ti

    """
    Grid coordinates
    """
    coord::Matrix{Tv}

    BNode{Tv,Ti}(sys::AbstractSystem{Tv,Ti}) where {Tv,Ti}  =new(0,0,0,0,num_species(sys),coordinates(sys.grid))
end

function _fill!(node::BNode,bfacenodes,bfaceregions,ibnode,ibface)
    K=bfacenodes[ibnode,ibface]
    node.ibface=ibface
    node.ibnode=ibnode
    node.region=bfaceregions[ibface]
    node.index=K
end

##################################################################
"""
$(TYPEDEF)

Structure holding local node information.

$(TYPEDFIELDS)
"""
mutable struct Node{Tv,Ti} <: AbstractGeometryItem{Tv, Ti}

    """
    Index in grid

    """
    index::Ti
    """
    Inner region number
    """
    region::Ti

    """
    Number of species defined in node
    """
    nspec::Ti

    """
    Number of discretization cell the node is invoked from
    """
    icell::Ti

    """
    Grid coordinates
    """
    coord::Matrix{Tv}

    Node{Tv,Ti}(sys::AbstractSystem{Tv,Ti}) where {Tv,Ti}  =new(zero(Ti),0,num_species(sys),0, coordinates(sys.grid))
end

function _fill!(node::Node,cellnodes,cellregions,inode,icell)
    K=cellnodes[inode,icell]
    node.region=cellregions[icell]
    node.index=K
    node.icell=icell
end

Base.size(node::Node)=(size(node.coord)[1],)

Base.getindex(node::Node, idim)= node.coord[idim,node.index]

##################################################################
"""
$(TYPEDEF)

Structure holding local edge information.

$(TYPEDFIELDS)
"""
mutable struct Edge{Tv,Ti}  <: AbstractGeometryItem{Tv, Ti}

    """
    Index in grid
    """
    index::Ti

    """
    Index
    """
    node::Vector{Ti}

    """
    Inner region number corresponding to edge
    """
    region::Ti

    """
    Number of species defined in edge
    """
    nspec::Ti

    """
    Number of discretization cell the edge is invoked from
    """
    icell::Ti

    """
    Grid coordinates
    """
    coord::Matrix{Tv}

    Edge{Tv,Ti}(sys::AbstractSystem{Tv,Ti}) where {Tv,Ti}  =new(0,[0,0],0,num_species(sys),0,coordinates(sys.grid))
end

function _fill!(edge::Edge,cellx,edgenodes,cellregions,iedge,icell, has_celledges) where Tv
    if has_celledges #  cellx==celledges, edgenodes==global_edgenodes
        # If we work with projections of fluxes onto edges,
        # we need to ensure that the edges are accessed with the
        # same orientation without regard of the orientation induced
        # by local cell numbering
        edge.index=cellx[iedge,icell]
        edge.node[1]=edgenodes[1,edge.index]
        edge.node[2]=edgenodes[2,edge.index]
    else # cx==cellnodes, edgenodes== local_edgenodes
        edge.index=0
        edge.node[1]=cellx[edgenodes[1,iedge],icell]
        edge.node[2]=cellx[edgenodes[2,iedge],icell]
    end
    edge.region=cellregions[icell]
    edge.icell=icell
end

Base.size(edge::Edge)=(size(edge.coord)[1],2)
Base.getindex(edge::Edge, idim,inode)= edge.coord[idim,edge.node[inode]]

##################################################################
"""
$(TYPEDSIGNATURES)

Return number of species for edge
"""
num_species(edge::Edge)=edge.nspec

##################################################################
"""
$(TYPEDSIGNATURES)

Calculate the length of an edge.
"""
function meas(edge::Edge)
    l=0.0
    for i=1:size(edge.coord)[1]
        d=edge.coord[i,edge.node[1]]-edge.coord[i,edge.node[2]]
        l=l+d*d
    end
    return sqrt(l)
end

edgelength(edge::Edge)=meas(edge)

function project(edge::Edge,vec)
    vh=0.0
    for i=1:size(edge.coord)[1]
        vh+=(edge.coord[i,edge.node[2]]-edge.coord[i,edge.node[1]])*vec[i]
    end
    return vh
end

##################################################################
"""
$(TYPEDEF)

Wrapper struct for viewing unknowns passed to flux as matrix

$(TYPEDFIELDS)
"""
struct MatrixUnknowns{T} <:AbstractMatrix{T}
    u::Vector{T}
    n1::Int64
end

"""
$(TYPEDSIGNATURES)

Construct matrix of unknowns from edge - these can be used in flux functions
with the v0.7.x and v0.8.x syntax to acces data.
"""
unknowns(edge::Edge,u::Vector{T}) where T = MatrixUnknowns{T}(u,edge.nspec)
Base.getindex(u::MatrixUnknowns,i,j)=@inbounds u.u[(j-1)*u.n1+i]
Base.size(u::MatrixUnknowns)=(u.n1,2)

##################################################################
"""
$(TYPEDEF)

Wrapper struct for viewing unknowns passed to callback functions

$(TYPEDFIELDS)
"""
struct VectorUnknowns{T} <:AbstractVector{T}
    u::Vector{T}
    n::Int64
    offset::Int64
end

"""
$(TYPEDSIGNATURES)

Construct vector unknowns on edge.
"""
unknowns(edge::Edge, u::Vector{T},i) where T = VectorUnknowns{T}(u,edge.nspec,(i-1)*(edge.nspec))
Base.getindex(u::VectorUnknowns,i)=@inbounds u.u[u.offset+i]
Base.size(u::VectorUnknowns)=(u.n,)

"""
$(TYPEDSIGNATURES)

Construct vector unknowns on node
"""
unknowns(node::Node, u)=u

"""
$(TYPEDSIGNATURES)

Construct vector unknowns on bnode
"""
unknowns(node::BNode, u)=u

"""
$(TYPEDSIGNATURES)

Solution view on first edge node
"""
viewK(edge::Edge,u)=unknowns(edge,u,1)

"""
$(TYPEDSIGNATURES)

Solution view on second edge node
"""
viewL(edge::Edge,u)=unknowns(edge,u,2)


text:
# NG86/computation.jl
# ===================
#
# Core computations for the NG86 method of computing dN and dS statistics.
#
# This file is a part of BioJulia.
# License is MIT: https://github.com/BioJulia/NaturalSelection.jl/blob/master/LICENSE.md

"""
    S_N_NG86(codon::C, code::GeneticCode) where {C <: CDN}

Enumerate the number of synonymous (S) and non-synonymous (N) sites in a codon,
using the method used by [Nei and Gojobori (1986)](https://www.ncbi.nlm.nih.gov/pubmed/3444411).

Returns a tuple where S is the first element and N is the second (S, N).

Each site in a codon may be both partially synonymous and non-synonymous.
"""
function S_N_NG86(codon::C, code::GeneticCode) where {C <: Codon}
    cdn_bits = UInt64(codon)
    aa = code[codon]
    S = N = 0
    for (pos, msk) in enumerate(CDN_POS_MASKS)
        bidx = bitindex(codon, pos)
        for base in 0:3
            # Create the neighbor codon.
            neighbor = C((cdn_bits & msk) | (base << bidx))
            if codon == neighbor # Codon created is not a neighbor: should happen 3 times.
                continue
            end
            # See if the protein changes between codon and neighbor, and update
            # N and S counts accordingly.
            neighbor_aa = code[neighbor]
            if neighbor_aa == BioSequences.AA_Term
                N += 1
            elseif neighbor_aa == aa
                S += 1
            else
                N += 1
            end
        end
    end
    normalization = (N + S) / 3
    return (S / normalization), (N / normalization)
end

"""
    DS_DN_NG86(x::C, y::C, code::GeneticCode) where C <: CDN

Compute the number of synonymous (DS) and non-synonymous (DN) mutations between
two codons, using the all paths method used by the [Nei and Gojobori (1986)](https://www.ncbi.nlm.nih.gov/pubmed/3444411).
"""
function DS_DN_NG86(x::C, y::C, code::GeneticCode) where C <: Codon
    return DS_DN_enumerator(AllPaths, x, y, code)
end

@inline function d_(p::Float64)
    if p < 3 / 4
        return - 3 / 4 * log(1 - 4.0 / 3 * p)
    else
        return -1.0
    end
end

function dNdS_NG86_kernel(x, y,
    S::Float64, N::Float64,
    DS::Float64, DN::Float64,
    snlookup::S_N_NG86_LOOKUP, dsdnlookup::DS_DN_NG86_LOOKUP)

    # Iterate over every pair of codons.
    @inbounds for (i, j) in zip(x, y)
        si, ni = snlookup[i]
        sj, nj = snlookup[j]
        S += (si + sj)
        N += (ni + nj)
        DSi, DNi = dsdnlookup[i, j]
        DS += DSi
        DN += DNi
    end

    S = S / 2.0
    N = N / 2.0
    pN = DN / N
    pS = DS / S
    dN = d_(pN)
    dS = d_(pS)
    return dN, dS
end

function _dNdS_NG86(x, y, addone::Bool, snlookup::S_N_NG86_LOOKUP, dsdnlookup::DS_DN_NG86_LOOKUP, ::Type{C}, ::Type{C}) where C <: Codon
    # Expected no. of syn and nonsyn sites.
    S = N = 0.0
    # Observed no. of syn and nonsyn mutations.
    DS = ifelse(addone, 1.0, 0.0)
    DN = 0.0
    return dNdS_NG86_kernel(x, y, S, N, DS, DN, snlookup, dsdnlookup)
end

function _dNdS_NG86(x, y, addone::Bool, snlookup::S_N_NG86_LOOKUP, dsdnlookup::DS_DN_NG86_LOOKUP, ::Type{N}, ::Type{N}) where N <: NucleicAcid
    xcdns, ycdns = aligned_codons(x, y)
    _dNdS_NG86(xcdns, ycdns, addone, snlookup, dsdnlookup, eltype(xcdns), eltype(ycdns))
end


text:
function constrained1(D = 5)
    # Objective function
    f(x) = (sum((x .- 1).^2), [sum((x .- 1).^2) - 4, sum(sin.(x .- 1)) - 1], [(x[1] - x[2])^2])

    bounds = Array([-10.0ones(D) 10.0ones(D)]')

    x = ones(D)
    return f, bounds, [generateChild(x, f(x)) ]
end

function constrained2(D = 5)

    f(x) = (sum((x .- 1).^2), [sum((x .- 1).^2) - 4, sum(sin.(x .- 1)) - 1, (x[1] - x[2])^2 - 6], [0.0])

    bounds = Array([-10.0ones(D) 10.0ones(D)]')

    x = ones(D)
    return f, bounds, [generateChild(x, f(x)) ]

end

function constrained3()
    f(y) = begin
        x = zeros(2)
        return x[1] + 2x[2] + y[1] + y[2] + 2y[3],
                    [0.0], # g
                    [
                     - y[1] + y[2] + y[3] + y[4] - 1,
                     2x[1] - y[1] + 2y[2] - 0.5y[3] + y[5] - 1,
                     2x[2] + 2y[1] - y[2] - 0.5y[3] + y[6] - 1
                    ]
    end

    bounds = Array([zeros(6) 100.0ones(6)]')
    y = zeros(6)
    y[4:6] .= 1.0
    return f, bounds, [generateChild(y, f(y)) ]
end


text:
module Statulator

include("calculations.jl")

function input(prompt::AbstractString="")
    print(prompt)
    return chomp(readline())
end

function terminate(message::AbstractString="")
    println(message)
    exit()
 end

 q1 = input("Is this is a problem of sample proportions or means? [p/m] ")

if q1 != "p" && q1 != "m"
    terminate("You must enter 'p' for proportion or 'm' for mean.")
end

q2 = input("Do you want to run a test or create an interval? [t/i] ")

if q2 != "t" && q2 != "i"
    terminate("You must enter 't' for test or 'i' for interval.")
end

q3 = input("How many proportions are you working with? [1/2] ")

if q3 != "1" && q3 != "2"
    terminate("Only one and two proportion tests and intervals are currently supported.")
end

if q1 == "p"
    if q2 == "t"
        if q3 == "1"
            p = 0
            p0 = 0
            n = 0
            alpha = 0
            alt = ""

            try
                p = parse(Float64, input("What is your sample proportion? "))
                p0 = parse(Float64, input("What is your assumed population proportion? "))
                n = parse(Float64, input("What is your sample size? "))
                alpha = parse(Float64, input("What is your alpha level? "))
                alt = input("Is your alternate hypothesis '!=', '>', or '<'? ")
            catch
                terminate("You must enter a numeric value.")
            end

            if alt != "!=" && alt != ">" && alt != "<"
                terminate("That wasn't an option.")
            end

            p_value = one_prop_z_test(p, p0, n, alpha, alt, p_pooled)
            println("The calculated p-value is ", p_value)
            println("If the population proportion is ", p0, " then the probability of observing a sample proportion of ", p, " is ", p_value, ".")
        elseif q3 == "2"
            p1 = 0
            n1 = 0
            p2 = 0
            n2 = 0
            alpha = 0
            alt = ""

            try
                p1 = parse(Float64, input("What is your first sample proportion? "))
                n1 = parse(Float64, input("What is your first sample size? "))
                p2 = parse(Float64, input("What is your second sample proportion? "))
                n2 = parse(Float64, input("What is your second sample size? "))
                alpha = parse(Float64, input("What is your alpha level?"))
                alt = input("Is your alternate hypothesis '!=', '>', or '<'? ")
            catch
                terminate("You must enter a numeric value.")
            end

            if alt != "!=" && alt != ">" && alt != "<"
                terminate("That wasn't an option.")
            end

            p_value = two_prop_z_test(p1, n1, p2, n2, alpha, alt)
            println("The calculated p-value is ", abs(p_value))
            println("If the difference between the population proportions is 0, then the probability of observing a sample proportion difference of ", abs(p1-p2), " is ", abs(p_value), ".")
        end
    elseif q2 == "i"
        if q3 == "1"
            p = 0
            n = 0
            lvl = 0

            try
                p = parse(Float64, input("What is your sample proportion? "))
                n = parse(Float64, input("What is your sample size? "))
                lvl = parse(Float64, input("What is your needed confidence level? "))
            catch
                terminate("You must enter a numeric value.")
            end

            interval = one_prop_z_int(p, n, lvl)

            println("The interval is (", interval.lower, ", ", interval.upper, ")")
            println("We can state with ", (lvl*100), "% confidence that the true proportion lies between ", interval.lower, " and ", interval.upper, ".")
        elseif q3 == "2"
            p1 = 0
            n1 = 0
            p2 = 0
            n2 = 0
            lvl = 0

            try
                p1 = parse(Float64, input("What is your first sample proportion? "))
                n1 = parse(Float64, input("What is your first sample size? "))
                p2 = parse(Float64, input("What is your second sample proportion? "))
                n2 = parse(Float64, input("What is your second sample size? "))
                lvl = parse(Float64, input("What is your needed confidence level? (in proportion)"))
            catch
                terminate("You must enter a numeric value.")
            end

            interval = two_prop_z_int(p1, n1, p2, n2, lvl)

            println("The interval is (", interval.lower, ", ", interval.upper, ")")
            println("We can state with ", (lvl*100), "% confidence that the difference in the true proportion lies between ", interval.lower, " and ", interval.upper, ".")
        end
    end
elseif q1 == "m"
    if q2 == "t"
        if q3 == "1"
            x̄ = 0
            μ0 = 0
            sx = 0
            n = 0
            alpha = 0
            alt = ""

            try
                x̄ = parse(Float64, input("What is your sample mean? "))
                μ0 = parse(Float64, input("What is your assumed population mean? "))
                sx = parse(Float64, input("What is your sample standard deviation? "))
                n = parse(Float64, input("What is your sample size? "))
                alpha = parse(Float64, input("What is your alpha level? "))
                alt = input("Is your alternate hypothesis '!=', '>', or '<'? ")
            catch
                terminate("You must enter a numeric value.")
            end

            if alt != "!=" && alt != ">" && alt != "<"
                terminate("That wasn't an option.")
            end

            p_value = z_test(p, p0, sx, n, alpha, alt)
            println("The calculated p-value is ", p-value)
        elseif q3 == "2"
            x̄1 = 0
            sx1 = 0
            n1 = 0
            x̄2 = 0
            sx2 = 0
            n2 = 0
            alpha = 0
            alt = ""

            try
                x̄1 = parse(Float64, input("What is your first sample mean? "))
                sx1 = parse(Float64, input("What is your first sample standard deviation? "))
                n1 = parse(Float64, input("What is your first sample size? "))
                x̄2 = parse(Float64, input("What is your second sample mean? "))
                sx2 = parse(Float64, input("What is your second sample standard deviation? "))
                n2 = parse(Float64, input("What is your second sample size? "))
                alpha = parse(Float64, input("What is your alpha level? "))
                alt = input("Is your alternate hypothesis '!=', '>', or '<'? ")
            catch
                terminate("You must enter a numeric value.")
            end

            if alt != "!=" && alt != ">" && alt != "<"
                terminate("That wasn't an option.")
            end

            p_value = two_sample_z_test(x̄1, sx1, n1, x̄2, sx2, n2, alpha, alt)
            println("The calculated p-value is ", p_value)
            println("If the difference between the population proportions is 0, then the probability of observing a sample proportion difference of ", abs(x̄1 - x̄2), " is ", abs(p_value), ".")
        end
    elseif q2 == "i"
        if q3 == "1"
            x̄ = 0
            sx = 0
            n = 0
            lvl = 0

            try
                x̄ = parse(Float64, input("What is your sample mean? "))
                sx = parse(Float64, input("What is your sample standard deviation? "))
                n = parse(Float64, input("What is your sample size? "))
                lvl = parse(Float64, input("What is your needed confidence level? "))
            catch
                terminate("You must enter a numeric value.")
            end

            interval = z_interval(x̄, sx, n, lvl)

            println("The interval is (", interval.lower, ", ", interval.upper, ")")
            println("We can state with ", (lvl*100), "% confidence that the true mean lies between ", interval.lower, " and ", interval.upper, ".")
        elseif q3 == "2"
            x̄1 = 0
            sx1 = 0
            x̄2 = 0
            sx2 = 0
            n1 = 0
            n2 = 0
            lvl = 0

            try
                x̄1 = parse(Float64, input("What is your first sample mean? "))
                sx1 = parse(Float64, input("What is your first sample standard deviation? "))
                n1 = parse(Float64, input("What is your first sample size? "))
                x̄2 = parse(Float64, input("What is your second sample mean? "))
                sx2 = parse(Float64, input("What is your second sample standard deviation? "))
                n2 = parse(Float64, input("What is your second sample size? "))
                lvl = parse(Float64, input("What is your needed confidence level? "))
            catch
                terminate("You must enter a numeric value.")
            end

            interval = two_sample_z_interval(x̄1, sx1, n1, x̄2, sx2, n2, lvl)

            println("The interval is (", interval.lower, ", ", interval.upper, ")")
            println("We can state with ", (lvl*100), "% confidence that the difference between the true means lies between ", interval.lower, " and ", interval.upper, ".")
        end
    end
end

end

max_stars_repo_name: jackcook/statulator

max_issues_repo_name: jackcook/statulator

max_forks_repo_name: jackcook/statulator


text:
include("structs.jl")

using PyPlot

function plot_density(u::AbstractArray{T, 3},
        v::AbstractArray{T, 3},
        ρ::AbstractArray{T, 3},
        s::AbstractArray{T, 3},
        p::Parameters) where T<:AbstractFloat
    fig, axs = PyPlot.subplots(1, 2, figsize=(10, 4))
    axs[1].set_xlabel("x, m")
    axs[1].set_ylabel("y, m")

    rgx = range(0, 2, length=p.nx)
    rgy = range(0, 2, length=p.ny)
    x = [rgx;]'
    y = [rgy;]'
    X = repeat([rgx;]', length(x))
    Y = repeat([rgy;],1, length(y))

    axs[1].set_ylabel(L"$y, (m)$")
    @views ρ̂ = ρ ./s
    for k = 1 : 2
        axs[k].set_xlabel(L"$x, (m)$")
        axs[k].quiver(x, y, u[:, :, k]', v[:, :, k]')
        pos = axs[k].contourf(X, Y, ρ̂[:, :, k]',
                              cmap=matplotlib.cm.viridis,
                              alpha=0.5)
        axs[k].contour(X, Y, ρ̂[:, :, k]',
                       cmap=matplotlib.cm.viridis)
        fig.colorbar(pos, ax=axs[k], label=L"$\rho, \left(\frac{kg}{m^3}\right)$")
    end

    # fig.suptitle("Профиль плотностей и поле скоростей")
    axs[1].set_title("Азот")
    axs[2].set_title("Пентан")

    savefig("../img/2phase-filtration-density.png", dpi=200)
    savefig("../img/2phase-filtration-density.svg")
end

function plot_pressure(u::AbstractArray{T, 3},
        v::AbstractArray{T, 3},
        P::AbstractMatrix{T}, p) where T<:AbstractFloat
    fig = PyPlot.figure(figsize=(9, 8))
    ax = PyPlot.axes()

    rgx = range(0, 2, length=p.nx)
    rgy = range(0, 2, length=p.ny)
    x = [rgx;]'
    y = [rgy;]'
    X = repeat([rgx;]', length(x))
    Y = repeat([rgy;],1, length(y))

    ## Velocity vector field
    # scale = 100.0
    quiver(x, y, u[:, :, 1]', v[:, :, 1]', color="r")
    quiver(x, y, u[:, :, 2]', v[:, :, 2]', color="b")

    pos = ax.contourf(X, Y, P',
        cmap=matplotlib.cm.viridis, alpha=0.5)
    fig.colorbar(pos, ax=ax, label="Pressure")

    ## Pressure contour map
    # cp = contour(X, Y, P', cmap=matplotlib.cm.viridis)

    PyPlot.title("2 Phase Filtration: Nitrogen and Pentane")

    savefig("../img/2phase-filtration.png", dpi=200)
    savefig("../img/2phase-filtration.svg")
end

# function plot_fluxes(u::AbstractArray{T, 3},
#         v::AbstractArray{T, 3},
#         ρ::AbstractArray{T, 3},
#         s::AbstractArray{T, 3},
#         p::Parameters,
#         y_value::T, y_index::Integer) where T<:AbstractFloat
#     fig, axs = PyPlot.subplots(1, 2, figsize=(13, 7))
#     rgx = range(0, 2, length=p.nx)
#
#     for k = 1 : 2
#         axs[k].set_xlabel("x, (m)")
#         axs[k].set_ylabel(L"$\left( \rho \cdot v_y \right), \left( \frac{kg \cdot m}{s}\right)$")
#         flux = get_flux(ρ[:, :, k], s[:, :, k], v[:, :, k], y_index)
#         axs[k].plot(rgx, flux)
#     end
#
#     axs[1].set_title("Поток азота через границу y = "   * string(y_value), y=1.08)
#     axs[2].set_title("Поток пентана через границу y = " * string(y_value), y=1.08)
#
#     savefig("../img/2phase-filtration-flux" * string(Integer(y_value)) * ".png", dpi=200)
#     savefig("../img/2phase-filtration-flux" * string(Integer(y_value)) * ".svg")
# end

function plot(sys::System, p::Parameters)
    plot_density(sys.u, sys.v, sys.ρ, sys.s, p)
    plot_pressure(sys.u, sys.v, sys.P, p)
    # plot_fluxes(sys.u, sys.v, sys.ρ, sys.s, p, 0.0, 1)
    # plot_fluxes(sys.u, sys.v, sys.ρ, sys.s, p, 2.0, p.ny - 1)
end

max_stars_repo_name: sofiabelen/Ideal-Gas-Compressible-Fluid

max_issues_repo_name: sofiabelen/Ideal-Gas-Compressible-Fluid

max_forks_repo_name: sofiabelen/Two-Phase-Filtration


text:
# Works, but doesn't make sense for: sankey, gauge
function legend!(ec::EChart; kwargs...)

	#Define data upfront for the most common cases
	#This currently clobbers, should this be a check for nothing instead of clobber?
	if ec.ec_charttype in ["circular", "funnel"]
		ec.legend = Legend(data = [x["name"] for x in ec.series[1].data])
	elseif ec.ec_charttype in ["streamgraph"]
		ec.legend = Legend(data = unique([x[3] for x in ec.series[1].data]))
	else
		ec.legend = Legend(data = [x.name for x in ec.series])
	end

	#Set all of the kwargs values provided
	for (k, v) in kwargs
	   setfield!(ec.legend, k, v)
	end

    return ec

end


text:
#--------------------------------------------------------------------
# Spacetime Discretization methods in Julia
# Soham 01-2018
#--------------------------------------------------------------------

struct Patch
    loc::Array{Int,1}
    value::Array{Float64,2}
end

struct Boundary
    kind::Int
    value::Array{Float64,1}
end


text:
# this is annoying
my_long_variable = 3
println("my_long_variable = ", my_long_variable)

function myshow(y)
    println("the value is $y")
end

a = 1
b = 2

myshow(a + b)

# but what if we want to know *whose* value that is? The solution is to use a macro

y = 3
@show y  # this is a macro

@show a + b  # macros can access the name of the variable somehow

# this is replacing the old code with new code, i.e. *code generation*


text:
module TestNullCLV

using Test
using Parameters: @with_kw, @unpack
using LyapunovExponents
using LyapunovExponents.Stages: is_finished
using LyapunovExponents: DEMOS, LEDemo, dimension, is_semi_unitary

@with_kw struct NullCLVTest
    name::String
    prob::CLVProblem
    tolerance::Float64
    err_rate::Float64
end

NullCLVTest(demo::LEDemo;
            tolerance = nothing,
            err_rate = 0.0,
            kwargs...) = NullCLVTest(
    name = demo.example.name,
    prob = CLVProblem(demo.prob; kwargs...),
    tolerance = tolerance,
    err_rate = err_rate,
)

null_CLV_tests = [
    NullCLVTest(LyapunovExponents.lorenz_63();
                t_clv = 20000,
                t_forward_tran = 4000,
                t_backward_tran = 4000,
                err_rate = 0.004,
                tolerance = 1e-2),
    # linz_sprott_99() requires a small `tspan` to make `tolerance`
    # smaller.
    NullCLVTest(LyapunovExponents.linz_sprott_99(t_renorm=0.1);
                t_clv = 2000,
                t_forward_tran = 4000,
                t_backward_tran = 4000,
                err_rate = 0.2,
                tolerance = 0.2),  # TODO: minimize
    NullCLVTest(LyapunovExponents.beer_95();
                t_clv = 2000,
                t_forward_tran = 1000,
                t_backward_tran = 1000,
                err_rate = 0.05,
                tolerance = 1e-2),
]

@time @testset "Null CLV: $(test.name)" for test in null_CLV_tests
    @unpack prob, tolerance, err_rate = test

    solver = init(prob; record=[:G, :C, :x])
    solve!(solver)

    Q0 = @view prob.tangent_prob.u0[:, 2:end]
    dims = size(Q0)
    x = solver.sol.x_history
    G = solver.sol.G_history
    C = solver.sol.C_history
    num_clv = ceil(Int, prob.t_clv / prob.t_renorm)
    @test_broken length(x) == num_clv
    @test_broken length(G) == num_clv
    @test length(C) == num_clv
    @test all(norm(Cₙ[:, i]) ≈ 1 for Cₙ in C for i in 1:size(Cₙ, 2))
    @test all(map(is_semi_unitary, G))

    function ∂ₜ(u, prob = prob.phase_prob, t = 0.0)
        du = similar(u)
        prob.f(du, u, prob.p, t)
        return du
    end

    angles = collect(
        let ∂ₜxₙ = ∂ₜ(x[n]),
            vₙ = G[n] * C[n][:, 2]
            acos(abs(∂ₜxₙ' * vₙ) / norm(∂ₜxₙ))
        end
        for n in 1:num_clv)

    @test mean(angles .> tolerance) <= err_rate

end

end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct IoK8sApiExtensionsV1beta1DeploymentSpec <: SwaggerModel
    minReadySeconds::Any # spec type: Union{ Nothing, Int32 } # spec name: minReadySeconds
    paused::Any # spec type: Union{ Nothing, Bool } # spec name: paused
    progressDeadlineSeconds::Any # spec type: Union{ Nothing, Int32 } # spec name: progressDeadlineSeconds
    replicas::Any # spec type: Union{ Nothing, Int32 } # spec name: replicas
    revisionHistoryLimit::Any # spec type: Union{ Nothing, Int32 } # spec name: revisionHistoryLimit
    rollbackTo::Any # spec type: Union{ Nothing, IoK8sApiExtensionsV1beta1RollbackConfig } # spec name: rollbackTo
    selector::Any # spec type: Union{ Nothing, IoK8sApimachineryPkgApisMetaV1LabelSelector } # spec name: selector
    strategy::Any # spec type: Union{ Nothing, IoK8sApiExtensionsV1beta1DeploymentStrategy } # spec name: strategy
    template::Any # spec type: Union{ Nothing, IoK8sApiCoreV1PodTemplateSpec } # spec name: template

    function IoK8sApiExtensionsV1beta1DeploymentSpec(;minReadySeconds=nothing, paused=nothing, progressDeadlineSeconds=nothing, replicas=nothing, revisionHistoryLimit=nothing, rollbackTo=nothing, selector=nothing, strategy=nothing, template=nothing)
        o = new()
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("minReadySeconds"), minReadySeconds)
        setfield!(o, Symbol("minReadySeconds"), minReadySeconds)
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("paused"), paused)
        setfield!(o, Symbol("paused"), paused)
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("progressDeadlineSeconds"), progressDeadlineSeconds)
        setfield!(o, Symbol("progressDeadlineSeconds"), progressDeadlineSeconds)
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("replicas"), replicas)
        setfield!(o, Symbol("replicas"), replicas)
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("revisionHistoryLimit"), revisionHistoryLimit)
        setfield!(o, Symbol("revisionHistoryLimit"), revisionHistoryLimit)
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("rollbackTo"), rollbackTo)
        setfield!(o, Symbol("rollbackTo"), rollbackTo)
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("selector"), selector)
        setfield!(o, Symbol("selector"), selector)
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("strategy"), strategy)
        setfield!(o, Symbol("strategy"), strategy)
        validate_property(IoK8sApiExtensionsV1beta1DeploymentSpec, Symbol("template"), template)
        setfield!(o, Symbol("template"), template)
        o
    end
end # type IoK8sApiExtensionsV1beta1DeploymentSpec

const _property_map_IoK8sApiExtensionsV1beta1DeploymentSpec = Dict{Symbol,Symbol}(Symbol("minReadySeconds")=>Symbol("minReadySeconds"), Symbol("paused")=>Symbol("paused"), Symbol("progressDeadlineSeconds")=>Symbol("progressDeadlineSeconds"), Symbol("replicas")=>Symbol("replicas"), Symbol("revisionHistoryLimit")=>Symbol("revisionHistoryLimit"), Symbol("rollbackTo")=>Symbol("rollbackTo"), Symbol("selector")=>Symbol("selector"), Symbol("strategy")=>Symbol("strategy"), Symbol("template")=>Symbol("template"))
const _property_types_IoK8sApiExtensionsV1beta1DeploymentSpec = Dict{Symbol,String}(Symbol("minReadySeconds")=>"Int32", Symbol("paused")=>"Bool", Symbol("progressDeadlineSeconds")=>"Int32", Symbol("replicas")=>"Int32", Symbol("revisionHistoryLimit")=>"Int32", Symbol("rollbackTo")=>"IoK8sApiExtensionsV1beta1RollbackConfig", Symbol("selector")=>"IoK8sApimachineryPkgApisMetaV1LabelSelector", Symbol("strategy")=>"IoK8sApiExtensionsV1beta1DeploymentStrategy", Symbol("template")=>"IoK8sApiCoreV1PodTemplateSpec")
Base.propertynames(::Type{ IoK8sApiExtensionsV1beta1DeploymentSpec }) = collect(keys(_property_map_IoK8sApiExtensionsV1beta1DeploymentSpec))
Swagger.property_type(::Type{ IoK8sApiExtensionsV1beta1DeploymentSpec }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiExtensionsV1beta1DeploymentSpec[name]))}
Swagger.field_name(::Type{ IoK8sApiExtensionsV1beta1DeploymentSpec }, property_name::Symbol) =  _property_map_IoK8sApiExtensionsV1beta1DeploymentSpec[property_name]

function check_required(o::IoK8sApiExtensionsV1beta1DeploymentSpec)
    (getproperty(o, Symbol("template")) === nothing) && (return false)
    true
end

function validate_property(::Type{ IoK8sApiExtensionsV1beta1DeploymentSpec }, name::Symbol, val)
end


text:
@testset "clearborder" begin
    #Case when given border width is more than image size
    img = [1 0 1 1 1 1
            0 1 1 1 0 0
            1 1 0 0 0 1
            0 1 0 1 0 1
            1 1 0 0 0 1
            0 0 1 1 0 0]
    @test_throws ArgumentError clearborder(img,7)

    #Normal Case
    img = [0 0 0 0 0 0 0 1 0
            0 0 0 0 1 0 0 0 0
            1 0 0 1 0 1 0 0 0
            0 0 1 1 1 1 1 0 0
            0 1 1 1 1 1 1 1 0
            0 0 0 0 0 0 0 0 0]
    cleared_img = clearborder(img)
    check_img = copy(img)
    check_img[3,1] = 0
    check_img[1,8] = 0
    @test cleared_img == check_img

    cleared_img = clearborder(img,2)
    @test cleared_img == fill!(similar(img), zero(eltype(img)))

    cleared_img = clearborder(img,2,10)
    @test cleared_img == 10*fill!(similar(img), one(eltype(img)))

    #Multidimentional Case
    img = cat([0 0 0 0;
                    0 0 0 0;
                    0 0 0 0;
                    1 0 0 0],
                [0 0 0 0;
                    0 1 1 0;
                    0 0 1 0;
                    0 0 0 0],
                [0 0 0 0;
                    0 0 0 0;
                    0 0 0 0;
                    0 0 0 0], dims=3)
    cleared_img = clearborder(img)
    check_img = copy(img)
    check_img[4,1,1] = 0
    @test cleared_img == check_img

    cleared_img = clearborder(img,2)
    @test cleared_img == fill!(similar(img), zero(eltype(img)))

    cleared_img = clearborder(img,2,10)
    @test cleared_img == 10*fill!(similar(img), one(eltype(img)))

    #Grayscale input image Case
    img = [1 2 3 1 2
            3 3 5 4 2
            3 4 5 4 2
            3 3 2 1 2]
    cleared_img = clearborder(img)
    check_img = [0 0 0 0 0
                    0 0 5 4 0
                    0 4 5 4 0
                    0 0 0 0 0]
    @test cleared_img == check_img
end


text:
module Bioview

include("errors.jl")
include("options.jl")
include("MSA.jl")
include("Ngl.jl")

isijulia() = isdefined(Main, :IJulia) && Main.IJulia.inited

if isijulia()
    js = """
    (function (\$) {
        require.config({
            paths: {
                'msa': 'https://cdn.bio.sh/msa/latest/msa.min.gz'
            },
            shim: {
                'msa': {
                    exports: 'msa'
                }
            }
        });
     })(jQuery);
     """
    display("text/html", """

""")
    display("text/javascript", js)
    display("text/javascript", """console.log("[Bioview] loaded");""")
end

end


text:
using SSGrB
using Test

@testset "SSGrB.jl" begin
    # Write your tests here.
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec <: SwaggerModel
    maxReplicas::Any # spec type: Union{ Nothing, Int32 } # spec name: maxReplicas
    metrics::Any # spec type: Union{ Nothing, Vector{IoK8sApiAutoscalingV2beta2MetricSpec} } # spec name: metrics
    minReplicas::Any # spec type: Union{ Nothing, Int32 } # spec name: minReplicas
    scaleTargetRef::Any # spec type: Union{ Nothing, IoK8sApiAutoscalingV2beta2CrossVersionObjectReference } # spec name: scaleTargetRef

    function IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec(;maxReplicas=nothing, metrics=nothing, minReplicas=nothing, scaleTargetRef=nothing)
        o = new()
        validate_property(IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec, Symbol("maxReplicas"), maxReplicas)
        setfield!(o, Symbol("maxReplicas"), maxReplicas)
        validate_property(IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec, Symbol("metrics"), metrics)
        setfield!(o, Symbol("metrics"), metrics)
        validate_property(IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec, Symbol("minReplicas"), minReplicas)
        setfield!(o, Symbol("minReplicas"), minReplicas)
        validate_property(IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec, Symbol("scaleTargetRef"), scaleTargetRef)
        setfield!(o, Symbol("scaleTargetRef"), scaleTargetRef)
        o
    end
end # type IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec

const _property_map_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec = Dict{Symbol,Symbol}(Symbol("maxReplicas")=>Symbol("maxReplicas"), Symbol("metrics")=>Symbol("metrics"), Symbol("minReplicas")=>Symbol("minReplicas"), Symbol("scaleTargetRef")=>Symbol("scaleTargetRef"))
const _property_types_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec = Dict{Symbol,String}(Symbol("maxReplicas")=>"Int32", Symbol("metrics")=>"Vector{IoK8sApiAutoscalingV2beta2MetricSpec}", Symbol("minReplicas")=>"Int32", Symbol("scaleTargetRef")=>"IoK8sApiAutoscalingV2beta2CrossVersionObjectReference")
Base.propertynames(::Type{ IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec }) = collect(keys(_property_map_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec))
Swagger.property_type(::Type{ IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec[name]))}
Swagger.field_name(::Type{ IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec }, property_name::Symbol) =  _property_map_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec[property_name]

function check_required(o::IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec)
    (getproperty(o, Symbol("maxReplicas")) === nothing) && (return false)
    (getproperty(o, Symbol("scaleTargetRef")) === nothing) && (return false)
    true
end

function validate_property(::Type{ IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec }, name::Symbol, val)
end