text:
using PkgSRA
using Plots, Random
using Flux, DiffEqFlux, OrdinaryDiffEq, Statistics
using DSP
pyplot()
Random.seed!(11)

#####
##### Define the controlled dynamical system
#####
# Load example problem
include("paper_settings.jl")
include(EXAMPLE_FOLDERNAME*"example_mass_spring.jl")

# Define the time dependent forcing function
# num_ctr = 2;
# U_starts = rand(num_ctr,1) .* tspan[2]
# U_width = 0.05;
# U_func(t) = U_func_time(t, u, U_width, U_starts)
U_func = spring_forcing_example(tspan)

# Solve the system
dat = Array(solve_msd_system(U_func))
dat_unforced = Array(solve_msd_system())
# Add a constant to the data
n, m = size(dat)
dat_and_const = vcat(dat, ones(1,m))

# Get true control signal
U_true = zeros(size(dat))
for (i, t) in enumerate(collect(ts))
    U_true[:,i] = U_func(t, dat[:,1])
end

#####
##### SRA: initialize the separation for dynamics vs. control
#####
dat_grad = numerical_derivative(dat, ts)

U_guess = sra_dmd(dat_and_const, dat_grad, quantile_threshold=0.8)[1]
A, B = dmdc(dat_and_const, dat_grad, U_guess)
# Loop a couple of times
for i in 1:20
    # Update guess for control signal
    global U_guess = calculate_residual(dat_and_const,
                                        dat_grad,
                                        A)
    sparsify_signal!(U_guess, quantile_threshold=0.8)
    # Update guess for dynamics
    global A, B = dmdc(dat_and_const, dat_grad, U_guess)
end

#####
##### Try to learn the dynamics directly
#####
nn_dim = 64
    U_dim = 1 # Expect that the true dimensionality is 1
core_dyn_naive = Dense(n, n, identity)
# Part 2: Neural network for control signal
ctr_dyn_naive = Chain(Dense(1,nn_dim, initb=(x)-> tspan[2].*rand(x)),
                        Dense(nn_dim, nn_dim, σ),
                        Dense(nn_dim, nn_dim, σ),
                        Dense(nn_dim, U_dim),
                        Dense(U_dim,2)) # Equivalent to the B matrix
p = param(Float32[1.0; 1.0])

function dudt_naive(u::AbstractArray,p,t)
    core_dyn_naive(u) + p.*ctr_dyn_naive([t])
end
prob_naive = ODEProblem(dudt_naive,u0,tspan,p)

_x = param(u0) # The initial condition can be learned too

function predict_rd_naive()
    Flux.Tracker.collect(diffeq_rd(p,prob_naive,Tsit5(),u0=_x, saveat=ts))
end
function loss_naive(λ=0.01)
    return sum(abs2,predict_rd_naive() .- dat) +      # Good fit
            λ*sum(abs,ctr_dyn_naive(collect(ts)'))   # L1 norm on ctr
end

# SOLVE the mixed NODE
ps = params(core_dyn_naive, ctr_dyn_naive, p);

# Initial quick learning
opt = ADAM(0.01)
dat_dummy = Iterators.repeated((), 300)
Flux.train!(loss_naive, ps,
            dat_dummy, opt, cb = ()->@show loss_naive())
# Run for a long time
opt = ADAM(0.001)
tol = 25
dat_dummy = Iterators.repeated((), 20)
num_iter = 1
max_iter = 10
while loss_naive() > tol
    Flux.train!(loss_naive, ps,
                dat_dummy, opt, cb = ()->@show loss_naive())
    global num_iter += 1
    num_iter > max_iter && break
end

#####
##### Plot and save: uninitialized
#####
# Full fit
sol = Flux.data(predict_rd_naive())
p_naive_full = plot(sol[2,:], label="Simulation",
                    color=COLOR_DICT["intrinsic"], lw=2);
    plot!(dat_and_const[2,:], label="Data",
                    color=COLOR_DICT["data"], lw=3);
    title!("Unitilialized Fit");

# Only "dynamics"
function dudt_naive_only_dyn(u::AbstractArray,p,t)
    core_dyn_naive(u)
end
prob_naive_only_dyn = ODEProblem(dudt_naive_only_dyn,u0,tspan,p)
function predict_rd_naive_dyn()
    Flux.Tracker.collect(diffeq_rd(p,prob_naive_only_dyn,Tsit5(),u0=_x, saveat=ts))
end
p_naive_dyn = plot(Flux.data(predict_rd_naive_dyn())[2,:], legend=false,
                    color=COLOR_DICT["intrinsic"], lw=2);
    title!("Intrinsic Dynamics");

# Only "control"
dat_naive_ctr = Flux.data(ctr_dyn_naive(collect(ts)'))
p_naive_ctr = plot(dat_naive_ctr[2,:], legend=false,
                    color=COLOR_DICT["control_time"], lw=2);
    title!("Control Signal");

# Save everything
my_layout = @layout [p_naive_full  [p_naive_dyn; p_naive_ctr]];
    p_all = plot(p_naive_full, p_naive_dyn, p_naive_ctr, layout = my_layout)
fname = FIGURE_FOLDERNAME * "fig_uninitialized.png";
savefig(p_all, fname)

#####
##### Instead: initialize the controller and then learn
#####
# SRA: Learn a neural network to approximate the guess
# Note: need to initialize the first layer so that the whole space is used
ctr_dyn = Chain(Dense(1,nn_dim, initb=(x)-> tspan[2].*rand(x)),
                Dense(nn_dim, nn_dim, σ),
                Dense(nn_dim, nn_dim, σ),
                Dense(nn_dim, U_dim),
                Dense(U_dim,2)) # Equivalent to the B matrix
ps = Flux.params(ctr_dyn)
    loss_U() = sum(abs2,ctr_dyn(collect(ts)') .- U_guess)
    loss_to_use = loss_U

# Initial fast learning
tol = 500
    dat_dummy = Iterators.repeated((), 100)
    opt = ADAM(0.01)
while loss_to_use() > 5*tol
    Flux.train!(loss_to_use, ps, dat_dummy, opt, cb = ()->@show loss_to_use())
end
opt = ADAM(0.001)
while loss_to_use() > tol
    Flux.train!(loss_to_use, ps, dat_dummy, opt, cb = ()->@show loss_to_use())
end
println("Finished learning control signal")
# plot(Flux.data(ctr_dyn(collect(ts)')[2,:]))

## Now learn entire system
core_dyn = Dense(param(Float32.(A[:, 1:n])),
                 param(Float32.(A[:, end])),
                 identity)
# Part 2: Neural network for control signal; initialized above
p = param(Float32[1.0; 1.0])

function dudt_(u::AbstractArray,p,t)
    core_dyn(u) + p.*ctr_dyn([t])
end
prob = ODEProblem(dudt_,u0,tspan,p)

_x = param(u0) # The initial condition can be learned too

function predict_rd()
    Flux.Tracker.collect(diffeq_rd(p,prob,Tsit5(),u0=_x, saveat=ts))
end
function loss_rd(λ1=0.01, λ2=0.1)
    return sum(abs2,predict_rd() .- dat) +      # Good fit
            λ1*loss_U() +                # Control signal close to guess
            λ2*sum(abs,ctr_dyn(collect(ts)'))   # L1 norm on ctr
end

## SOLVE the initialized mixed NODE
ps = params(core_dyn,ctr_dyn,p);

# Initial quick learning
opt = ADAM(0.0001)
dat_dummy = Iterators.repeated((), 10)
Flux.train!(loss_rd, ps,
            dat_dummy, opt, cb = ()->@show loss_rd())
# Run for a long time
opt = ADAM(0.00001)
tol = 50
dat_dummy = Iterators.repeated((), 10)
while loss_rd() > tol
    Flux.train!(loss_rd, ps,
                dat_dummy, opt, cb = ()->@show loss_rd())
    break
end

#####
##### Plot and save: Initialized
#####
# Full fit
sol = Flux.data(predict_rd())
p_full = plot(dat_and_const[2,:], label="Data",
                            color=COLOR_DICT["data"], lw=3);
    plot!(sol[2,:], label="Simulation",
                            color=COLOR_DICT["intrinsic"], lw=2);
    title!("Initialized Fit");

# Only "dynamics"
function dudt_only_dyn(u::AbstractArray,p,t)
    core_dyn(u)
end
prob_only_dyn = ODEProblem(dudt_only_dyn,u0,tspan,p)
function predict_rd_dyn()
    Flux.Tracker.collect(diffeq_rd(p,prob_only_dyn,Tsit5(),u0=_x, saveat=ts))
end
p_dyn = plot(dat_unforced[2,:], label="True",
                    color=COLOR_DICT["intrinsic_true"], lw=3)
        plot!(Flux.data(predict_rd_dyn())[2,:], label="Simulation",
                    color=COLOR_DICT["intrinsic"], lw=2);
    title!("Intrinsic Dynamics");

# Only "control"
dat_full_ctr = Flux.data(p.*ctr_dyn(collect(ts)'))
p_ctr = plot(U_true[2,:], label="True", lw=2,
            color=COLOR_DICT["control_true"])
        plot!(dat_full_ctr[2,:], label="Simulation",
                color=COLOR_DICT["control_time"], lw=2);
    title!("Control Signal");

# Save everything
my_layout = @layout [p_full  [p_dyn; p_ctr]];
    p_all = plot(p_full, p_dyn, p_ctr, layout = my_layout)
fname = FIGURE_FOLDERNAME * "fig_initialized.png";
savefig(p_all, fname)


text:
##IDM
function test_idm_creation()
	println("\t\tTesting IDM Creation")
	#do it directly using the build functions
	p1 = Multilane.build_cautious_idm(30.,2.)
	p2 = Multilane.build_normal_idm(30.,2.)
	p3 = Multilane.build_aggressive_idm(30.,2.)
	#use the new constructor
	ps = [IDMParam(s,35.,3.) for s in ["AGGRESSIVE","CautiOUS","normal"]]
end

function test_idm_equality()
	#do it directly using the build functions
	p1 = Multilane.build_cautious_idm(30.,2.)
	p2 = Multilane.build_normal_idm(30.,2.)
	p3 = Multilane.build_aggressive_idm(30.,2.)
	#use the new constructor
	ps = [IDMParam(s,35.,3.) for s in ["AGGRESSIVE","CautiOUS","normal"]]
	#test equality
	test_equality("IDM",ps)
	assert(p1 == IDMParam(1.,1.,2.,30.,2.))
	assert(p2 == IDMParam(1.5,1.5,1.4,30.,2.))
	assert(p3 == IDMParam(2.,2.,0.8,30.,2.))
	assert(IDMParam(1.,1.,2.,30.,2.) == p1)
	assert(p2 == p2)
	assert(ps[3] == ps[3])
	assert(p1 != ps[1])
	assert(p2 != ps[2])
	assert(p3 != ps[3])
	assert(p1 != p2)
	assert(p2 != p1)
end

function test_idm_hashing()
	#println("\t\tTesting IDM Hashing")
	#do it directly using the build functions
	p1 = Multilane.build_cautious_idm(30.,2.)
	p2 = Multilane.build_normal_idm(30.,2.)
	p3 = Multilane.build_aggressive_idm(30.,2.)
	#use the new constructor
	ps = [IDMParam(s,35.,3.) for s in ["AGGRESSIVE","CautiOUS","normal"]]
	#test hashing as applied to dictionaries
	test_hashing("IDM",ps)
end

#TODO FIX VVV

function test_get_dv_ds()
	println("\t\tTesting get_dv_ds()")
	nb_lanes = 3
	pp = PhysicalParam(nb_lanes,lane_length=12.)
	bs = IDMMOBILBehavior[IDMMOBILBehavior(x[1],x[2],x[3],idx) for (idx,x) in enumerate(product(["cautious","normal","aggressive"],[pp.v_slow;pp.v_med;pp.v_fast],[pp.l_car]))]
	#CASE: just agent car
	cs = CarState[CarState(6.,2,31.,0,bs[1],0)]
	dmodel = IDMMOBILModel(length(cs), pp)
	s = MLState(0.0,0.0,cs)
	nbhd = get_neighborhood(pp,s,1)
	for nbr = 1:6
		dv, ds = get_dv_ds(pp,s,nbhd,1,nbr)
		assert(dv,0.)
		assert(ds,1000.)
	end
	#full house
	cs = CarState[CarState(0.,1,27.,0,bs[1],1),
								CarState(0.,2,30.,0,bs[1],2),
								CarState(0.,3,35.,0,bs[1],3),
								CarState(12.,1,27.,0,bs[1],4),
								CarState(12.,2,30.,0,bs[1],5),
								CarState(12.,3,35.,0,bs[1],6),
								CarState(6.,2,31.,0,bs[1],7)]

	_ds = 2.

	dmodel = IDMMOBILModel(length(cs), pp)
	s = MLState(0.0,0.0,cs)
	nbhd = get_neighborhood(pp,s,7)
	dv, ds = get_dv_ds(pp,s,nbhd,7,1)
	assert(dv,4.)
	assert(ds,_ds)
	dv, ds = get_dv_ds(pp,s,nbhd,7,2)
	assert(dv,1.)
	assert(ds,_ds)
	dv, ds = get_dv_ds(pp,s,nbhd,7,3)
	assert(dv,-4.)
	assert(ds,_ds)
	dv, ds = get_dv_ds(pp,s,nbhd,7,4)
	assert(dv,-4.)
	assert(ds,_ds)
	dv, ds = get_dv_ds(pp,s,nbhd,7,5)
	assert(dv,-1.)
	assert(ds,_ds)
	dv, ds = get_dv_ds(pp,s,nbhd,7,6)
	assert(dv,4.)
	assert(ds,_ds)

end

function test_idm_dv()
	println("\t\tTesting IDM Calculations")
	# NOTE this just prints it out for general sanity checking
	#TODO: calculate by hand...? or use existing examples if can be found
	nb_lanes = 2
	_a = MLAction(0.,0.)
	pp = PhysicalParam(nb_lanes,lane_length=48.)
	bs = IDMMOBILBehavior[IDMMOBILBehavior(x[1],x[2],x[3],idx) for (idx,x) in enumerate(product(["cautious","normal","aggressive"],[pp.v_slow;pp.v_med;pp.v_fast],[pp.l_car]))]
	#CASE: it's faster, but there's no space--is this even a real case?
	#CASE: it's faster and there is space
	cs = CarState[CarState(1.,2,27.,0,IDMMOBILBehavior("aggressive",35.,4.,1),5),CarState(36.,2,27.,0,IDMMOBILBehavior("cautious",27.,4.,1),1)]
	s = MLState(0.0,0.0,cs)
	dmodel = IDMMOBILModel(length(cs),pp)
	nbhd = get_neighborhood(pp,s,1)
	v = cs[1].vel
	dv, ds = get_dv_ds(pp,s,nbhd,1,2)
	a = get_idm_dv(cs[1].behavior.p_idm,pp.dt,v,dv,ds)/pp.dt
	println("Fast going slow behind slow: v=$v,dv=$dv,s=$ds,a=$a")
	cs = CarState[CarState(1.,2,35.,0,IDMMOBILBehavior("aggressive",35.,4.,1),4),CarState(36.,2,27.,0,IDMMOBILBehavior("cautious",27.,4.,1),2)]
	s = MLState(0.0,0.0,cs)
	dmodel = IDMMOBILModel(length(cs),pp)
	nbhd = get_neighborhood(pp,s,1)
	v = cs[1].vel
	dv, ds = get_dv_ds(pp,s,nbhd,1,2)
	a = get_idm_dv(cs[1].behavior.p_idm,pp.dt,v,dv,ds)/pp.dt
	println("Fast going fast behind slow: v=$v,dv=$dv,s=$ds,a=$a")
	cs = CarState[CarState(1.,2,35.,0,IDMMOBILBehavior("cautious",27.,4.,1),6),CarState(36.,2,27.,0,IDMMOBILBehavior("cautious",27.,4.,1),3)]
	s = MLState(0.0,0.0,cs)
	dmodel = IDMMOBILModel(length(cs),pp)
	nbhd = get_neighborhood(pp,s,1)
	v = cs[1].vel
	dv, ds = get_dv_ds(pp,s,nbhd,1,2)
	a = get_idm_dv(cs[1].behavior.p_idm,pp.dt,v,dv,ds)/pp.dt
	println("slow going fast behind slow: v=$v,dv=$dv,s=$ds,a=$a")
	cs = CarState[CarState(1.,2,27.,0,IDMMOBILBehavior("cautious",27.,4.,1),7),CarState(36.,2,27.,0,IDMMOBILBehavior("cautious",27.,4.,1),8)]
	s = MLState(0.0,0.0,cs)
	dmodel = IDMMOBILModel(length(cs),pp)
	nbhd = get_neighborhood(pp,s,1)
	v = cs[1].vel
	dv, ds = get_dv_ds(pp,s,nbhd,1,2)
	a = get_idm_dv(cs[1].behavior.p_idm,pp.dt,v,dv,ds)/pp.dt
	println("slow going slow behind slow: v=$v,dv=$dv,s=$ds,a=$a")
	cs = CarState[CarState(1.,2,35.,0,IDMMOBILBehavior("cautious",27.,4.,1),9)]
	s = MLState(0.0,0.0,cs)
	dmodel = IDMMOBILModel(length(cs),pp)
	nbhd = get_neighborhood(pp,s,1)
	v = cs[1].vel
	dv, ds = get_dv_ds(pp,s,nbhd,1,2)
	a = get_idm_dv(cs[1].behavior.p_idm,pp.dt,v,dv,ds)/pp.dt
	println("slow going fast: v=$v,dv=$dv,s=$ds,a=$a")
	cs = CarState[CarState(1.,2,27.,0,IDMMOBILBehavior("cautious",35.,4.,1),10)]
	s = MLState(0.0,0.0,cs)
	dmodel = IDMMOBILModel(length(cs),pp)
	nbhd = get_neighborhood(pp,s,1)
	v = cs[1].vel
	dv, ds = get_dv_ds(pp,s,nbhd,1,2)
	a = get_idm_dv(cs[1].behavior.p_idm,pp.dt,v,dv,ds)/pp.dt
	println("fast going slow: v=$v,dv=$dv,s=$ds,a=$a")
	cs = CarState[CarState(1.,2,31.,0,IDMMOBILBehavior("cautious",27.,4.,1),11)]
	s = MLState(0.0,0.0,cs)
	dmodel = IDMMOBILModel(length(cs),pp)
	nbhd = get_neighborhood(pp,s,1)
	v = cs[1].vel
	dv, ds = get_dv_ds(pp,s,nbhd,1,2)
	a = get_idm_dv(cs[1].behavior.p_idm,pp.dt,v,dv,ds)/pp.dt
	println("slow going med: v=$v,dv=$dv,s=$ds,a=$a")
	cs = CarState[CarState(1.,2,31.,0,IDMMOBILBehavior("cautious",35.,4.,1),12)]
	s = MLState(0.0,0.0,cs)
	dmodel = IDMMOBILModel(length(cs),pp)
	nbhd = get_neighborhood(pp,s,1)
	v = cs[1].vel
	dv, ds = get_dv_ds(pp,s,nbhd,1,2)
	a = get_idm_dv(cs[1].behavior.p_idm,pp.dt,v,dv,ds)/pp.dt
	println("fast going med: v=$v,dv=$dv,s=$ds,a=$a")
end

function test_idm()
	println("\tTesting IDM Units...")
	test_idm_creation()
	test_idm_hashing()
	test_get_dv_ds()
	test_idm_dv()
end

ext: jl

max_stars_repo_name: zhcao/HighwayExit

max_issues_repo_name: zhcao/HighwayExit

max_forks_repo_name: zhcao/HighwayExit


text:
function Linear_Spline(t::Vector,V::Vector)
  # t must be the time vector
  # V is any vector that you are interpolating

  # remove any repeating values
  M = Array(Bool,length(t)); M[1:length(t)] = false;
  for i in 1:length(t)-1
      if t[i]==t[i+1]
          M[i]=true
      else
          M[i]=false
      end
  end

  rm_idx = find(M)

  if (length(t)==length(rm_idx))
    error("No time has elapsed and there will be an issue with interpolation! -----> Do not even try to simulate this data!")
  end

  # initialize vetors
  t_new = Array(Float64,(length(t)-length(rm_idx)));
  V_new = Array(Float64,(length(t)-length(rm_idx)));

  q=1;
  for i in 1:length(t)
      if !M[i]
          t_new[q] = t[i];
          V_new[q] = V[i];
          q=q+1
      end
  end

  # make interpolant using Dierckx.jl
  #Spline1D(t_new,V_new,k=1)    # linear spline

  # make interpolant using Interpolations.jl
  knots = (t_new,)
  interpolate(knots,V_new,Gridded(Linear()))
end


text:
function scores(a::AbstractArray; latest = false, top=0)

end

max_stars_repo_name: josobar/julia

max_issues_repo_name: josobar/julia

max_forks_repo_name: josobar/julia


text:
import Example: greet
greet();


text:
function ODBCAllocHandle(handletype,parenthandle)
	handle = Array(Ptr{Void},1)
	if @FAILED SQLAllocHandle(handletype,parenthandle,handle)
		error("[ODBC]: ODBC Handle Allocation Failed; Return Code: $ret")
	else
		#If allocation succeeded, retrieve handle pointer stored in handle's array index 1
		handle = handle[1]
		if handletype == SQL_HANDLE_ENV
			if @FAILED SQLSetEnvAttr(handle,SQL_ATTR_ODBC_VERSION,SQL_OV_ODBC3)
				#If version-setting fails, release environment handle and set global env variable to a null pointer
				SQLFreeHandle(SQL_HANDLE_ENV,handle)
				global env = C_NULL
				error("[ODBC]: Failed to set ODBC version; Return Code: $ret")
			end
		end
	end
	return handle
end
#ODBCConnect: Connect to qualified DSN (pre-established through ODBC Admin), with optional username and password inputs
function ODBCConnect!(dbc::Ptr{Void},dsn::String,username::String,password::String)
	if @FAILED SQLConnect(dbc,dsn,username,password)
		ODBCError(SQL_HANDLE_DBC,dbc)
		error("[ODBC]: SQLConnect failed; Return Code: $ret")
	end
end
#ODBCDriverConnect: Alternative connect function that allows user to create datasources on the fly through opening the ODBC admin
function ODBCDriverConnect!(dbc::Ptr{Void},conn_string::String,driver_prompt::Uint16)
	window_handle = C_NULL
	@windows_only window_handle = ccall( (:GetForegroundWindow, "user32"), Ptr{Void}, () )
	@windows_only driver_prompt = SQL_DRIVER_PROMPT
	out_buff = Array(Int16,1)
	if @FAILED SQLDriverConnect(dbc,window_handle,conn_string,C_NULL,out_buff,driver_prompt)
		ODBCError(SQL_HANDLE_DBC,dbc)
		error("[ODBC]: SQLDriverConnect failed; Return Code: $ret")
	end
end
#ODBCQueryExecute: Send query to DMBS
function ODBCQueryExecute(stmt::Ptr{Void},querystring::String)
	if @FAILED SQLExecDirect(stmt,querystring)
		ODBCError(SQL_HANDLE_STMT,stmt)
		error("[ODBC]: SQLExecDirect failed; Return Code: $ret")
	end
end
#ODBCMetadata: Retrieve resultset metadata once query is processed, Metadata type is returned
function ODBCMetadata(stmt::Ptr{Void},querystring::String)
		#Allocate space for and fetch number of columns and rows in resultset
		cols = Array(Int16,1)
		rows = Array(Int,1)
		SQLNumResultCols(stmt,cols)
		SQLRowCount(stmt,rows)
		#Allocate arrays to hold each column's metadata
		colnames = UTF8String[]
		coltypes = Array((String,Int16),0)
		colsizes = Int[]
		coldigits = Int16[]
		colnulls = Int16[]
		#Allocate space for and fetch the name, type, size, etc. for each column
		for x in 1:cols[1]
			column_name = zeros(Uint8,256)
			name_length = Array(Int16,1)
			datatype = Array(Int16,1)
			column_size = Array(Int,1)
			decimal_digits = Array(Int16,1)
			nullable = Array(Int16,1)
			SQLDescribeCol(stmt,x,column_name,name_length,datatype,column_size,decimal_digits,nullable)
			push!(colnames,ODBCClean(column_name,1,name_length[1]))
			push!(coltypes,(get(SQL_TYPES,int(datatype[1]),"SQL_CHAR"),datatype[1]))
			push!(colsizes,int(column_size[1]))
			push!(coldigits,decimal_digits[1])
			push!(colnulls,nullable[1])
		end
	return Metadata(querystring,int(cols[1]),rows[1],colnames,coltypes,colsizes,coldigits,colnulls)
end
#ODBCFetch: Using resultset metadata, allocate space/arrays for previously generated resultset, retrieve results
function ODBCBindCols(stmt::Ptr{Void},meta::Metadata)
	#with catalog functions or all-filtering WHERE clauses, resultsets can have 0 rows/cols
	meta.rows == 0 && return (Any[],Any[],0)
	rowset = MULTIROWFETCH > meta.rows ? (meta.rows < 0 ? 1 : meta.rows) : MULTIROWFETCH
	SQLSetStmtAttr(stmt,SQL_ATTR_ROW_ARRAY_SIZE,uint(rowset),SQL_IS_UINTEGER)

	#these Any arrays are where the ODBC manager dumps result data
	indicator = Any[]
	columns = Any[]
	for x in 1:meta.cols
		sqltype = meta.coltypes[x][2]
		#we need the C type so the ODBC manager knows how to store the data
		ctype = get(SQL2C,sqltype,SQL_C_CHAR)
		#we need the julia type that corresponds to the C type size
		jtype = get(SQL2Julia,sqltype,Uint8)
		holder, jlsize = ODBCColumnAllocate(jtype,meta.colsizes[x]+1,rowset)
		ind = Array(Int,rowset)
		if @SUCCEEDED ODBC.SQLBindCols(stmt,x,ctype,holder,int(jlsize),ind)
			push!(columns,holder)
			push!(indicator,ind)
		else #SQL_ERROR
			ODBCError(SQL_HANDLE_STMT,stmt)
			error("[ODBC]: SQLBindCol $x failed; Return Code: $ret")
		end
	end
	return (columns, indicator, rowset)
end

#ODBCColumnAllocate is used to allocate the raw underlying C-type buffers
# to be bound in SQLBindCol
ODBCColumnAllocate(x,y,z) 				= (Array(x,z),sizeof(x))
ODBCColumnAllocate(x::Type{Uint8},y,z) 	= (zeros(x,(y,z)),y)
ODBCColumnAllocate(x::Type{Uint16},y,z) = (zeros(x,(y,z)),y*2)
ODBCColumnAllocate(x::Type{Uint32},y,z) = (zeros(x,(y,z)),y*4)

#ODBCAllocate is the Julia type array that the raw underlying C-type buffer
# data is converted to when moved to a DataFrame or written to file
ODBCAllocate(x,y) 							= zeros(eltype(typeof(x)),y)
ODBCAllocate(x::Array{Uint8,2},y) 			= Array(UTF8String,y)
ODBCAllocate(x::Array{Uint16,2},y) 			= Array(UTF16String,y)
ODBCAllocate(x::Array{Uint32,2},y) 			= Array(UTF8String,y)
ODBCAllocate(x::Array{SQLDate,1},y) 		= Array(Date,y)
ODBCAllocate(x::Array{SQLTime,1},y) 		= Array(SQLTime,y)
ODBCAllocate(x::Array{SQLTimestamp,1},y) 	= Array(DateTime{ISOCalendar,UTC},y)

#ODBCClean does any necessary transformations from raw C-type to Julia type
ODBCClean(x,y,z) = x[y]
ODBCClean(x::Array{Uint8},y,z) 			= bytestring(x[1:z,y])
ODBCClean(x::Array{Uint16},y,z) 		= UTF16String(x[1:z,y])
ODBCClean(x::Array{Uint32},y,z)			= bytestring(convert(Array{Uint8},x[1:z,y]))
ODBCClean(x::Array{SQLDate,1},y,z) 		= date(x[y].year,0 < x[y].month < 13 ? x[y].month : 1,x[y].day)
ODBCClean(x::Array{SQLTimestamp,1},y,z)	= datetime(int64(x[y].year),int64(0 < x[y].month < 13 ? x[y].month : 1),int64(x[y].day),
													int64(x[y].hour),int64(x[y].minute),int64(x[y].second),int64(div(x[y].fraction,1000000)))

ODBCCopy!(dest,dsto,src,n,ind) = unsafe_copy!(pointer(dest,dsto),pointer(src,1),n)
function ODBCCopy!(dest::Array{UTF8String},dsto,src::Array{Uint8,2},n,ind)
	for i=1:n
        @inbounds arrayset(dest, utf8(bytestring(src[1:ind[i],i])), i+dsto-1)
    end
end
function ODBCCopy!(dest::Array{UTF16String},dsto,src::Array{Uint16,2},n,ind)
	for i=1:n
        @inbounds arrayset(dest, UTF16String(src[1:div(ind[i],2),i]), i+dsto-1)
    end
end
function ODBCCopy!(dest::Array{UTF8String},dsto,src::Array{Uint32},n,ind)
	for i=1:n
        @inbounds arrayset(dest, utf8(bytestring(convert(Array{Uint8},src[1:div(ind[i],4),i]))), i+dsto-1)
    end
end
function ODBCCopy!{D<:Date}(dest::Array{D},dsto,src::Array{SQLDate},n,ind)
	for i=1:n
        @inbounds arrayset(dest, date(src[i].year,
        	0 < src[i].month < 13 ? src[i].month : 1,src[i].day), i+dsto-1)
    end
end
function ODBCCopy!{D<:DateTime}(dest::Array{D},dsto,src::Array{SQLTimestamp},n,ind)
	for i=1:n
        @inbounds arrayset(dest, datetime(src[i].year,0 < src[i].month < 13 ? src[i].month : 1,
        	src[i].day,src[i].hour,src[i].minute,src[i].second,div(src[i].fraction,1000000)),i+dsto-1)
    end
end
function ODBCCopy!(dest::Array{SQLTime},dsto,src::Array{SQLTime},n,ind)
	for i=1:n
        @inbounds arrayset(dest, src[i], i+dsto-1)
    end
end

#ODBCEscape takes a Julia value and gets it ready for writing to a file
ODBCEscape(x) = string(x)
ODBCEscape(x::String) = "\"" * x * "\""

#function for fetching a resultset into a DataFrame
function ODBCFetchDataFrame(stmt::Ptr{Void},meta::Metadata,columns::Array{Any,1},rowset::Int,indicator)
	tic()
	cols = Array(Any,meta.cols)
	for i = 1:meta.cols
		cols[i] = ODBCAllocate(columns[i],meta.rows)
	end
	rowsfetched = zeros(Int64,1)
	SQLSetStmtAttr(stmt,SQL_ATTR_ROWS_FETCHED_PTR,rowsfetched,SQL_NTS)
	r = 1
	while @SUCCEEDED SQLFetchScroll(stmt,SQL_FETCH_NEXT,0)
		rows = rowsfetched[1] < rowset ? rowsfetched[1] : rowset
		for col in 1:meta.cols
			@inbounds ODBCCopy!(cols[col],r,columns[col],rows,indicator[col])
		end
		r += rows
	end
	toc()
	resultset = DataFrame(cols, Index(meta.colnames))
end
function ODBCDirectToFile(stmt::Ptr{Void},meta::Metadata,columns::Array{Any,1},rowset::Int,output::String,delim::Char,l::Int)
	out_file = l == 0 ? open(output,"w") : open(output,"a")
	write(out_file,join(meta.colnames,delim)*"\n")
	while @SUCCEEDED SQLFetchScroll(stmt,SQL_FETCH_NEXT,0)
		for row in 1:rowset, col in 1:meta.cols
			write(out_file,ODBCEscape(ODBCClean(columns[col],row)))
	        write(out_file,delim)
	        col == meta.cols && write(out_file,"\n")
		end
	end
	close(out_file)
	return DataFrame()
end
#ODBCFreeStmt!: used to 'clear' a statement of bound columns, resultsets, and other bound parameters in preparation for a subsequent query
function ODBCFreeStmt!(stmt)
	SQLFreeStmt(stmt,SQL_CLOSE)
	SQLFreeStmt(stmt,SQL_UNBIND)
	SQLFreeStmt(stmt,SQL_RESET_PARAMS)
end
#Error Reporting: Takes an SQL handle as input and retrieves any error messages associated with that handle; there may be more than one
function ODBCError(handletype::Int16,handle::Ptr{Void})
	i = int16(1)
	state = zeros(Uint8,6)
	error_msg = zeros(Uint8, 1024)
	native = Array(Int,1)
	msg_length = zeros(Int16,1)
	while @SUCCEEDED SQLGetDiagRec(handletype,handle,i,state,native,error_msg,msg_length)
		st = ODBCClean(state,1,5)
		msg = ODBCClean(error_msg,1,msg_length[1])
		println("[ODBC] $st: $msg")
		i = int16(i+1)
	end
end


text:
"""
    struct GridPortion{Dc,Dp,G} <: Grid{Dc,Dp}
      parent::G
      cell_to_parent_cell::Vector{Int32}
      node_to_parent_node::Vector{Int32}
    end
"""
struct GridPortion{Dc,Dp,G} <: Grid{Dc,Dp}
  parent::G
  cell_to_parent_cell::Vector{Int32}
  node_to_parent_node::Vector{Int32}
  cell_to_nodes::Table{Int32,Vector{Int32},Vector{Int32}}
  @doc """
      GridPortion(parent::Grid{Dc,Dp},cell_to_parent_cell::Vector{Int32}) where {Dc,Dp}
  """
  function GridPortion(parent::Grid,cell_to_parent_cell::AbstractVector{<:Integer})

    Dc = num_cell_dims(parent)
    Dp = num_point_dims(parent)

    parent_cell_to_parent_nodes = get_cell_node_ids(parent)
    nparent_nodes = num_nodes(parent)
    parent_node_to_coords = get_node_coordinates(parent)

    node_to_parent_node, parent_node_to_node = _find_active_nodes(
      parent_cell_to_parent_nodes,cell_to_parent_cell,nparent_nodes)

    cell_to_nodes = _renumber_cell_nodes(
      parent_cell_to_parent_nodes,parent_node_to_node,cell_to_parent_cell)

    new{Dc,Dp,typeof(parent)}(parent,cell_to_parent_cell,node_to_parent_node,cell_to_nodes)
  end
end

function GridPortion(parent::Grid,parent_cell_to_mask::AbstractArray{Bool})
  cell_to_parent_cell = findall(collect1d(parent_cell_to_mask))
  GridPortion(parent,cell_to_parent_cell)
end

function GridPortion(parent::Grid,parent_cell_to_mask::AbstractVector{Bool})
  cell_to_parent_cell = findall(parent_cell_to_mask)
  GridPortion(parent,cell_to_parent_cell)
end

function OrientationStyle(::Type{GridPortion{Dc,Dp,G}}) where {Dc,Dp,G}
  OrientationStyle(G)
end

function RegularityStyle(::Type{GridPortion{Dc,Dp,G}}) where {Dc,Dp,G}
  RegularityStyle(G)
end

function get_node_coordinates(grid::GridPortion)
  parent_node_to_coords = get_node_coordinates(grid.parent)
  lazy_map(Reindex(parent_node_to_coords),grid.node_to_parent_node)
end

function get_cell_node_ids(grid::GridPortion)
  grid.cell_to_nodes
end

function get_reffes(grid::GridPortion)
  get_reffes(grid.parent)
end

function get_cell_type(grid::GridPortion)
  lazy_map(Reindex(get_cell_type(grid.parent)),grid.cell_to_parent_cell)
end

function get_facet_normal(grid::GridPortion)
  lazy_map(Reindex(get_facet_normal(grid.parent)),grid.cell_to_parent_cell)
end

# The following are not strictly needed, sine there is a default implementation for them.
# In any case, we delegate just in case the underlying grid defines more performant versions
function get_cell_coordinates(grid::GridPortion)
  lazy_map(Reindex(get_cell_coordinates(grid.parent)),grid.cell_to_parent_cell)
end
function get_cell_ref_coordinates(grid::GridPortion)
  lazy_map(Reindex(get_cell_ref_coordinates(grid.parent)),grid.cell_to_parent_cell)
end
function get_cell_shapefuns(grid::GridPortion)
  lazy_map(Reindex(get_cell_shapefuns(grid.parent)),grid.cell_to_parent_cell)
end
function get_cell_map(grid::GridPortion)
  lazy_map(Reindex(get_cell_map(grid.parent)),grid.cell_to_parent_cell)
end
function get_cell_reffe(grid::GridPortion)
  lazy_map(Reindex(get_cell_reffe(grid.parent)),grid.cell_to_parent_cell)
end

# Helpers

function _find_active_nodes(oldcell_to_oldnodes,cell_to_oldcell,noldnodes)
  oldnode_is_active = fill(false,noldnodes)
  cache = array_cache(oldcell_to_oldnodes)
  for oldcell in cell_to_oldcell
    oldnodes = getindex!(cache,oldcell_to_oldnodes,oldcell)
    for oldnode in oldnodes
      oldnode_is_active[oldnode] = true
    end
  end
  node_to_oldnode = findall(oldnode_is_active)
  oldnode_to_node = fill(UNSET,noldnodes)
  oldnode_to_node[node_to_oldnode] = 1:length(node_to_oldnode)
  (node_to_oldnode, oldnode_to_node)
end

function _renumber_cell_nodes(oldcell_to_oldnodes,oldnode_to_node,cell_to_oldcell)
  ncells = length(cell_to_oldcell)
  cell_to_nodes_ptrs = zeros(Int32,ncells+1)
  cache = array_cache(oldcell_to_oldnodes)
  for (cell,oldcell) in enumerate(cell_to_oldcell)
    oldnodes = getindex!(cache,oldcell_to_oldnodes,oldcell)
    cell_to_nodes_ptrs[cell+1] = length(oldnodes)
  end
  length_to_ptrs!(cell_to_nodes_ptrs)
  ndata = cell_to_nodes_ptrs[end]-1
  cell_to_nodes_data = zeros(Int32,ndata)
  for (cell,oldcell) in enumerate(cell_to_oldcell)
    oldnodes = getindex!(cache,oldcell_to_oldnodes,oldcell)
    a = cell_to_nodes_ptrs[cell]-1
    for (lnode,oldnode) in enumerate(oldnodes)
      node = oldnode_to_node[oldnode]
      @assert node > 0
      cell_to_nodes_data[a+lnode] = node
    end
  end
  Table(cell_to_nodes_data,cell_to_nodes_ptrs)
end

# In contrast to GridPortion, this one only renumbers cells (not nodes)
# and its creation does not allocate memory proportional to number of cells
struct GridView{Dc,Dp,A,B} <: Grid{Dc,Dp}
  parent::A
  cell_to_parent_cell::B
  function GridView(parent::Grid,cell_to_parent_cell::AbstractArray)
    Dc = num_cell_dims(parent)
    Dp = num_point_dims(parent)
    A = typeof(parent)
    B = typeof(cell_to_parent_cell)
    new{Dc,Dp,A,B}(parent,cell_to_parent_cell)
  end
end

Base.view(a::Grid,b::AbstractArray) = GridView(a,b)

function GridView(parent::Grid,parent_cell_to_mask::AbstractArray{Bool})
  cell_to_parent_cell = findall(collect1d(parent_cell_to_mask))
  GridView(parent,cell_to_parent_cell)
end

function GridView(parent::Grid,parent_cell_to_mask::AbstractVector{Bool})
  cell_to_parent_cell = findall(parent_cell_to_mask)
  GridView(parent,cell_to_parent_cell)
end

function OrientationStyle(::Type{GridView{Dc,Dp,G}}) where {Dc,Dp,G}
  OrientationStyle(G)
end

function RegularityStyle(::Type{GridView{Dc,Dp,G}}) where {Dc,Dp,G}
  RegularityStyle(G)
end

function get_node_coordinates(grid::GridView)
  get_node_coordinates(grid.parent)
end

function get_cell_node_ids(grid::GridView)
  lazy_map(Reindex(get_cell_node_ids(grid.parent)),grid.cell_to_parent_cell)
end

function get_reffes(grid::GridView)
  get_reffes(grid.parent)
end

function get_cell_type(grid::GridView)
  lazy_map(Reindex(get_cell_type(grid.parent)),grid.cell_to_parent_cell)
end

function get_cell_map(grid::GridView)
  lazy_map(Reindex(get_cell_map(grid.parent)),grid.cell_to_parent_cell)
end

function get_facet_normal(grid::GridView)
  lazy_map(Reindex(get_facet_normal(grid.parent)),grid.cell_to_parent_cell)
end


text:
using EconFunctions
using ContinuousTransformations
using Base.Test
using Compat: ∘
import ForwardDiff.derivative

@testset "quadrature general" begin
    @test_throws ArgumentError Quadrature(1..2, collect(1:3), collect(1:4))
end

@testset "normal quadrature" begin
    q = quadrature_standard_normal(10)
    @test sprint(show, q) == "Quadrature of 10 nodes on " * sprint(show, ℝ)
    @test length(q) == 10
    @test domain(q) == ℝ
    @test q(one) ≈ 1
    @test isapprox(q(identity), 0, atol=eps()) # FIXME replace with new test syntax
    @test q(x->x^2) ≈ 1
    μ = 2.0
    σ = 3.0
    a = Affine(σ, μ)
    @test q(a) ≈ μ
    @test q((x->x^2) ∘ a) ≈ μ^2 + σ^2
end

@testset "uniform quadrature" begin
    q = quadrature_standard_uniform(9)
    @test sprint(show, q) == "Quadrature of 9 nodes on " * sprint(show, 𝕀)
    @test length(q) == 9
    @test domain(q) == 𝕀
    @test q(one) ≈ 1
    @test q(identity) ≈ 0.5
    @test q(x->(x-0.5)^2) ≈ 1/12
end

@testset "CRRA utility" begin
    u = CrraUtility(2.0)
    @test u(0) == -Inf
    @test u(1) < u(2)
    @test derivative(u, 3) ≈ abs(crra_u′(2.0)(3))
    c = 2.0
    σ = 3.1
    @test derivative(σ -> CrraUtility(σ)(c), σ) ≈
        derivative(σ -> (c^(1-σ)-1)/(1-σ), σ)
end


text:
import GRAYTR.Ray

@testset "Rays" begin
    origin = Point3(0,0,0)
    direction = Vector3(1.0, 0.0, 0.0)
    @testset "Creation" begin
        R = Ray(origin, direction)
        @test R.origin === origin
        @test R.direction === direction
        @test R.tmin ≈ 0
        @test R.tmax == Inf
        @test R.depth == 1
    end
    @testset "Ray extension" begin
        R = Ray(origin, direction)
        R(1.0) ≈ Point3(1, 0, 0)
        R(-1.0) ≈ Point3(-1, 0, 0)
        R = Ray(origin, Vector3(2.0, -1.0, 0.0))
        R(2.0) ≈ Point3(4.0, -2.0, 0.0)
    end
end

max_stars_repo_name: dronir/GRAYTR

max_issues_repo_name: dronir/GRAYTR

max_forks_repo_name: dronir/GRAYTR


text:
#! /usr/bin/env julia

println("Start test 'tests/loadmodel.jl'")

include("../src/DCellC.jl")
using DCellC

model = UNetLike(GreyscaleImage, bn = true)

println("Test loadmodel.jl: Created model successfully")

mname = tempname()
modelsave(mname, model)

println("Test loadmodel.jl: Saved model successfully")

model2 = modelload(mname)

@assert weights(model) == weights(model2)
#@assert state(model) == state(model2)

println("Test loadmodel.jl: Loaded model sucessfully")
println("Test loadmodel.jl completed")

max_stars_repo_name: tscode/DCellC

max_issues_repo_name: tscode/DCellC


text:
using Random
using Statistics
import EchelleCCFs

@testset "CCF" begin

@testset "Testing function definitions" begin
    @test isdefined(GRASS, :calc_ccf)
    @test isdefined(GRASS, :calc_rvs_from_ccf)
    @test isdefined(EchelleCCFs, :calc_doppler_factor)
end

@testset "Testing velocity injection/extraction" begin
    # get line centers
    vel = 0.5 .* sin.(range(0, 2π, length=50)) # 50 m/s sin curve
    ΔλD = EchelleCCFs.calc_doppler_factor.(vel)
    λvs = ΔλD .* 5434.5

    # measure velocities for each Doppler shifted line
    res = 1e6
    xs = range(5433.0, 5436.0, step=5434.5/res)
    ccfs = []
    v_grid = []
    for i in eachindex(λvs)
        ys = GRASS.gaussian_line.(xs, mid=λvs[i], width=0.1, depth=1.0)
        v_grid, ccf = calc_ccf(xs, ys, [5434.5], [1.0], res, normalize=true)
        push!(ccfs, ccf)
    end
    ccfs = cat(ccfs..., dims=2)
    rvs, sigs = GRASS.calc_rvs_from_ccf(v_grid, ccfs)
    delta = vel .- rvs

    # now actually test
    @test maximum(delta) < 0.1 # 0.1 m/s = 10 cm/s
end

end

max_stars_repo_name: palumbom/GRASS

max_issues_repo_name: palumbom/GRASS

max_forks_repo_name: palumbom/GRASS


text:
"""
    pretty_print_results

Print the results of functions like `today`.
"""
function pretty_print_results(now, tracks, legend, highlighting, tables, highlighters)
    header = (["Time", "Title", "Type", "Speaker"],)
    header_crayon = crayon"dark_gray bold"
    border_crayon = crayon"dark_gray"
    h_times = Highlighter((data, i, j) -> j == 1, crayon"white bold")

    println()
    println(Dates.format(TimeZones.Date(now), "E d U Y"))

    for j in eachindex(tracks)
        track = tracks[j]
        data = tables[j]
        h_running = highlighters[j]
        println()
        pretty_table(
            data;
            title=track,
            title_crayon=Crayon(; foreground=_track2color(track), bold=true),
            header=header,
            header_crayon=header_crayon,
            border_crayon=border_crayon,
            highlighters=(h_times, h_running),
            tf=tf_unicode_rounded,
            alignment=[:c, :l, :c, :l],
        )
    end

    if legend
        print_legend(highlighting)
    end

    return nothing
end

"""
    results_to_string

Put the results of functions like `today` to a string.
"""
function results_to_string(now, tracks, legend, highlighting, tables, highlighters)
    header = (["Time", "Title", "Type", "Speaker"],)
    header_crayon = crayon"dark_gray bold"
    border_crayon = crayon"dark_gray"
    h_times = Highlighter((data, i, j) -> j == 1, crayon"white bold")

    strings = Vector{String}()
    push!(strings, string(Dates.format(TimeZones.Date(now), "E d U Y")))
    for j in eachindex(tracks)
        track = tracks[j]
        data = tables[j]
        h_running = highlighters[j]
        str = pretty_table(
            String,
            data;
            title=track,
            title_crayon=Crayon(; foreground=_track2color(track), bold=true),
            header=header,
            header_crayon=header_crayon,
            border_crayon=border_crayon,
            highlighters=(h_times, h_running),
            tf=tf_unicode_rounded,
            alignment=[:c, :l, :c, :l],
        )
        push!(strings, str)
    end

    legend = if highlighting
        """
        Currently running talks are prefixed by a '>'.

        """
    else
        ""
    end

    legend *= """
    $(JuliaCon.abbrev(JuliaCon.Talk)) = Talk, $(JuliaCon.abbrev(JuliaCon.LightningTalk)) = Lightning Talk, $(JuliaCon.abbrev(JuliaCon.SponsorTalk)) = Sponsor Talk, $(JuliaCon.abbrev(JuliaCon.Keynote)) = Keynote,
    $(JuliaCon.abbrev(JuliaCon.Workshop)) = Workshop, $(JuliaCon.abbrev(JuliaCon.Minisymposium)) = Minisymposium, $(JuliaCon.abbrev(JuliaCon.BoF)) = Birds of Feather,
    $(JuliaCon.abbrev(JuliaCon.Experience)) = Experience, $(JuliaCon.abbrev(JuliaCon.VirtualPoster)) = Virtual Poster, $(JuliaCon.abbrev(JuliaCon.SocialHour)) = Social Hour

    Check out $(CONFERENCE_SCHEDULE_URL) for more information.
    """
    push!(strings, legend)
    return strings
end


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

@doc raw"""TypedLocalObjectReference contains enough information to let you locate the typed referenced object inside the same namespace.

    IoK8sApiCoreV1TypedLocalObjectReference(;
        apiGroup=nothing,
        kind=nothing,
        name=nothing,
    )

    - apiGroup::String : APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.
    - kind::String : Kind is the type of resource being referenced
    - name::String : Name is the name of resource being referenced
"""
mutable struct IoK8sApiCoreV1TypedLocalObjectReference <: SwaggerModel
    apiGroup::Any # spec type: Union{ Nothing, String } # spec name: apiGroup
    kind::Any # spec type: Union{ Nothing, String } # spec name: kind
    name::Any # spec type: Union{ Nothing, String } # spec name: name

    function IoK8sApiCoreV1TypedLocalObjectReference(;apiGroup=nothing, kind=nothing, name=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1TypedLocalObjectReference, Symbol("apiGroup"), apiGroup)
        setfield!(o, Symbol("apiGroup"), apiGroup)
        validate_property(IoK8sApiCoreV1TypedLocalObjectReference, Symbol("kind"), kind)
        setfield!(o, Symbol("kind"), kind)
        validate_property(IoK8sApiCoreV1TypedLocalObjectReference, Symbol("name"), name)
        setfield!(o, Symbol("name"), name)
        o
    end
end # type IoK8sApiCoreV1TypedLocalObjectReference

const _property_map_IoK8sApiCoreV1TypedLocalObjectReference = Dict{Symbol,Symbol}(Symbol("apiGroup")=>Symbol("apiGroup"), Symbol("kind")=>Symbol("kind"), Symbol("name")=>Symbol("name"))
const _property_types_IoK8sApiCoreV1TypedLocalObjectReference = Dict{Symbol,String}(Symbol("apiGroup")=>"String", Symbol("kind")=>"String", Symbol("name")=>"String")
Base.propertynames(::Type{ IoK8sApiCoreV1TypedLocalObjectReference }) = collect(keys(_property_map_IoK8sApiCoreV1TypedLocalObjectReference))
Swagger.property_type(::Type{ IoK8sApiCoreV1TypedLocalObjectReference }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiCoreV1TypedLocalObjectReference[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1TypedLocalObjectReference }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1TypedLocalObjectReference[property_name]

function check_required(o::IoK8sApiCoreV1TypedLocalObjectReference)
    (getproperty(o, Symbol("kind")) === nothing) && (return false)
    (getproperty(o, Symbol("name")) === nothing) && (return false)
    true
end

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


text:
"""
    COVID

An agent-based approach to modeling COVID-19 outbreaks and possible intervention strategies
"""
module COVID

export
    ParameterSetting,
    run_model,
    run_evo,
    cvd_plot

using Distributed
using LinearAlgebra
using Distributions
using Distances
using DataFrames
using Random
using StatsBase
using StaticArrays
using LightGraphs
using Parameters
using Plots
using Pipe

include("COVID_FNCS.jl")
include("COVID_FLEX.jl")
include("nsga2.jl")
include("COVID_PLOT.jl")

end


text:
using Hyperscript
using Test

macro errors(expr)
    quote
        @test_throws ErrorException $expr
    end
end

macro renders(x, s)
    quote
        @test Hyperscript.render($x) == $s
    end
end

# Convenience macro for strings with embedded double-quotes
macro s_cmd(x)
    x
end

## Tags
# Can render tags
@renders m("p") "

"
# Cannot render nonempty tags
@errors m("")
# Tags can be <: AbstractString
@renders m(SubString("xspan", 2)) ""
# Tags *must* be <: AbstractString
@test_throws MethodError m(1)
@test_throws MethodError m('1')
@test_throws MethodError m(1.0)
# Tags are normalized to strip whitespace
@test m("p") == m("p")
@test m(" p ") == m("p")
@test m("\tp\t") == m("p")

## Attributes
# Can render a tag with an attribute
@renders m("p", name="value") "

"
# Can render a tag with multiple attributes
@test let x = string(m("p", a="x", b="y"))
    # Account for the two possible attribute orderings
    x == s`<p a="x" b="y"></p>` || x == s`<p b="y" a="x"></p>`
end
# Render tags with various non-string attribute values
@renders m("p", name='7') s`<p name="7"></p>`
@renders m("p", name=7) s`<p name="7"></p>`
@renders m("p", name=7.0) s`<p name="7.0"></p>`
# squishcase renders as squishcase
@renders m("p"; squishname=7.0) s`<p squishname="7.0"></p>`
# camelCase renders as kebab-case
@renders m("p"; camelName=7.0) s`<p camel-name="7.0"></p>`
# kebab-case renders as kebab-case
@renders m("p"; [Symbol("kebab-name") => 7]...) s`<p kebab-name="7"></p>`
# Can start attribute names with numbers
@renders m("p"; [Symbol("7-name") => 7]...) s`<p 7-name="7"></p>`

# Disallow NaN attribute values by default
@errors m("p", name=NaN)
# Disallow spaces in attribute names by default
@errors m("p"; [Symbol("7 space name") => 7]...)

# Passing a string as an attribute name preserves it un-normalized
@renders Hyperscript.Node(Hyperscript.DEFAULT_HTMLSVG_CONTEXT, "p", [], ["camelName" => 7.0]) s`<p camelName="7.0"></p>`

## Children
# Can render children
@renders m("p", "child") s`<p>child</p>`
# Can render multiple children
@renders m("p", "childOne", "childTwo") s`<p>childOnechildTwo</p>`

# Can render multiply-typed children
@renders m("p", "childOne", 2) s`<p>childOne2</p>`
# Can render Node children
@renders m("p", m("p")) s`<p><p></p></p>`
# Can render other non-String children
@renders m("p", 1) s`<p>1</p>`
@renders m("p", 1.0) s`<p>1.0</p>`
@renders m("p", '1') s`<p>1</p>`
# Can render nodes with mixed-type children
@renders m("p", m("span", "child", 1), 2) s`<p><span>child1</span>2</p>`
# Can render mixed-type children inside an array
@renders m("p", [m("span", "child", 1), 2]) s`<p><span>child1</span>2</p>`

## Accessors
@test Hyperscript.tag(m("p")) == "p"
@test Hyperscript.attrs(m("p", attr="value")) == Dict{String,Any}("attr" => "value")
@test Hyperscript.children(m("p", "child")) == Any["child"]

## Generators, arrays, and tuples
# Arrays are flattened
@renders m("p", [1, 2, 3]) s`<p>123</p>`
# Generators are flattened
@renders m("p", (x for x in 1:3)) s`<p>123</p>`
# Tuples are flattened
@renders m("p", (1, 2, 3)) s`<p>123</p>`
# Ranges are not flattened
@renders m("p", 1:3) s`<p>1:3</p>`

## Normalization of HTML- and SVG-specific attribute nanes
# we don't normalize tag names
@renders m("linearGradient") s`<linearGradient></linearGradient>`
@renders m("magicLinearGradient") s`<magicLinearGradient></magicLinearGradient>`
# for those special attributes we preserve camelCase
@renders m("path", pathLength=7) s`<path pathLength="7" />`
# for those special attributes we convert squishcase
@renders m("path", pathlength=7) s`<path pathLength="7" />`
# for those special attributes you can still bypass HTML normalization (but not validation)
# by sending the value in as a String
@renders Hyperscript.Node(Hyperscript.DEFAULT_HTMLSVG_CONTEXT, "path", [], ["pathlength" => 7]) s`<path pathlength="7" />`
@renders Hyperscript.Node(Hyperscript.DEFAULT_HTMLSVG_CONTEXT, "path", [], ["path-length" => 7]) s`<path path-length="7" />`

# Void tags render as void tags
@renders m("br") s`<br />`
@renders m("stop") s`<stop />`
# Void tags are not allowed to have children
@errors m("stop", "child")

# Non-void tags render as non-void tags
@renders m("div") s`<div></div>`
@renders m("span") s`<span></span>`

# @tags
@tags beep
# The @tags macro declares a tag
@renders beep("hello<") s`<beep>hello<</beep>`

# @tags_noescape
@tags_noescape boop
# The @tags_noescape macro declares a tag with unescaped children
@renders boop("hello<") s`<boop>hello<</boop>`

# escape behavior
# HTML-relevant characters are escaped
@renders m("p", "<") s`<p><</p>`
@renders m("p", "\"") s`<p>"</p>`
# Non-HTML Non-ASCII characters are not escaped; we assume a utf-8 charset
@renders m("p", "—") s`<p>—</p>`
# Regular characters are not escaped
@renders m("p", "x") s`<p>x</p>`
# Characters are escaped inside attribute names
@renders m("p", attr="<value") s`<p attr="<value"></p>`
# This is weird. Should we allow it?
# m("p"; [Symbol("<attr")=>"<value"]...)

# noescape behavior
@tags_noescape q
@renders q("<") s`<q><</q>`
@renders q("—") s`<q>—</q>`
@renders q("\"") s`<q>"</q>`
@renders q("x") s`<q>x</q>`
# Noescape does not propagate and only applies to children, not attributes.
# This is the most useful behavior — you only really want to not-escape the
# contents of e.g. of


text:
using Colors
using CoordinateTransformations
using FileIO
using GeometryBasics
using MeshCat, MeshIO, Meshing
using Rotations

function visualize!(vis, model::Particle2D, q;
	Δt = 0.1, r = 0.25)

	default_background!(vis)

    setobject!(vis["particle"],
		GeometryBasics.Sphere(GeometryBasics.Point3f0(0),
		convert(Float32, r)),
		MeshPhongMaterial(color = RGBA(13/255, 152/255, 186/255, 1.0)))

    anim = MeshCat.Animation(convert(Int, floor(1.0 / Δt)))

    for t = 1:length(q)
        MeshCat.atframe(anim, t) do
            settransform!(vis["particle"], MeshCat.Translation(q[t][1], 0.0, q[t][2]))
        end
    end

    MeshCat.setanimation!(vis, anim)
end

function plot_lines!(vis::Visualizer, model::Particle2D, q::AbstractVector;
		r=0.25, size=10, name::Symbol=:particle_2D, col::Bool=true)
	# Point Traj
	com_point = Vector{Point{3,Float64}}()

	for qi in q
		push!(com_point, Point(qi[1], 0.0, qi[2] + r))
	end

	# Set lines
	orange_mat, blue_mat, black_mat = get_line_material(size)
	if col
		setobject!(vis[name]["lines"]["com"], MeshCat.Line(com_point, orange_mat))
	else
		setobject!(vis[name]["lines"]["com"], MeshCat.Line(com_point, black_mat))
	end
	return nothing
end

function build_robot!(vis::Visualizer, model::Particle2D; name::Symbol=:Particle2D, r=0.25, α=1.0)
	nc = model.nc
	r = convert(Float32, r)
	body_mat = MeshPhongMaterial(color = RGBA(13/255, 152/255, 186/255, α))

	default_background!(vis)

    setobject!(vis[name][:robot]["particle_2D"], GeometryBasics.Rect(
		Vec(-1.0 * r, -1.0 * r, -1.0 * r),
		Vec(2.0 * r, 2.0 * r, 2.0 * r)),
		body_mat)
	return nothing
end

function set_robot!(vis::Visualizer, model::Particle2D, q::AbstractVector; name::Symbol=:Particle2D, r=0.25)
	nc = model.nc

	settransform!(vis[name][:robot]["particle_2D"], Translation(q[1], 0.0, q[2]+r))
	return nothing
end

function contact_point(model::Particle2D, q::AbstractVector; r=0.25)
	pc = [q[1], 0.0, q[2]]
	return [pc]
end


text:
"""
    bdecode(io::IO)

Bdecode the content of the IO.

# Examples
```jldoctest
julia> BitTorrent.bdecode(IOBuffer("d6:string11:hello world7:integeri42e4:listli1ei2ei3eee"))
Dict{String,Any} with 3 entries:
  "string"  => "hello world"
  "list"    => Any[1, 2, 3]
  "integer" => 42
```
"""
function bdecode(io::IO)
    c = Char(Base.peek(io)) # peek(io, Char) in Julia 1.5 and above
    if c === 'i'
        return parseint(io)
    elseif c === 'l'
        return parselist(io)
    elseif c === 'd'
        return parsedict(io)
    else
        return parsestring(io)
    end
end

function parseint(io::IO)
    @assert read(io, Char) === 'i'
    return parse(Int, readuntil(io, 'e'))
end

function parselist(io::IO)
    @assert read(io, Char) === 'l'
    r = Any[]
    while Char(Base.peek(io)) !== 'e' # peek(io, Char) !== 'e' in Julia 1.5 and above
        push!(r, bdecode(io))
    end
    @assert read(io, Char) === 'e'
    return r
end

function parsedict(io::IO)
    @assert read(io, Char) === 'd'
    r = Dict{String,Any}()
    while Char(Base.peek(io)) !== 'e' # peek(io, Char) !== 'e' in Julia 1.5 and above
        push!(r, parsestring(io) => bdecode(io))
    end
    @assert read(io, Char) === 'e'
    return r
end

function parsestring(io::IO)
    l = parse(Int, readuntil(io, ':'))
    return String(read(io, l))
end

"""
    bencode(io::IO, data)

Bencode `data` and write it to the IO.

# Examples
```jldoctest
julia> data = ["hello world", 1, 2, 3];

julia> sprint(BitTorrent.bencode, data)
"l11:hello worldi1ei2ei3ee"
```
"""
bencode(io::IO, data)

function bencode(io::IO, data::Int)
    print(io, 'i', data, 'e')
end

function bencode(io::IO, data::AbstractVector)
    print(io, 'l')
    foreach(x -> bencode(io, x), data)
    print(io, 'e')
end

function bencode(io::IO, data::AbstractDict{<:AbstractString})
    print(io, 'd')
    ks = sort(collect(keys(data)))
    foreach(x -> (bencode(io, x); bencode(io, data[x])), ks)
    print(io, 'e')
end

function bencode(io::IO, data::AbstractString)
    print(io, sizeof(data), ':', data)
end


text:
using Text, Stage, Ollam
using DataStructures

const url_pattern     = r"http://[^\s]*"
const hashtag_pattern = r"^#.*$"
const mention_pattern = r"^@.*$"

function clean_tweet(tw)
  w = replace(strip(tw), url_pattern, "--url--")
  while true
    x = replace_html_entities(w)
    if x != w
      w = x
    else
      break
    end
  end
  if ismatch(r".*>.*", w)
    println("w: $w")
    exit(1)
  end
  return w
end

# -------------------------------------------------------------------------------------------------------------------------
# Twitter LID
# -------------------------------------------------------------------------------------------------------------------------
xsection = DefaultDict(String, Vector{String}, () -> (String)[])

for (class, text) in lazy_map(ln -> split(ln, '\t'), filelines("filtered.txt"))
  if text != "" && text != "--url--"
    push!(xsection[class], strip(text))
  end
end

total = 0
for k in keys(xsection)
  @info @sprintf("%-30s %10d", k, length(xsection[k]))
  total += length(xsection[k])
end
@sep
@info @sprintf("%-30s %10d", "total", total)

train       = vcat([ map(fvt -> fvt, xsection[k][1:min(end-600, 65000)]) for k in keys(xsection) ]...)
train_truth = vcat([ map(fvt -> k,   xsection[k][1:min(end-600, 65000)]) for k in keys(xsection) ]...)
test        = vcat([ map(fvt -> fvt, xsection[k][min(end-600, int(end*0.95)):end]) for k in keys(xsection) ]...)
test_truth  = vcat([ map(fvt -> k,   xsection[k][min(end-600, int(end*0.95)):end]) for k in keys(xsection) ]...)
@info "size of train: $(length(train)), size of test: $(length(test))"

bkgmodel, fextractor, model = tc_train(train, train_truth, lid_iterating_tokenizer, mincount = 2, cutoff = 1e10,
                                       trainer = (fvs, truth, init_model) -> train_mira(fvs, truth, init_model, iterations = 20, k = 12, C = 0.01, average = true),
                                       iteration_method = :eager)

confmat = DefaultDict(String, DefaultDict{String, Int32}, () -> DefaultDict(String, Int32, 0))
res     = test_classification(model, lazy_map(x -> fextractor(lid_iterating_tokenizer(x)), test), test_truth, record = (t, h) -> confmat[t][h] += 1) * 100.0
@info @sprintf("mira test set error rate: %7.3f", res)
print_confusion_matrix(confmat)

# List specific errors
for (text, t) in zip(test, test_truth)
  fv      = fextractor(lid_iterating_tokenizer(text))
  scores  = score(model, fv)
  bidx, b = best(scores)
  if model.index_class[bidx] != t
    @debug "ERROR: (ref: $t, hyp: $(model.index_class[bidx])) $text"
  end
end

# save the model
f = open("flt-model", "w")
serialize(f, bkgmodel)
serialize(f, fextractor)
serialize(f, model)
close(f)


text:
module Magic

import Util

function initSlidersAttack(is_bishop)
    attacks = Array{Dict}(undef,64)
    for i in 1:64
        attacks[i] = Dict()
    end
    println("INITIALIZING SLIDER MOVES",is_bishop)
    for sq in 1:64
        attack_mask = (is_bishop) ? bMask(sq) : rMask(sq)
        relevant_bits_count = count_ones(attack_mask)
        occupancy_indicies = (1 << relevant_bits_count)
        for index in 0:occupancy_indicies-1
            if(is_bishop)
                occ = UInt128(setOcc(index,relevant_bits_count,attack_mask))
                magic_index = (occ * bishop_magic_numbers[sq]) >> (64 - n_b_bits[sq])
                attacks[sq][magic_index] = bishopAttacksOnTheFly(occ,sq)
            else
                occ = UInt128(setOcc(index,relevant_bits_count,attack_mask))
                magic_index = (occ * rook_magic_numbers[sq]) >> (64 - n_r_bits[sq])
                attacks[sq][magic_index] = rookAttacksOnTheFly(occ,sq)

            end
        end
    end
    return attacks
end

function bishopAttacksOnTheFly(occ,sq)
    if(sq < 1)
        return false
    end
    attacks = UInt64(0)
    piece_rank = (sq == 0) ? 0 : ceil(Int64,sq / 8 - 1)
    piece_file = (sq % 8) - 1
    piece_file = ((sq % 8) == 0) ? 7 : piece_file
    piece_rank = (piece_rank == 8) ? 7 : piece_rank

    rank = piece_rank + 1
    file = piece_file + 1
    while(rank < 8 && file < 8)
        attacks |= (1 << ((rank * 8) + file))
        if((1 << ((rank * 8) + file)) & occ > 0) break end
        file = file + 1
        rank = rank + 1
    end

    rank = piece_rank + 1
    file = piece_file - 1
    while(rank < 8 && file >= 0)
        attacks |= (1 << ((rank * 8) + file))
        if((1 << ((rank * 8) + file)) & occ > 0) break end
        file = file - 1
        rank = rank + 1
    end

    rank = piece_rank - 1
    file = piece_file + 1
    while(rank >= 0 && file < 8)
        attacks |= (1 << ((rank * 8) + file))
        if((1 << ((rank * 8) + file)) & occ > 0) break end
        file = file + 1
        rank = rank - 1
    end

    rank = piece_rank - 1
    file = piece_file - 1
    while(rank >= 0 && file >= 0)
        attacks |= (1 << ((rank * 8) + file))
        if((1 << ((rank * 8) + file)) & occ > 0 ) break end
        file = file - 1
        rank = rank - 1
    end
    return attacks
end

function rookAttacksOnTheFly(occ,sq)
    if(sq < 1)
        return false
    end
    attacks = UInt64(0)
    piece_rank = ceil(Int64,sq / 8 - 1)
    piece_file = (sq % 8) - 1
    piece_file = ((sq % 8) == 0) ? 7 : piece_file
    piece_rank = (piece_rank == 8) ? 7 : piece_rank
    #ranks above
    for rank in (piece_rank+1):7
        attacks |= (1 << (rank * 8 + piece_file))
        if ((1 << (rank * 8 + piece_file)) & occ > 0) break end
    end

    #ranks below
    rank = piece_rank - 1
    while(rank >= 0)
        attacks |= (1 << ((rank * 8) + piece_file))
        if ((1 << (rank * 8 + piece_file)) & occ > 0 ) break end
        rank = rank - 1
    end

    #files to the right
    for file in (piece_file+1):7
        attacks |= (1 << ((piece_rank * 8) + file))
        if ((1 << (piece_rank * 8 + file)) & occ > 0 ) break end
    end

    #files to the left
    file = piece_file - 1
    while(file >= 0)
        attacks |= (1 << (piece_rank * 8 + file))
        if ((1 << (piece_rank * 8 + file)) & occ > 0 ) break end
        file = file - 1
    end

    return attacks
end

n_r_bits =  [
	12, 11, 11, 11, 11, 11, 11, 12,
	11, 10, 10, 10, 10, 10, 10, 11,
	11, 10, 10, 10, 10, 10, 10, 11,
	11, 10, 10, 10, 10, 10, 10, 11,
	11, 10, 10, 10, 10, 10, 10, 11,
	11, 10, 10, 10, 10, 10, 10, 11,
	11, 10, 10, 10, 10, 10, 10, 11,
	12, 11, 11, 11, 11, 11, 11, 12
]

n_b_bits = [
	6, 5, 5, 5, 5, 5, 5, 6,
	5, 5, 5, 5, 5, 5, 5, 5,
	5, 5, 7, 7, 7, 7, 5, 5,
	5, 5, 7, 9, 9, 7, 5, 5,
	5, 5, 7, 9, 9, 7, 5, 5,
	5, 5, 7, 7, 7, 7, 5, 5,
	5, 5, 5, 5, 5, 5, 5, 5,
	6, 5, 5, 5, 5, 5, 5, 6
]

function rMask(sq)

    result = 0
    rank = ceil(Int64,sq / 8 - 1)
    file = sq % 8 - 1
    file = ((sq % 8 ) == 0) ? 7 : file
    rank = rank == 8 ? 7 : rank
    for index in rank+1:6
        result |= (1 << (file + (index * 8)))
    end
    index = rank - 1
    while index >= 1
        result |= (1 << (file + (index * 8)))
        index = index - 1
    end

    for index in file+1:6
        result |= (1 << (index + (rank * 8)))
    end

    index = file - 1
    while index >= 1 && index <= 64
        result |= (1 << (index + (rank * 8)))
        index = index - 1
    end
    return result

end

function bMask(sq)
    result = 0
    rank = ceil(UInt64,sq / 8 - 1)
    file = sq % 8 - 1
    file = ((sq % 8) == 0) ? 7 : file
    rank = rank == 8 ? 7 : rank
    # println(file, ' ', rank)
    r = rank + 1
    f = file + 1
    while(r < 7 && f < 7)
        result |= (1 << (f + (r * 8)))
        r = r + 1
        f = f + 1
    end

    r = rank + 1
    f = file - 1
    while(r < 7 && f >= 1)
        result |= (1 << (f + (r * 8)))
        r = r + 1
        f = f - 1
    end

    r = rank - 1
    f = file + 1
    while(r >= 1 && f < 7)
        result |= (1 << (f + (r * 8)))
        r = r - 1
        f = f + 1
    end

    r = rank - 1
    f = file - 1
    while(r >= 1 && f >= 1)
        result |= (1 << (f + (r * 8)))
        r = r - 1
        f = f - 1
    end
    return result
end

# https://www.chessprogramming.org/Looking_for_Magics

rook_magic_numbers = [
    0x8a80104000800020,
    0x140002000100040,
    0x2801880a0017001,
    0x100081001000420,
    0x200020010080420,
    0x3001c0002010008,
    0x8480008002000100,
    0x2080088004402900,
    0x800098204000,
    0x2024401000200040,
    0x100802000801000,
    0x120800800801000,
    0x208808088000400,
    0x2802200800400,
    0x2200800100020080,
    0x801000060821100,
    0x80044006422000,
    0x100808020004000,
    0x12108a0010204200,
    0x140848010000802,
    0x481828014002800,
    0x8094004002004100,
    0x4010040010010802,
    0x20008806104,
    0x100400080208000,
    0x2040002120081000,
    0x21200680100081,
    0x20100080080080,
    0x2000a00200410,
    0x20080800400,
    0x80088400100102,
    0x80004600042881,
    0x4040008040800020,
    0x440003000200801,
    0x4200011004500,
    0x188020010100100,
    0x14800401802800,
    0x2080040080800200,
    0x124080204001001,
    0x200046502000484,
    0x480400080088020,
    0x1000422010034000,
    0x30200100110040,
    0x100021010009,
    0x2002080100110004,
    0x202008004008002,
    0x20020004010100,
    0x2048440040820001,
    0x101002200408200,
    0x40802000401080,
    0x4008142004410100,
    0x2060820c0120200,
    0x1001004080100,
    0x20c020080040080,
    0x2935610830022400,
    0x44440041009200,
    0x280001040802101,
    0x2100190040002085,
    0x80c0084100102001,
    0x4024081001000421,
    0x20030a0244872,
    0x12001008414402,
    0x2006104900a0804,
    0x1004081002402
];

bishop_magic_numbers = [
    0x40040844404084,
    0x2004208a004208,
    0x10190041080202,
    0x108060845042010,
    0x581104180800210,
    0x2112080446200010,
    0x1080820820060210,
    0x3c0808410220200,
    0x4050404440404,
    0x21001420088,
    0x24d0080801082102,
    0x1020a0a020400,
    0x40308200402,
    0x4011002100800,
    0x401484104104005,
    0x801010402020200,
    0x400210c3880100,
    0x404022024108200,
    0x810018200204102,
    0x4002801a02003,
    0x85040820080400,
    0x810102c808880400,
    0xe900410884800,
    0x8002020480840102,
    0x220200865090201,
    0x2010100a02021202,
    0x152048408022401,
    0x20080002081110,
    0x4001001021004000,
    0x800040400a011002,
    0xe4004081011002,
    0x1c004001012080,
    0x8004200962a00220,
    0x8422100208500202,
    0x2000402200300c08,
    0x8646020080080080,
    0x80020a0200100808,
    0x2010004880111000,
    0x623000a080011400,
    0x42008c0340209202,
    0x209188240001000,
    0x400408a884001800,
    0x110400a6080400,
    0x1840060a44020800,
    0x90080104000041,
    0x201011000808101,
    0x1a2208080504f080,
    0x8012020600211212,
    0x500861011240000,
    0x180806108200800,
    0x4000020e01040044,
    0x300000261044000a,
    0x802241102020002,
    0x20906061210001,
    0x5a84841004010310,
    0x4010801011c04,
    0xa010109502200,
    0x4a02012000,
    0x500201010098b028,
    0x8040002811040900,
    0x28000010020204,
    0x6000020202d0240,
    0x8918844842082200,
    0x4010011029020020
];

function setOcc(index,bits_in_mask,attack_mask)
    # println(index, ' ',bits_in_mask, ' ', attack_mask)
    temp_occ = 0
    for count in 0:bits_in_mask-1
        square = Util.leastSignificantBit(attack_mask)
        attack_mask = Util.popBit(attack_mask,square)
        if((index & (1 << count)) > 0)
            temp_occ |= (1 << square)
        end
        #  println(count, ' ', square, ' ', attack_mask, ' ',temp_occ)
    end
    return temp_occ
end

end

max_stars_repo_name: grahamclyne/chessEngine

max_issues_repo_name: grahamclyne/chessEngine

max_forks_repo_name: grahamclyne/chessEngine


text:
r = @theory begin
    foo(x,y) => 2*x%y
    foo(x,y) => sin(x)
    sin(x) => foo(x,x)
end
@testset "Basic Equalities 1" begin
    @test (@areequal r foo(b,c) foo(d,d)) == false
end

r = @theory begin
    a * 1 => foo
    a * 2 => bar
    1 * a => baz
    2 * a => mag
end
@testset "Matching Literals" begin
    @test (@areequal r a * 1 foo) == true
    @test (@areequal r a * 2 foo) == false
    @test (@areequal r a * 1 bar) == false
    @test (@areequal r a * 2 bar) == true

    @test (@areequal r 1 * a baz) == true
    @test (@areequal r 2 * a baz) == false
    @test (@areequal r 1 * a mag) == false
    @test (@areequal r 2 * a mag) == true
end

comm_monoid = @commutative_monoid (*) 1
@testset "Basic Equalities - Commutative Monoid" begin
    @test true == (@areequal comm_monoid a*(c*(1*d)) c*(1*(d*a)) )
    @test true == (@areequal comm_monoid x*y y*x )
    @test true == (@areequal comm_monoid (x*x)*(x * 1) x*(x*x) )
end

comm_group = @abelian_group (+) 0 inv
t = comm_monoid ∪ comm_group ∪ distrib(:(*), :(+))
@testset "Basic Equalities - Comm. Monoid, Abelian Group, Distributivity" begin
    @test true == (@areequal t (a * b) + (a * c) a*(b+c) )
    @test true == (@areequal t a*(c*(1*d)) c*(1*(d*a)) )
    @test true == (@areequal t a+(b*(c*d)) ((d*c)*b)+a )
    @test true == (@areequal t (x+y)*(a+b) ((a*(x+y)) + b*(x+y)) ((x*(a+b)) + y*(a+b)) )
    @test true == (@areequal t (((x*a + x*b) + y*a) + y*b) (x+y)*(a+b) )
    @test true == (@areequal t a+(b*(c*d)) ((d*c)*b)+a )
    @test true == (@areequal t a+inv(a) 0 (x*y)+inv(x*y) 1*0 )
end

@testset "Basic Equalities - False statements" begin
    @test false == (@areequal t (a * b) + (a * c) a*(b+a))
    @test false == (@areequal t (a * c) + (a * c) a*(b+c) )
    @test false == (@areequal t a*(c*c) c*(1*(d*a)) )
    @test false == (@areequal t c+(b*(c*d)) ((d*c)*b)+a )
    @test false == (@areequal t (x+y)*(a+c) ((a*(x+y)) + b*(x+y)) )
    @test false == (@areequal t ((x*(a+b)) + y*(a+b)) (x+y)*(a+c) )
    @test false == (@areequal t (((x*a + x*b) + y*a) + y*b) (x+y)*(a+x) )
    @test false == (@areequal t a+(b*(c*a)) ((d*c)*b)+a )
    @test false == (@areequal t a+inv(a) a )
    @test false == (@areequal t (x*y)+inv(x*y) 1 )
end

# Issue 21
simp_theory = @theory begin
    munit() => :foo
end
G = EGraph( :(munit()) )
saturate!(G, simp_theory, timeout=1)

module Bar
   foo = 42
   using Metatheory
   @metatheory_init
   export foo
end

module Foo
   foo = 12
   using Metatheory
   @metatheory_init
end

t = @theory begin
   :woo |> foo
end

g = EGraph(:woo);
saturate!(g, t; mod=Bar);
saturate!(g, t; mod=Foo);
foo = 12

@testset "Different modules" begin
    @test @areequalg g t 42 12
end

# expr = cleanast(:(1 * 1 * 1 * 1 * 1 * zoo * 1 * 1 * foo * 1))
#
# G = EGraph(expr)
#
# @time saturate!(G, comm_monoid)
#
# G.H |> display


text:
# Type Definition
@aml mutable struct Person "person", check_course
    age::UInt64, "~"
    field, "study-field"
    GPA::Float64 = 4.5, "~", GPAcheck
    courses::Vector{String}, "taken-courses"
    professors::UN{DataFrame} = nothing, "table"
    id::Int64, att"~"
    comment::UN{String} = nothing, txt"end"
end

@aml mutable struct University doc"university"
    name, att"university-name"
    people::Vector{Person}, "person"
end

# Value Checking Functions
GPAcheck(x) = x <= 4.5 && x >= 0

function check_course(age, field, GPA, courses, professors, id, comment)

    if field == "Mechanical Engineering"
        relevant = ["Artificial Intelligence", "Robotics", "Machine Design"]
    elseif field == "Computer Engineering"
        relevant = ["Julia", "Algorithms"]
    else
        error("study field is not known")
    end

    return any(in.(courses, Ref(relevant)))
end

################################################################

# parametric
@aml mutable struct MyGeneralXML{T} "~"
    myfield::T, "~"
end
pxml_string = MyGeneralXML{String}(myfield = "a")
pprint(pxml_string)
pxml_vector = MyGeneralXML{Vector{String}}(myfield = ["b","c"])
pprint(pxml_vector)

@aml mutable struct MyGeneralXML2{T} "MyGeneralXML2"
    myfield::T, "~"
end
################################################################

# empty or no aml
@aml mutable struct NoAMLFields empty"no-aml-fields"
    a, "~"
    b = 1
    c::String = 10
    d
    e::String
    f = "hey", "~"
end

function meta_check(a, b, c, d, e, f)
    return d
end

@aml mutable struct NoAMLFields2 empty"~", meta_check
    a, "~"
    b = 1
    c::String = 10
    d
    e::String
    f = "hey", "~"
end

# The method does not create keyword arguments for normal fiels
@test_throws MethodError NoAMLFields2(a="a", d=true)
@test_broken NoAMLFields2(a="a")

# TODO Should make @aml add keyword arguments on top of normal arguments

@aml mutable struct NoAMLFields3 empty"NoAMLFields3", meta_check
    a, "~"
    b = 1
    c::String = 10
    d
    e::String
    f = "hey", "~"
end


text:
using Documenter, Clustering

makedocs(
    source = "source",
    format = Documenter.HTML(prettyurls=false),
    sitename = "Clustering.jl",
    modules = [Clustering],
    pages = [
        "Introduction" => "index.md",
        "Algorithms" => [
            "algorithms.md",
            "init.md",
            "kmeans.md",
            "kmedoids.md",
            "hclust.md",
            "mcl.md",
            "affprop.md",
            "dbscan.md",
            "fuzzycmeans.md",
        ],
        "validate.md",
    ],
)

deploydocs(
    repo = "github.com/JuliaStats/Clustering.jl.git",
)


text:
module SippyArt
using WAV, Images
using Flux, Flux.Data.MNIST, Statistics
using Flux: throttle, params
using Distributions
import Distributions: logpdf
using Plots
togray(x) = Gray.(reshape(x, 3024, 3024))
tostereo(x) = reshape(x, (:, 2))

songfn = "/home/sippycups/Music/2019/81 - 9 21 19 2.wav"
wave, sr  = wavread(songfn) # 6,659,596
flatwave = reshape(wave, :)
sr = Int(sr)
println("sample rate: $(sr)")
batch_size = 1
start_sec = 0
end_sec = 23
# sec = wave[sr*start_sec:sr*end_sec - 1, :]
# flatsec = reshape(sec, :)
# out_dim = length(flatsec)
imgfn = "/home/sippycups/audio/square.jpg"
img = load(imgfn)
img_data = channelview(img) # 3, 3024, 3024 == 27,433,728
gray = Gray.(img)
gray_data = channelview(gray) # 3024, 3024 = 9,144,576 first training on gray
smaller = gray_data[988:2011, 988:2011]

gray_floats = convert(Array{Float32}, smaller)
flat_grays = reshape(gray_floats, :)
flat_gray = flat_grays[1:2000]
in_dim = 784 # length(flat_grays)
out_dim = in_dim
out_wav = flatwave[1:in_dim]

bottleneck, mid = 5, 500

# data = zip([flat_grays, out_wav])
data = Iterators.repeated(flat_gray, 1000)

logpdf(b::Bernoulli, y::Bool) = y * log(b.p + eps(Float32)) + (1f0 - y) * log(1 - b.p + eps(Float32))
A, μ, logσ = Dense(in_dim, mid, tanh), Dense(mid, bottleneck), Dense(mid, bottleneck)

# A_out = A(gray_data)
# sig_out = μ(A_out)
# logsig_out = logσ(A_out)
# g_out = g(gray_data)

g(X) = (h = A(X); (μ(h), logσ(h)))

z(μ, logσ) = μ + exp(logσ) * randn(Float32)

f = Chain(Dense(bottleneck, mid, tanh), Dense(mid, out_dim, σ))

kl_q_p(μ, logσ) = 0.5f0 * sum(exp.(2f0 .* logσ) + μ.^2 .- 1f0 .- (2 .* logσ))

logp_x_z(x, z) = sum(logpdf.(Bernoulli.(f(z)), x))

L̄(X) = ((μ̂, logσ̂) = g(X); (logp_x_z(X, z.(μ̂, logσ̂)) - kl_q_p(μ̂, logσ̂)) * 1 // batch_size)
# L̄(X, Y) = ((μ̂, logσ̂) = g(X); (logp_x_z(Y, z.(μ̂, logσ̂)) - kl_q_p(μ̂, logσ̂)) * 1 // batch_size)

loss(X) = -L̄(X) + 0.01f0 * sum(x->sum(x.^2), params(f))
# loss(X, Y) = -L̄(X, Y) + 0.0001f0 * sum(x->sum(x.^2), params(f))

modelsample() = rand.(Bernoulli.(f(z.(zeros(bottleneck), zeros(bottleneck)))))

# loss(flat_grays, flat_grays)
loss(flat_gray)
loss(out_wav)

evalcb = function ()
	throttle(() -> @show(-L̄(X[:, rand(1:N, batch_size)])), 30)
end

opt = ADAM()
ps = params(A, μ, logσ, f)

Flux.train!(loss, ps, data, opt, cb=evalcb)

# s = randn((88200, 2))
# a = randn((88200, 2))
# s /= maximum(s).^ 2
# vcat(a, s)
# wavwrite(s, "jltest.wav", Fs=44100)

end # module

max_stars_repo_name: anandijain/audio

max_issues_repo_name: anandijain/audio

max_forks_repo_name: anandijain/audio


text:
using Caesar;
using Caesar.ZmqCaesar;
fg = initfg();
config = Dict{String, String}();
zmqConfig = ZmqServer(fg, config, true, "tcp://*:5555");
start(zmqConfig)


text:
using JuMP
function test_jump_sdp(solver)
    @testset "Semidefinite Programming" begin
        @testset "SDP1" begin
            # Problem SDP1 - sdo1 from MOSEK docs
            # From Mosek.jl/test/mathprogtestextra.jl, under license:
            #   Copyright (c) 2013 Ulf Worsoe, Mosek ApS
            #   Permission is hereby granted, free of charge, to any person obtaining a copy of this
            #   software and associated documentation files (the "Software"), to deal in the Software
            #   without restriction, including without limitation the rights to use, copy, modify, merge,
            #   publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
            #   to whom the Software is furnished to do so, subject to the following conditions:
            #   The above copyright notice and this permission notice shall be included in all copies or
            #   substantial portions of the Software.
            #
            #     | 2 1 0 |
            # min | 1 2 1 | . X + x1
            #     | 0 1 2 |
            #
            #
            # s.t. | 1 0 0 |
            #      | 0 1 0 | . X + x1 = 1
            #      | 0 0 1 |
            #
            #      | 1 1 1 |
            #      | 1 1 1 | . X + x2 + x3 = 1/2
            #      | 1 1 1 |
            #
            #      (x1,x2,x3) in C^3_q
            #      X in C_sdp

            m = Model(solver=solver)

            @variable(m, x[1:3])
            @constraint(m, x in MOI.SecondOrderCone(3))
            @variable(m, X[1:3, 1:3], PSD)

            C = [2 1 0
                 1 2 1
                 0 1 2]
            A1 = [1 0 0
                  0 1 0
                  0 0 1]
            A2 = [1 1 1
                  1 1 1
                  1 1 1]

            @objective(m, Min, vecdot(C, X) + x[1])

            @constraint(m, vecdot(A1, X) + x[1] == 1)
            @constraint(m, vecdot(A2, X) + x[2] + x[3] == 1/2)

            JuMP.solve(m)

            @test JuMP.isattached(m)
            @test JuMP.hasvariableresult(m)
            @test JuMP.terminationstatus(m) == MOI.Success
            @test JuMP.primalstatus(m) == MOI.FeasiblePoint

            @test JuMP.objectivevalue(m) ≈ 0.705710509 atol=1e-6

            xv = JuMP.resultvalue.(x)
            Xv = JuMP.resultvalue.(X)
            @test vecdot(C, Xv) + xv[1] ≈ 0.705710509 atol=1e-6

            @test eigmin(Xv) > -1e-6
        end

        @testset "Nonsensical SDPs" begin
            m = Model()
            @test_throws ErrorException @variable(m, unequal[1:5,1:6], PSD)
            # Some of these errors happen at compile time, so we can't use @test_throws
            @test macroexpand(:(@variable(m, notone[1:5,2:6], PSD))).head == :error
            @test macroexpand(:(@variable(m, oneD[1:5], PSD))).head == :error
            @test macroexpand(:(@variable(m, threeD[1:5,1:5,1:5], PSD))).head == :error
            @test macroexpand(:(@variable(m, psd[2] <= rand(2,2), PSD))).head == :error
            @test macroexpand(:(@variable(m, -ones(3,4) <= foo[1:4,1:4] <= ones(4,4), PSD))).head == :error
            @test macroexpand(:(@variable(m, -ones(3,4) <= foo[1:4,1:4] <= ones(4,4), Symmetric))).head == :error
            @test macroexpand(:(@variable(m, -ones(4,4) <= foo[1:4,1:4] <= ones(4,5), Symmetric))).head == :error
            @test macroexpand(:(@variable(m, -rand(5,5) <= nonsymmetric[1:5,1:5] <= rand(5,5), Symmetric))).head == :error
        end

        # min o                    max y + X11
        # Q11 - 1   = Q22        [y-X12-X21  0     [0 0
        #                             0     -y] <=  0 0]
        # [1   Q11
        #  Q11 o  ] >= 0          -X[2,2] = 1
        # Q >= 0                        y free
        # o free                        X <= 0
        #   @testset "Just another SDP" begin
        #       model = Model(solver=CSDPSolver(printlevel=0))
        #       @variable(model, Q[1:2, 1:2], PSD)
        #       c1 = @constraint(model, Q[1,1] - 1 == Q[2,2])
        #       @variable(model, objective)
        #       T = [1 Q[1,1]; Q[1,1] objective]
        #       @test_throws ErrorException SDConstraint(T, 1)
        #       c2 = JuMP.addconstraint(model, SDConstraint(T, 0))
        #       @objective(model, Min, objective)
        #
        #       JuMP.solve(m)
        #
        #       @test JuMP.terminationstatus(m) == MOI.Success
        #       @test JuMP.primalstatus(m) == MOI.FeasiblePoint
        #
        #       @test JuMP.resultvalue(Q) ≈ [1 0; 0 0] atol=1e-3
        #       @test JuMP.objectivevalue(model) ≈ 1 atol=1e-4
        #       @test JuMP.resultvalue(objective) ≈ 1 atol=1e-4
        #       @test getdual(objective) ≈, 0, atol=1e-5
        #       @test getdual(Q) ≈ [0 0; 0 2] atol=1e-3
        #       @test getdual(c1) ≈ 2, atol=1e-4 # y
        #       @test getdual(c2) ≈ [-1 1; 1 -1] atol=1e-3 # X
        #   end

        # The four following tests are from Example 2.11, Example 2.13 and Example 2.27 of:
        # Blekherman, G., Parrilo, P. A., & Thomas, R. R. (Eds.).
        # Semidefinite optimization and convex algebraic geometry SIAM 2013

        # Example 2.11
        @testset "SDP variable and optimal objective not rational" begin
            #       solver = fixscs(solver, 7000000)
            m = Model(solver=solver)
            @variable(m, X[1:2,1:2], PSD)
            c = @constraint(m, X[1,1]+X[2,2] == 1)
            @objective(m, Min, 2*X[1,1]+2*X[1,2])
            #       @test all(isnan.(getdual(X)))

            JuMP.solve(m)

            @test JuMP.terminationstatus(m) == MOI.Success
            @test JuMP.primalstatus(m) == MOI.FeasiblePoint

            @test JuMP.objectivevalue(m) ≈ 1-sqrt(2) atol=1e-5
            @test JuMP.resultvalue.(X) ≈ [(2-sqrt(2))/4 -1/(2*sqrt(2)); -1/(2*sqrt(2)) (2+sqrt(2))/4] atol=1e-4
            #       @test getdual(X) ≈ [1+sqrt(2) 1; 1 sqrt(2)-1] atol=1e-4
            #       @test getdual(c) ≈ 1-sqrt(2) atol=1e-5
        end

        #   # Example 2.13
        #   @testset "SDP constraint and optimal objective not rational with $solver" for solver in sdp_solvers
        #       solver = fixscs(solver, 7000000)
        #       m = Model(solver=solver)
        #       @variable(m, y)
        #       c = @SDconstraint(m, [2-y 1; 1 -y] >= 0)
        #       @objective(m, Max, y)
        #       @test all(isnan, getdual(c))
        #       status = solve(m)
        #
        #       @test status == :Optimal
        #       @test isapprox(getobjectivevalue(m), 1-sqrt(2), atol=1e-5)
        #       @test isapprox(getvalue(y), 1-sqrt(2), atol=1e-5)
        #
        #       X = getdual(c)
        #       @test isapprox(getdual(c), [(2-sqrt(2))/4 -1/(2*sqrt(2)); -1/(2*sqrt(2)) (2+sqrt(2))/4], atol=1e-4)
        #       @test isapprox(getdual(y), 0, atol=1e-5)
        #   end
        #
        #   # Example 2.27
        #   # min X[1,1]   max y
        #   # 2X[1,2] = 1  [0 y     [1 0
        #   # X ⪰ 0         y 0] ⪯   0 0]
        #   # The dual optimal solution is y=0 and there is a primal solution
        #   # [ eps  1/2
        #   #   1/2  1/eps]
        #   # for any eps > 0 however there is no primal solution with objective value 0.
        #   @testset "SDP with dual solution not attained with $solver" for solver in sdp_solvers
        #       solver = fixscs(solver, 7000000)
        #       m = Model(solver=solver)
        #       @variable(m, y)
        #       c = @SDconstraint(m, [0 y; y 0] <= [1 0; 0 0])
        #       @objective(m, Max, y)
        #       @test all(isnan, getdual(c))
        #       status = solve(m)
        #
        #       if contains(string(typeof(solver)),"MosekSolver")
        #           # Mosek returns Stall on this instance
        #           # Hack until we fix statuses in MPB
        #           JuMP.fillConicDuals(m)
        #       else
        #           @test status == :Optimal
        #       end
        #       @test isapprox(getobjectivevalue(m), 0, atol=1e-5)
        #       @test isapprox(getvalue(y), 0, atol=1e-5)
        #
        #       X = getdual(c)
        #       @test isapprox(X[1,1], 0, atol=1e-5)
        #       @test isapprox(X[1,2], 1/2, atol=1e-5)
        #       @test isapprox(X[2,1], 1/2, atol=1e-5)
        #       @test isapprox(getdual(y), 0, atol=1e-5)
        #   end

        @testset "SDP with primal solution not attained" begin
            #       solver = fixscs(solver, 7000000)
            m = Model(solver=solver)
            @variable(m, X[1:2,1:2], PSD)
            c = @constraint(m, 2*X[1,2] == 1)
            @objective(m, Min, X[1,1])
            #       @test all(isnan, getdual(X))
            status = solve(m)

            @test JuMP.terminationstatus(m) in [ MOI.Success, MOI.SlowProgress ]
            @test JuMP.primalstatus(m) == MOI.FeasiblePoint

            @test JuMP.objectivevalue(m) ≈ 0 atol=1e-5
            Xval = JuMP.resultvalue.(X)
            #Mosek.writedata(m.solverinstance.task,"jump_sdo_1_stalls.task")
            #showall(m.solverinstance.task)
            #showall(m.solverinstance.task[Sol(Mosek.MSK_SOL_ITR)])

            @test Xval[1,1] ≈ 0 atol=1e-5
            @test Xval[1,2] ≈ 1/2 atol=1e-5
            @test Xval[2,1] ≈ 1/2 atol=1e-5

            #       @test isapprox(getdual(X), [1 0; 0 0], atol=1e-4)
            #       @test isapprox(getdual(c), 0, atol=1e-5)
        end

        @testset "No constraint" begin
            m = Model(solver=solver)
            @variable(m, X[1:3,1:3], PSD)
            @objective(m, Min, trace(X))

            JuMP.solve(m)

            status = solve(m)

            @test JuMP.terminationstatus(m) == MOI.Success
            @test JuMP.primalstatus(m) == MOI.FeasiblePoint

            @test abs(JuMP.objectivevalue(m)) < 1e-5
            @test norm(JuMP.resultvalue.(X)) < 1e-5
            #@test isapprox(getdual(X), eye(3), atol=1e-5)
        end

    end
end


text:
# Plots angles:
nb = 1001; nr = 1001
b=linspace(0.0,2,nr)
r=linspace(0.0,2,nr)
lambda = zeros(Float64,nr,nb)
phi = zeros(Float64,nr,nb)
for i=1:nr, j=1:nr
  if b[i] <= 1-r[j]
    phi[j,i]=pi/2; lambda[i,j]=pi/2
  elseif abs(1-r[j]) < b[i] && b[i] < 1+r[j]
    sphi = (1-r[j]^2-b[i]^2)/(2*b[i]*r[j])
    if abs(sphi) <= 1
      phi[j,i]=asin(sphi)
    else
      cphi = (1-b[i]+r[j])*(1+b[i]-r[j])*(b[i]+r[j]-1)*(1+b[i]+r[j])/(2*b[i]*r[j])
      println("r: ",r[j]," b: ",b[i]," sin(phi): ",sphi," cos(phi): ",cphi)
      phi[j,i] = acos(cphi)
    end
    slam = (1+(r[j]+b[i])*(b[i]-r[j]))/(2*b[i])
    if abs(slam) > 1
      println("r: ",r[j]," b: ",b[i]," sin(lam): ",slam)
    end
    lambda[j,i]=asin(slam)
  end
end
using PyPlot
clf()
img=imshow(phi,interpolation="nearest",origin="lower",extent=[0,2,0,2])
xlabel("Impact parameter")
ylabel("Radius ratio")
colorbar(img)
#read(STDIN,Char)
clf()
img=imshow(lambda,interpolation="nearest",origin="lower",extent=[0,2,0,2])
xlabel("Impact parameter")
ylabel("Radius ratio")
colorbar(img)

max_stars_repo_name: tagordon/limbdark

max_issues_repo_name: tagordon/limbdark

max_forks_repo_name: tagordon/limbdark


text:
@testset "newton raphson with linesearch" begin
    function f1(θ, u)
        return u^2 - 1, 2*spdiag(u)
    end

    function f2(θ, u)
        return u^3-2u-5, spdiag(3u^2-2)
    end

    function f3(θ, u)
        return exp(2u)-u-6, spdiag(2*exp(2u)-1)
    end

    function f4(θ, u)
        return (cos(u)-u)^2, spdiag((-u + cos(u))*(-2*sin(u) - 2))
    end

    function f5(θ, u)
        return sum(1/3*(u-1)^3), (u - 1)^2, 2*spdiag(u-1)
    end

    function f6(θ, u)
        return sum((u-1.3)^2), 2(u-1.3), 2spdiag(length(u))
    end

    function f7(θ, u)
        return sum((0.988 * u^5 - 4.96 * u^4 + 4.978 * u^3 + 5.015 * u^2 - 6.043 * u - 1)),
                    4.94 * u^4 - 19.84 * u^3 + 14.934 * u^2 + 10.03 * u - 6.043,
                    spdiag(4.94*3*u^3 - 19.84*3*u^2 + 14.934*2*u + 10.03)
    end

    function f8(θ, u)
        return sum((u-1.3)^2), 2(u-1.3), 2spdiag(length(u))
    end

    res = [1.0, 2.0946, 0.97085, 0.73989]
    nr = Array{Any}(undef, 8)
    fs = [f1,f2,f3,f4,f5,f6,f7,f8]

    ADCME.options.newton_raphson.linesearch = true
    ADCME.options.newton_raphson.verbose = false
    ADCME.options.newton_raphson.rtol = 1e-12
    ADCME.options.newton_raphson.linesearch_options.αinitial = 1.0
    for i = 5:7
    nr[i] = newton_raphson(fs[i], constant(rand(1)), missing)
    end

    reset_default_options()
    ADCME.options.newton_raphson.verbose = false
    for i = 1:4
        nr[i] = newton_raphson(fs[i], constant(rand(1)), missing)
    end
    sess = Session(); init(sess)
    nrr = [run(sess, nr[i]) for i = 1:7]

    for i = 1:4
        @show nrr[i].x, nrr[i].iter, nrr[i].converged
        @test nrr[i].converged
    end

    for i = 5:7
        @show nrr[i].x, nrr[i].iter, nrr[i].converged
        @test nrr[i].converged
    end
end