text:
function UnivariateDerivative1(arg0::DerivativeStructure)
    return UnivariateDerivative1((DerivativeStructure,), arg0)
end

function UnivariateDerivative1(arg0::jdouble, arg1::jdouble)
    return UnivariateDerivative1((jdouble, jdouble), arg0, arg1)
end

function abs(obj::UnivariateDerivative1)
    return jcall(obj, "abs", UnivariateDerivative1, ())
end

function acos(obj::UnivariateDerivative1)
    return jcall(obj, "acos", UnivariateDerivative1, ())
end

function acosh(obj::UnivariateDerivative1)
    return jcall(obj, "acosh", UnivariateDerivative1, ())
end

function add(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "add", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function add(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "add", UnivariateDerivative1, (jdouble,), arg0)
end

function asin(obj::UnivariateDerivative1)
    return jcall(obj, "asin", UnivariateDerivative1, ())
end

function asinh(obj::UnivariateDerivative1)
    return jcall(obj, "asinh", UnivariateDerivative1, ())
end

function atan(obj::UnivariateDerivative1)
    return jcall(obj, "atan", UnivariateDerivative1, ())
end

function atan2(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "atan2", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function atanh(obj::UnivariateDerivative1)
    return jcall(obj, "atanh", UnivariateDerivative1, ())
end

function cbrt(obj::UnivariateDerivative1)
    return jcall(obj, "cbrt", UnivariateDerivative1, ())
end

function ceil(obj::UnivariateDerivative1)
    return jcall(obj, "ceil", UnivariateDerivative1, ())
end

function compose(obj::UnivariateDerivative1, arg0::jdouble, arg1::jdouble)
    return jcall(obj, "compose", UnivariateDerivative1, (jdouble, jdouble), arg0, arg1)
end

function copy_sign(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "copySign", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function copy_sign(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "copySign", UnivariateDerivative1, (jdouble,), arg0)
end

function cos(obj::UnivariateDerivative1)
    return jcall(obj, "cos", UnivariateDerivative1, ())
end

function cosh(obj::UnivariateDerivative1)
    return jcall(obj, "cosh", UnivariateDerivative1, ())
end

function divide(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "divide", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function divide(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "divide", UnivariateDerivative1, (jdouble,), arg0)
end

function equals(obj::UnivariateDerivative1, arg0::Object)
    return jcall(obj, "equals", jboolean, (Object,), arg0)
end

function exp(obj::UnivariateDerivative1)
    return jcall(obj, "exp", UnivariateDerivative1, ())
end

function expm1(obj::UnivariateDerivative1)
    return jcall(obj, "expm1", UnivariateDerivative1, ())
end

function floor(obj::UnivariateDerivative1)
    return jcall(obj, "floor", UnivariateDerivative1, ())
end

function get_derivative(obj::UnivariateDerivative1, arg0::jint)
    return jcall(obj, "getDerivative", jdouble, (jint,), arg0)
end

function get_exponent(obj::UnivariateDerivative1)
    return jcall(obj, "getExponent", jint, ())
end

function get_field(obj::UnivariateDerivative1)
    return jcall(obj, "getField", UnivariateDerivative1Field, ())
end

function get_first_derivative(obj::UnivariateDerivative1)
    return jcall(obj, "getFirstDerivative", jdouble, ())
end

function get_order(obj::UnivariateDerivative1)
    return jcall(obj, "getOrder", jint, ())
end

function get_real(obj::UnivariateDerivative1)
    return jcall(obj, "getReal", jdouble, ())
end

function get_value(obj::UnivariateDerivative1)
    return jcall(obj, "getValue", jdouble, ())
end

function hash_code(obj::UnivariateDerivative1)
    return jcall(obj, "hashCode", jint, ())
end

function hypot(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "hypot", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function linear_combination(obj::UnivariateDerivative1, arg0::UnivariateDerivative1, arg1::UnivariateDerivative1, arg2::UnivariateDerivative1, arg3::UnivariateDerivative1)
    return jcall(obj, "linearCombination", UnivariateDerivative1, (UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1), arg0, arg1, arg2, arg3)
end

function linear_combination(obj::UnivariateDerivative1, arg0::UnivariateDerivative1, arg1::UnivariateDerivative1, arg2::UnivariateDerivative1, arg3::UnivariateDerivative1, arg4::UnivariateDerivative1, arg5::UnivariateDerivative1)
    return jcall(obj, "linearCombination", UnivariateDerivative1, (UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1), arg0, arg1, arg2, arg3, arg4, arg5)
end

function linear_combination(obj::UnivariateDerivative1, arg0::UnivariateDerivative1, arg1::UnivariateDerivative1, arg2::UnivariateDerivative1, arg3::UnivariateDerivative1, arg4::UnivariateDerivative1, arg5::UnivariateDerivative1, arg6::UnivariateDerivative1, arg7::UnivariateDerivative1)
    return jcall(obj, "linearCombination", UnivariateDerivative1, (UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1, UnivariateDerivative1), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)
end

function linear_combination(obj::UnivariateDerivative1, arg0::Vector{UnivariateDerivative1}, arg1::Vector{UnivariateDerivative1})
    return jcall(obj, "linearCombination", UnivariateDerivative1, (Vector{UnivariateDerivative1}, Vector{UnivariateDerivative1}), arg0, arg1)
end

function linear_combination(obj::UnivariateDerivative1, arg0::Vector{jdouble}, arg1::Vector{UnivariateDerivative1})
    return jcall(obj, "linearCombination", UnivariateDerivative1, (Vector{jdouble}, Vector{UnivariateDerivative1}), arg0, arg1)
end

function linear_combination(obj::UnivariateDerivative1, arg0::jdouble, arg1::UnivariateDerivative1, arg2::jdouble, arg3::UnivariateDerivative1)
    return jcall(obj, "linearCombination", UnivariateDerivative1, (jdouble, UnivariateDerivative1, jdouble, UnivariateDerivative1), arg0, arg1, arg2, arg3)
end

function linear_combination(obj::UnivariateDerivative1, arg0::jdouble, arg1::UnivariateDerivative1, arg2::jdouble, arg3::UnivariateDerivative1, arg4::jdouble, arg5::UnivariateDerivative1)
    return jcall(obj, "linearCombination", UnivariateDerivative1, (jdouble, UnivariateDerivative1, jdouble, UnivariateDerivative1, jdouble, UnivariateDerivative1), arg0, arg1, arg2, arg3, arg4, arg5)
end

function linear_combination(obj::UnivariateDerivative1, arg0::jdouble, arg1::UnivariateDerivative1, arg2::jdouble, arg3::UnivariateDerivative1, arg4::jdouble, arg5::UnivariateDerivative1, arg6::jdouble, arg7::UnivariateDerivative1)
    return jcall(obj, "linearCombination", UnivariateDerivative1, (jdouble, UnivariateDerivative1, jdouble, UnivariateDerivative1, jdouble, UnivariateDerivative1, jdouble, UnivariateDerivative1), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)
end

function log(obj::UnivariateDerivative1)
    return jcall(obj, "log", UnivariateDerivative1, ())
end

function log10(obj::UnivariateDerivative1)
    return jcall(obj, "log10", UnivariateDerivative1, ())
end

function log1p(obj::UnivariateDerivative1)
    return jcall(obj, "log1p", UnivariateDerivative1, ())
end

function multiply(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "multiply", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function multiply(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "multiply", UnivariateDerivative1, (jdouble,), arg0)
end

function multiply(obj::UnivariateDerivative1, arg0::jint)
    return jcall(obj, "multiply", UnivariateDerivative1, (jint,), arg0)
end

function negate(obj::UnivariateDerivative1)
    return jcall(obj, "negate", UnivariateDerivative1, ())
end

function new_instance(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "newInstance", UnivariateDerivative1, (jdouble,), arg0)
end

function pow(::Type{UnivariateDerivative1}, arg0::jdouble, arg1::UnivariateDerivative1)
    return jcall(UnivariateDerivative1, "pow", UnivariateDerivative1, (jdouble, UnivariateDerivative1), arg0, arg1)
end

function pow(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "pow", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function pow(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "pow", UnivariateDerivative1, (jdouble,), arg0)
end

function pow(obj::UnivariateDerivative1, arg0::jint)
    return jcall(obj, "pow", UnivariateDerivative1, (jint,), arg0)
end

function reciprocal(obj::UnivariateDerivative1)
    return jcall(obj, "reciprocal", UnivariateDerivative1, ())
end

function remainder(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "remainder", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function remainder(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "remainder", UnivariateDerivative1, (jdouble,), arg0)
end

function rint(obj::UnivariateDerivative1)
    return jcall(obj, "rint", UnivariateDerivative1, ())
end

function root_n(obj::UnivariateDerivative1, arg0::jint)
    return jcall(obj, "rootN", UnivariateDerivative1, (jint,), arg0)
end

function scalb(obj::UnivariateDerivative1, arg0::jint)
    return jcall(obj, "scalb", UnivariateDerivative1, (jint,), arg0)
end

function signum(obj::UnivariateDerivative1)
    return jcall(obj, "signum", UnivariateDerivative1, ())
end

function sin(obj::UnivariateDerivative1)
    return jcall(obj, "sin", UnivariateDerivative1, ())
end

function sin_cos(obj::UnivariateDerivative1)
    return jcall(obj, "sinCos", FieldSinCos, ())
end

function sinh(obj::UnivariateDerivative1)
    return jcall(obj, "sinh", UnivariateDerivative1, ())
end

function sqrt(obj::UnivariateDerivative1)
    return jcall(obj, "sqrt", UnivariateDerivative1, ())
end

function subtract(obj::UnivariateDerivative1, arg0::UnivariateDerivative1)
    return jcall(obj, "subtract", UnivariateDerivative1, (UnivariateDerivative1,), arg0)
end

function subtract(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "subtract", UnivariateDerivative1, (jdouble,), arg0)
end

function tan(obj::UnivariateDerivative1)
    return jcall(obj, "tan", UnivariateDerivative1, ())
end

function tanh(obj::UnivariateDerivative1)
    return jcall(obj, "tanh", UnivariateDerivative1, ())
end

function taylor(obj::UnivariateDerivative1, arg0::jdouble)
    return jcall(obj, "taylor", jdouble, (jdouble,), arg0)
end

function to_degrees(obj::UnivariateDerivative1)
    return jcall(obj, "toDegrees", UnivariateDerivative1, ())
end

function to_derivative_structure(obj::UnivariateDerivative1)
    return jcall(obj, "toDerivativeStructure", DerivativeStructure, ())
end

function to_radians(obj::UnivariateDerivative1)
    return jcall(obj, "toRadians", UnivariateDerivative1, ())
end


text:
function maketable3(panel::DataFrame; trialrunonly::Bool=trialrunonly,
    runpanela::Bool=true,
    runpanelb::Bool=true,
    )::Nothing
  #load the data we will work with
  #panel::DataFrame = constructportfolios(refreshportfolios=false, trialrunonly=trialrunonly)
  sort!(panel, [:permno, :date])
  apanel::DataFrame = panel[panel.annflag,:]
  #apanel = apanel[apanel.fyear .≤ 2016,:] #WARNING DELETE THIS!!!!
  apanel.year = (year).(apanel.date)
  ################common data
  cqports::PortfolioConstructions = leverageconstructions()
  T3_FNAMES::Vector{Symbol} = CQUART_FNAMES_D
  T3_FVALS::Vector{Symbol} = CQUART_FVALS_D
  T3_FGROUPS::Vector{Symbol} = CQUART_FGROUPS_D
  T3_FNAMES_ALT::Vector{Symbol} = CQUART_FNAMES_ALT_D
  T3_FGROUPS_ALT::Vector{Symbol} = CQUART_FGROUPS_ALT_D

  #########################PANEL A#########################

  T3_PANEL_A_ROWKEYS::Vector{Symbol} = [:mknegcash, :bknegcash, :mkflev,
    :bkflev, :mkliab, :bkliab]

  T3_PANEL_A_ROWLABEL::Dict = Dict(
    :mknegcash=>"\$\\Delta\$mknegcash",
    :bknegcash=>"\$\\Delta\$bknegcash",
    :mkflev=>"\\\\ \$\\Delta\$mkflev",
    :bkflev=>"\$\\Delta\$bkflev",
    :mkliab=>"\\\\ \$\\Delta\$mkliab",
    :bkliab=>"\$\\Delta\$bkliab")

  T3_PANEL_A_FOCALS::Dict = Dict(
    :mknegcash=>[:Lvol252d, :LLvol252d, :LDmknegcash],
    :bknegcash=>[:Lvol252d, :LLvol252d, :LDbknegcash],
    :mkflev=>[:Lvol252d, :LLvol252d, :LDmkflev],
    :bkflev=>[:Lvol252d, :LLvol252d, :LDbkflev],
    :mkliab=>[:Lvol252d, :LLvol252d, :LDmkliab],
    :bkliab=>[:Lvol252d, :LLvol252d, :LDbkliab])

  T3_PANEL_A_CONTROLS::Dict = Dict(
    :mknegcash=>CONTROL0,
    :bknegcash=>CONTROL0,
    :mkflev=>CONTROL0,
    :bkflev=>CONTROL0,
    :mkliab=>CONTROL0,
    :bkliab=>CONTROL0)

  T3_PANEL_A_RET::Dict = Dict(
    :mknegcash=>:vol252d,
    :bknegcash=>:vol252d,
    :mkflev=>:vol252d,
    :bkflev=>:vol252d,
    :mkliab=>:vol252d,
    :bkliab=>:vol252d)

  T3_PANEL_A_NAME::String = "t3panela-$(REPLICATION_TYPE[])-$(OUT_SUFFIX[])"

  T3_PANEL_A_MIN_ROWS = 5

  runpanela && table3panelA(apanel,
      fvals=T3_FVALS,
      fgroups=T3_FGROUPS,
      ret = T3_PANEL_A_RET,
      rowkeys=T3_PANEL_A_ROWKEYS,
      rowlabel=T3_PANEL_A_ROWLABEL,
      controls=T3_PANEL_A_CONTROLS,
      focals=T3_PANEL_A_FOCALS,
      tablename=T3_PANEL_A_NAME,
      minrowspergroup = T3_PANEL_A_MIN_ROWS
    )

    #########################PANEL B#########################

    T3_PANEL_B_ROWKEYS::Vector{Symbol} = [:mknegcash, :bknegcash, :mkflev,
      :bkflev, :mkliab, :bkliab]

    T3_PANEL_B_ROWLABEL::Dict = Dict(
      :mknegcash=>"\$\\Delta\$mknegcash",
      :bknegcash=>"\$\\Delta\$bknegcash",
      :mkflev=>"\\\\ \$\\Delta\$mkflev",
      :bkflev=>"\$\\Delta\$bkflev",
      :mkliab=>"\\\\ \$\\Delta\$mkliab",
      :bkliab=>"\$\\Delta\$bkliab")

    T3_PANEL_B_FOCALS::Dict = Dict(
      :mknegcash=>[:Lvol252d, :LLvol252d, :LDmknegcash],
      :bknegcash=>[:Lvol252d, :LLvol252d, :LDbknegcash],
      :mkflev=>[:Lvol252d, :LLvol252d, :LDmkflev],
      :bkflev=>[:Lvol252d, :LLvol252d, :LDbkflev],
      :mkliab=>[:Lvol252d, :LLvol252d, :LDmkliab],
      :bkliab=>[:Lvol252d, :LLvol252d, :LDbkliab])

    T3_PANEL_B_CONTROLS::Dict = Dict(
      :mknegcash=>CONTROL0,
      :bknegcash=>CONTROL0,
      :mkflev=>CONTROL0,
      :bkflev=>CONTROL0,
      :mkliab=>CONTROL0,
      :bkliab=>CONTROL0)

    T3_PANEL_B_RET::Dict = Dict(
      :mknegcash=>:vol252d,
      :bknegcash=>:vol252d,
      :mkflev=>:vol252d,
      :bkflev=>:vol252d,
      :mkliab=>:vol252d,
      :bkliab=>:vol252d)

    T3_PANEL_B_CLUSTERS::Vector{Symbol} = [:fyear, :permno]

    T3_PANEL_B_Σ::Vector{Function} = [homoskedasticΣ!,
      lin::FMLM->clusteredΣ!(lin, clusters=[lin.clusters[1]]),
      lin::FMLM->clusteredΣ!(lin, clusters=[lin.clusters[2]]),
      modifiedwhiteΣ!,
      lin::FMLM->clusteredΣ!(lin, clusters=lin.clusters#=, testequivelance=true=#)]

    T3_PANEL_B_NAME::String = "t3panelb-$(REPLICATION_TYPE[])-$(OUT_SUFFIX[])"

    T3_PANEL_B_MIN_ROWS = 5

    runpanelb && table3panelB(apanel,
        fvals=T3_FVALS,
        fgroups=T3_FGROUPS,
        ret = T3_PANEL_B_RET,
        rowkeys=T3_PANEL_B_ROWKEYS,
        rowlabel=T3_PANEL_B_ROWLABEL,
        controls=T3_PANEL_B_CONTROLS,
        focals=T3_PANEL_B_FOCALS,
        tablename=T3_PANEL_B_NAME,
        minrowspergroup = T3_PANEL_B_MIN_ROWS,
        fclusters = [:fyear, :permno],
        errorfunctions = T3_PANEL_B_Σ
      )
  return nothing
end

function table3panelA(panel::DataFrame;
    fvals::Vector{Symbol} = error("fvals is required"),
    ret::Dict = error("ret is required"),
    rowkeys::Vector{Symbol} = error("rowkeys is required"),
    rowlabel::Dict = error("rowlabel is required"),
    focals::Dict = error("focals is required"),
    controls::Dict = error("controls is required"),
    tablename::String = error("table name is required"),
    fgroups::Vector{Symbol} = error("fgroups is required"),
    tablepath::String = TABLE_PATH,
    colnames::Vector{Vector{String}} = [["Method",
      "\$\\alpha\$", "\$\\rho_1\$", "\$\\rho_2\$", "\$\\gamma\$",
      "\\% Years Positive"]],
    decimals::Int = DEFAULT_DECIMALS,
    minrowspergroup::Int = error("minrowspergroup is required"))

  Nrows::Int = length(rowkeys)*2
  Ncols::Int = length(colnames[1])
  local parallel::Bool = PARALLEL[] && (!DISABLE_FM_PARALLEL)

  #################################
  fss::Vector{FactorSpecification} = Vector{FactorSpecification}()
  sizehint!(fss, length(rowkeys) * length(fgroups))

  #make the regression specifications
  for rname ∈ rowkeys
    fs::FactorSpecification = FactorSpecification(
      panel, ret[rname], :fyear, :permno,
      skiptimeseriesdfcheck = true,
      minrowspergroup = minrowspergroup,
      Ffactors=nothing,
      Fcharacteristics = focals[rname],
      Fcontrols = controls[rname],
      name=Symbol("row$(rname)"))
    push!(fss, fs)
  end

  #Run the regressions
  #WARNING: When BLAS paralllelization issues are solved replace with parallel=PARALLEL[]

  frs::Vector{FactorRegression} = Vector{FactorRegression}(undef, length(fss))
  for i ∈ 1:length(fss)
    frs[i] = characteristicFM(fss[i], parallel=parallel)
  end
  frsidx::Dict = Dict(fr.name=>fr for fr ∈ frs)
  #println(collect(keys(frsidx)))
  #make the table
  descrownames::Vector{String} = [(s->[rowlabel[s], ""]).(rowkeys)...;]
  desccontent::Vector{Vector{String}} = (i->
    Vector{String}(undef, Ncols)).(1:Nrows)

  for (i,rname) ∈ enumerate(rowkeys)
    fr::FactorRegression = frsidx[Symbol("row$(rname)")]
    r::Int = 2*(i-1)+1
    desccontent[r][1] = "\\text{Coefficients}"
    desccontent[r+1][1] = "\\text{(NW(2) T-stat)}"

    #coefficients
    desccontent[r][2] = "$(num2str(fr.λᵢ[fr.coefidx[:intercept]]))"
    desccontent[r][3] = "$(num2str(fr.λᵢ[fr.coefidx[focals[rname][1]]]))"
    desccontent[r][4] = "$(num2str(fr.λᵢ[fr.coefidx[focals[rname][2]]]))"
    desccontent[r][5] = "$(num2str(fr.λᵢ[fr.coefidx[focals[rname][3]]]))"

    #SEs
    desccontent[r+1][2] = tstatstr(fr, decimals=decimals, i=fr.coefidx[:intercept])
    desccontent[r+1][3] = tstatstr(fr, decimals=decimals, i=fr.coefidx[focals[rname][1]])
    desccontent[r+1][4] = tstatstr(fr, decimals=decimals, i=fr.coefidx[focals[rname][2]])
    desccontent[r+1][5] = tstatstr(fr, decimals=decimals, i=fr.coefidx[focals[rname][3]])

    perλ::Int = Int(round(sum(fr.λ[:,fr.coefidx[focals[rname][3]]] .≥ 0)/size(fr.λ,1)*100))
    desccontent[r][6] = num2str(perλ, 0)
    desccontent[r+1][6] = ""
  end

  alignmentstring::String = "ll rrrrr"

  tt::String = textable(colnames=colnames,  descrownames=descrownames,
    desccontent=desccontent, alignmentstring=alignmentstring)

  writetextable(tt, path=tablepath, outname="$tablename.tex")
end

function table3panelB(panel::DataFrame;
    fvals::Vector{Symbol} = error("fvals is required"),
    ret::Dict = error("ret is required"),
    rowkeys::Vector{Symbol} = error("rowkeys is required"),
    rowlabel::Dict = error("rowlabel is required"),
    focals::Dict = error("focals is required"),
    controls::Dict = error("controls is required"),
    tablename::String = error("table name is required"),
    fgroups::Vector{Symbol} = error("fgroups is required"),
    tablepath::String = TABLE_PATH,
    colnames::Vector{Vector{String}} = [[
      "\$\\rho_1\$", "\$\\rho_2\$", "\$\\gamma\$",
      "OLS", "CLR-i", "CLR-t", "WHT", "CLR-i\\&t"]],
    decimals::Int = DEFAULT_DECIMALS,
    minrowspergroup::Int = error("minrowspergroup is required"),
    errorfunctions::Vector{Function} = "error functions are required",
    fclusters = [:fyear, :permno]
    )

  Nrows::Int = length(rowkeys)
  Ncols::Int = length(colnames[1])
  local parallel::Bool = PARALLEL[] && (!DISABLE_FM_PARALLEL)

  #################################
  fss::Vector{FactorSpecification} = Vector{FactorSpecification}()
  sizehint!(fss, length(rowkeys))

  #make the regression specifications
  for rname ∈ rowkeys
    fs::FactorSpecification = FactorSpecification(
      skiptimeseriesdfcheck = true,
      minrowspergroup = minrowspergroup,
      panel, ret[rname], :fyear, :permno,
      Ffactors=nothing,
      Fcharacteristics = focals[rname],
      Fcontrols = controls[rname],
      name=Symbol("row$(rname)"))
    push!(fss, fs)
  end

  #Run the regressions
  #WARNING: When BLAS paralllelization issues are solved replace with parallel=PARALLEL[]

  vfrs::Vector{Vector{FactorRegression}} = []
  sizehint!(vfrs, length(fss))
  for i ∈ 1:length(fss)
    frs::Vector{FactorRegression} = panelFM(fss[i], errorfunctions=errorfunctions)
    push!(vfrs, frs)
  end

  #gets the row
  frsidx::Dict = Dict(rname=>vfrs[j] for (j,rname) ∈ enumerate(rowkeys))
  colidx::Dict = Dict(:ρ₁=>1, :ρ₂=>2, :γ=>3, :ols=>4, :cross=>5, :ts=>6, :wht=>7, :bth=>8)

  #println(collect(keys(frsidx)))
  #make the table
  descrownames::Vector{String} = [(s->rowlabel[s]).(rowkeys);]
  desccontent::Vector{Vector{String}} = (i->
    Vector{String}(undef, Ncols)).(1:Nrows)

  for (r,rname) ∈ enumerate(rowkeys)
    frs::Vector{FactorRegression} = frsidx[rname]

    #coefficients
    desccontent[r][colidx[:ρ₁]] = "$(num2str(frs[1].λᵢ[frs[1].coefidx[focals[rname][1]]]))"
    desccontent[r][colidx[:ρ₂]] = "$(num2str(frs[1].λᵢ[frs[1].coefidx[focals[rname][2]]]))"
    desccontent[r][colidx[:γ]] = "$(num2str(frs[1].λᵢ[frs[1].coefidx[focals[rname][3]]]))"

    #SEs
    desccontent[r][colidx[:ols]] = tstatstr(frs[1], decimals=decimals, i=frs[1].coefidx[focals[rname][3]])
    desccontent[r][colidx[:cross]] = tstatstr(frs[2], decimals=decimals, i=frs[2].coefidx[focals[rname][3]])
    desccontent[r][colidx[:ts]] = tstatstr(frs[3], decimals=decimals, i=frs[3].coefidx[focals[rname][3]])
    desccontent[r][colidx[:wht]] = tstatstr(frs[4], decimals=decimals, i=frs[4].coefidx[focals[rname][3]])
    desccontent[r][colidx[:bth]] = tstatstr(frs[5], decimals=decimals, i=frs[5].coefidx[focals[rname][3]])

  end

  #alignmentstring::String = "l rrrrrrrr"

  tt::String = textable(colnames=colnames,  descrownames=descrownames,
    desccontent=desccontent)

  writetextable(tt, path=tablepath, outname="$tablename.tex")
end

function tstatstr(fr::FactorRegression; decimals::Int=DEFAULT_DECIMALS, i::Int=2,
  )::String
  tstat::Float64 = fr.λᵢ[i]/fr.σᵢ[i]
  return "($(num2str(tstat, decimals)))"
end

ext: jl

max_stars_repo_name: clintonTE/CCA

max_issues_repo_name: clintonTE/CCA

max_forks_repo_name: clintonTE/CCA


text:
using Test
using DFTK
include("testcases.jl")

@testset "Test reduced / cartesian conversion" begin
    Ecut = 3
    fft_size = [13, 15, 14]
    model = Model(silicon.lattice, silicon.atoms, silicon.positions)

    rred = randn(3)  # reduced "position"
    fred = randn(3)  # reduced "force"
    qred = randn(3)  # reduced "reciprocal vector"
    @test(  dot(DFTK.covector_red_to_cart(model, fred), DFTK.vector_red_to_cart(model, rred))
          ≈ dot(fred, rred))
    @test(dot(DFTK.vector_red_to_cart(model, rred), DFTK.recip_vector_red_to_cart(model, qred))
          ≈ 2π * dot(rred, qred))

    @test DFTK.vector_cart_to_red(model, DFTK.vector_red_to_cart(model, rred)) ≈ rred
    @test DFTK.covector_cart_to_red(model, DFTK.covector_red_to_cart(model, fred)) ≈ fred
    @test DFTK.recip_vector_cart_to_red(model, DFTK.recip_vector_red_to_cart(model, qred)) ≈ qred

    rcart = randn(3)
    fcart = randn(3)
    @test dot(DFTK.covector_cart_to_red(model, fcart),
              DFTK.vector_cart_to_red(model, rcart))   ≈ dot(fcart, rcart)

    Ared = randn(3, 3)  # real-space       "symmetry"
    Bred = randn(3, 3)  # reciprocal-space "symmetry"
    @test(  dot(DFTK.comatrix_red_to_cart(model, Bred) * DFTK.covector_red_to_cart(model, fred),
                DFTK.matrix_red_to_cart(model, Ared) * DFTK.vector_red_to_cart(model, rred))
          ≈ dot(Bred * fred, Ared * rred))

    @test DFTK.comatrix_cart_to_red(model, DFTK.comatrix_red_to_cart(model, Bred)) ≈ Bred
    @test DFTK.matrix_cart_to_red(model,   DFTK.matrix_red_to_cart(model,   Ared)) ≈ Ared
end


text:
module TestChannels

using ArgCheck
using Julio
using Julio.Internal: @trace
using Test
using ..Utils: random_sleep, trywait, ⊏

function test_after_close()
    @testset for f in [Julio.stack, Julio.queue]
        test_after_close(f)
    end
end

function test_after_close(f)
    ie, oe = f(Int)
    put!(ie, 111)
    close(ie)
    @test take!(oe) == 111
end

function test_close_many()
    @testset for f in [Julio.stack, Julio.queue, Julio.channel]
        test_close_many(f)
    end
end

function test_close_many(f)
    ie, oe = f(Int)
    t = @task collect(oe)
    yield(t)
    put!(ie, 111)
    @test !trywait(t)
    put!(ie, 222)
    close(ie)
    close(ie)
    @check trywait(t, 3)
    @test fetch(t) == [111, 222]
end

function test_queue()
    @testset for f in [Julio.channel, Julio.queue]
        test_queue(f)
    end
end

function test_queue(f)
    fst = Ref(0)
    snd = Ref(0)
    ie, oe = f(Int)
    try
        Julio.withtaskgroup() do tg
            Julio.spawn!(tg) do
                put!(ie, 111)
                put!(ie, 222)
            end
            Julio.spawn!(tg) do
                fst[] = take!(oe)
                snd[] = take!(oe)
            end
        end
    finally
        close(ie)
        close(oe)
    end
    @test (fst[], snd[]) == (111, 222)
end

function test_stack()
    fst = Ref(0)
    snd = Ref(0)
    begin
        ie, oe = Julio.stack(Int)
        try
            put!(ie, 111)
            put!(ie, 222)
        finally
            close(ie)
        end
        try
            fst[] = take!(oe)
            snd[] = take!(oe)
        finally
            close(oe)
        end
    end
    @test (fst[], snd[]) == (222, 111)
end

function test_stack_iterate(; nrepeat = 100, kwargs...)
    @testset for trial in 1:nrepeat
        check_stack_iterate()
    end
end

function check_stack_iterate(; nitems = 100, kwargs...)
    Julio.withtaskgroup() do tg
        ie, oe = Julio.stack(Int)
        Julio.spawn!(tg) do
            try
                for i in 1:nitems
                    put!(ie, i)
                end
            finally
                close(ie)
            end
        end
        try
            received = collect(oe)
            sort!(received)
            @test length(received) == nitems
            @test received == 1:nitems
        finally
            close(oe)
        end
    end
end

function test_queue_iterate()
    @testset for f in [Julio.channel, Julio.queue]
        test_queue_iterate(f)
    end
end

function test_queue_iterate(f; nrepeat = 100, kwargs...)
    @testset for trial in 1:nrepeat
        check_queue_iterate(f; kwargs...)
    end
end

function check_queue_iterate(f; nitems = 100)
    Julio.withtaskgroup() do tg
        ie, oe = f(Int)
        Julio.spawn!(tg) do
            try
                for i in 1:nitems
                    put!(ie, i)
                end
            finally
                close(ie)
            end
        end
        try
            received = collect(oe)
            @test length(received) == nitems
            @test received == 1:nitems
        finally
            close(oe)
        end
    end
end

function test_any_type_blocking()
    @testset for f in [Julio.stack, Julio.queue]
        test_any_type_blocking(f)
    end
end

function test_any_type_blocking(f)
    ie, oe = f()
    put!(ie, 111)
    @test take!(oe) == 111
end

function test_any_type_async()
    @testset for f in [Julio.channel, Julio.stack, Julio.queue]
        test_any_type_async(f)
    end
end

function test_any_type_async(f)
    Julio.withtaskgroup() do tg
        ie, oe = f()
        Julio.spawn!(tg) do
            try
                put!(ie, 111)
            finally
                close(ie)
            end
        end
        try
            @test take!(oe) == 111
        finally
            close(oe)
        end
    end
end

# Like `test_channel_open_many_scoped` but using the "less strict" API:
function test_channel_open_many_scoped2()
    send_endpoint, receive_endpoint = Julio.channel()
    try
        local task
        Julio.withtaskgroup() do tg0
            task = Julio.spawn!(tg0) do
                sort!(collect(receive_endpoint))
            end
            try
                Julio.withtaskgroup() do tg1
                    for i in 1:10
                        Julio.spawn!(tg1) do
                            put!(send_endpoint, i)
                        end
                    end
                end
            finally
                close(send_endpoint)
            end
        end
        @test fetch(task) == 1:10
    finally
        close(send_endpoint)
        close(receive_endpoint)
    end
end

function sample_method_hint(io::IO, f, args...)
    @nospecialize f args
    Julio.Internal.on_channel_handle_method_error(io, MethodError(f, args), map(typeof, args), nothing)
end

function sample_method_hints(io::IO = stdout)
    send_endpoint, receive_endpoint = Julio.channel()

    printstyled(io, "Trying to take from a send endpointr:"; bold = true)
    println(io)
    sample_method_hint(io, take!, send_endpoint)

    printstyled(io, "Trying to put on a receive endpoint:"; bold = true)
    println(io)
    sample_method_hint(io, put!, receive_endpoint)
end

function test_method_hints()
    str = sprint(sample_method_hints)
    @test "take! requires" ⊏ str
    @test "put! requires" ⊏ str
end

end  # module


text:
using Test, MaskRCNN, Pkg, ArgParse, FileIO, Knet
Pkg.build("Knet")
Pkg.add("Libdl")
using Libdl
push!(Libdl.DL_LOAD_PATH,"/usr/lib")

@testset "MaskRCNN" begin

    @time include("test_utils.jl")
    @time include("test_resnet.jl")
    @time include("test_rpn.jl")
    @time include("test_fpn.jl")
    @time include("test_roi_align.jl")
    @time include("test_mrcnn.jl")

end


text:
using Makie

mesh([(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color = [:red, :green, :blue], shading = false)

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
import JuLIP.Potentials: @pot, @D, evaluate, evaluate_d, PairPotential, @analytic

@pot type Morseold <: PairPotential
   e0::Float64
   A::Float64
   r0::Float64
end
evaluate(p::Morseold, r) = p.e0 * (exp(-2*p.A*(r/p.r0-1.0)) - 2.0*exp(-p.A*(r/p.r0-1.0)))
evaluate_d(p::Morseold, r) = -2.0*p.e0*p.A/p.r0*(exp(-2*p.A*(r/p.r0-1.0)) - exp(-p.A*(r/p.r0-1.0)))

const e0 = 0.99
const r0 = 1.05
const A = 4.1

morse = @analytic( r -> e0 * (exp(-2*A*(r/r0-1.0)) - 2.0*exp(-A*(r/r0-1.0))) )
@show typeof(morse)
morseold = Morseold(e0, A, r0)

rr = collect(linspace(0.9, 2.1, 100))
morse_r = morse.(rr)
morseold_r = morseold.(rr)
dmorse_r = [(@D morse(r)) for r in rr]
dmorseold_r = [ (@D morseold(r)) for r in rr ]

println("Check consistency of hand-coded and analytic Morse potentials...")
@test vecnorm(morse_r - morseold_r, Inf) < 1e-12
@test vecnorm(dmorse_r - dmorseold_r, Inf) < 1e-12

function test(N, p)
   r = 1.234
   s = 0.0
   for n = 1:N
      s += p(r)
   end
   return s
end

function testgrad(N, p)
   r = 1.234
   s = 0.0
   for n = 1:N
      s += @D p(r)
   end
   return s
end

test(10, morse);
test(10, morseold);
testgrad(10, morse);
testgrad(10, morseold);

println("1M evaluations of Analytic Potential")
@time test(1_000_000, morse)
println("1M evaluations of old Potential")
@time test(1_000_000, morseold)
println("1M ∇ evaluations of Analytic Potential")
@time testgrad(1_000_000, morse)
println("1M ∇ evaluations of old Potential")
@time testgrad(1_000_000, morseold)


text:
# Does not test leafsize
# Does not test different metrics
import Distances.evaluate

@testset "knn" begin
    @testset "metric" for metric in metrics
        @testset "tree type" for TreeType in trees_with_brute
            # 8 node rectangle
            data = [0.0 0.0 0.0 0.5 0.5 1.0 1.0 1.0;
                    0.0 0.5 1.0 0.0 1.0 0.0 0.5 1.0]

            tree = TreeType(data, metric; leafsize=2)

            idxs, dists = knn(tree, [0.8, 0.8], 1)
            @test idxs[1] == 8 # Should be closest to top right corner
            @test evaluate(metric, [0.2, 0.2], zeros(2)) ≈ dists[1]

            idxs, dists = knn(tree, [0.1, 0.8], 3, true)
            @test idxs == [3, 2, 5]

            idxs, dists = knn(tree, [0.8 0.1; 0.8 0.8], 1, true)
            @test idxs[1][1] == 8
            @test idxs[2][1] == 3

            idxs, dists = knn(tree, [SVector{2, Float64}(0.8,0.8), SVector{2, Float64}(0.1,0.8)], 1, true)
            @test idxs[1][1] == 8
            @test idxs[2][1] == 3

            idxs, dists = knn(tree, [1//10, 8//10], 3, true)
            @test idxs == [3, 2, 5]

            @test_throws ArgumentError knn(tree, [0.1, 0.8], 10) # k > n_points
            @test_throws ArgumentError knn(tree, [0.1], 10) # n_dim != trees dim

        end
    end
end

@testset "knn skip" begin
    @testset "tree type" for TreeType in trees_with_brute
        data = rand(2, 1000)
        tree = TreeType(data)

        idxs, dists = knn(tree, data[:, 10], 2, true)
        first_idx = idxs[1]
        second_idx = idxs[2]

        idxs, dists = knn(tree, data[:, 10], 2, true, i -> i == first_idx)
        @test idxs[1] == second_idx
    end
end


text:
# # Example: Blowfly Model
# Likelihood-free inference for the blow-fly model was introduced by [Simon N.
# Wood](http://dx.doi.org/10.1038/nature09319). We model here the discrete time
# stochastic dynamics of the size ``N`` of an adult blowfly population as given in [section 1.2.3 of the supplementary
# information](https://static-content.springer.com/esm/art%3A10.1038%2Fnature09319/MediaObjects/41586_2010_BFnature09319_MOESM302_ESM.pdf).
# ```math
# N_{t+1} = P N_{t-\tau}\exp(-N_{t-\tau}/N_0)e_t + N_t\exp(-\delta \epsilon_t)
# ```
# where ``eₜ`` and ``ϵₜ`` are independent Gamma random deviates with
# mean 1 and variance ``σp²`` and ``σd²``, respectively.
using Distributions, StatsBase, LikelihoodfreeInference
Base.@kwdef struct BlowFlyModel
    burnin::Int = 50
    T::Int = 1000
end
function (m::BlowFlyModel)(P, N₀, σd, σp, τ, δ)
    p1 = Gamma(1/σp^2, σp^2)
    p2 = Gamma(1/σd^2, σd^2)
    T = m.T + m.burnin + τ
    N = fill(180., T)
    for t in τ+1:T-1
        N[t+1] = P * N[t-τ] * exp(-N[t-τ]/N₀)*rand(p1) + N[t]*exp(-δ*rand(p2))
    end
    N[end-m.T+1:end]
end

# Let us plot four realizations from this model with the same parameters.
using StatsPlots
gr()
m = BlowFlyModel()
plot([plot(m(29, 260, .6, .3, 7, .2),
           xlabel = "t", ylabel = "N", legend = false) for _ in 1:4]...,
     layout = (2, 2))

# To compare different realizations we will use histogram summary statistics.
# In the literature one finds also other summary statistics for this data.
summary_statistics(N) = fit(Histogram, N, 140:16:16140).weights

# We will use a normal prior on log-transformed parameters.
function parameter(logparams)
    lP, lN₀, lσd, lσp, lτ, lδ = logparams
    (P = round(exp(2 + 2lP)),
    N₀ = round(exp(4 + .5lN₀)),
    σd = exp(-.5 + lσd),
    σp = exp(-.5 + lσp),
    τ = round(Int, max(1, min(500, exp(2 + lτ)))),
    δ = exp(-1 + .4lδ))
end
(m::BlowFlyModel)(logparams) = m(parameter(logparams)...)
target(m::BlowFlyModel) = [(log(29) - 2)/2,
                           (log(260) - 4)*2,
                           log(.6) + .5,
                           log(.3) + .5,
                           log(7) - 2,
                           (log(.2) + 1)/.4]
lower(m::BlowFlyModel) = fill(-5., 6)
upper(m::BlowFlyModel) = fill(5., 6)
prior = TruncatedMultivariateNormal(zeros(6), ones(6),
                                    lower = lower(m), upper = upper(m))

# Let us now generate some target data.
model = BlowFlyModel()
x0 = target(model)
data = summary_statistics(model(x0))

# ## Adaptive SMC
smc = AdaptiveSMC(prior = prior)
result = run!(smc, x -> summary_statistics(model(x)), data,
              maxfevals = 2*10^5, verbose = false)
using PrettyTables
pretty_table([[keys(parameter(zeros(6)))...] quantile(smc, .05) median(smc) mean(smc) x0 quantile(smc, .95)],
             ["names", "5%", "median", "mean", "actual", "95%"],
             formatter = ft_printf("%10.3f"))
#-
histogram(smc)
#-
corrplot(smc)

# ## KernelABC
k = KernelABC(prior = prior, delta = 1e-1, K = 10^3, kernel = Kernel())
result = run!(k, x -> summary_statistics(model(x)), data)
pretty_table([[keys(parameter(zeros(6)))...] quantile(k, .05) median(k) mean(k) x0 quantile(k, .95)],
             ["names", "5%", "median", "mean", "actual", "95%"],
             formatter = ft_printf("%10.3f"))
#-
histogram(k)

# ## Kernel Recursive ABC (with callback)
k = KernelRecursiveABC(prior = prior,
                       K = 100,
                       delta = 1e-3,
                       kernel = Kernel(bandwidth = Bandwidth(heuristic = MedianHeuristic(2^3))),
                       kernelx = Kernel());
# We will use a callback here to show how the estimated parameters evolves.
using LinearAlgebra
res_krabc = run!(k, x -> summary_statistics(model(x)), data,
                 maxfevals = 1300,
                 verbose = true,
                 callback = () -> @show norm(k.theta - x0)/norm(x0))


text:
enum Color {
  RED,
  GREEN,
  BLUE
};

typedef struct Palette_t{
  Color color;
} * Palette;

int main(){
  Color color = Color.RED;
  if(color == Color.RED){
    printString("red");
  } else{
    printString("not red");
  }
  Palette p = new Palette_t;
  p->color = Color.GREEN;
  if(p->color == Color.GREEN){
    printString("green");
  } else{
    printString("not green");
  }
  return 0;
}

max_stars_repo_name: fredefox/javalette

max_issues_repo_name: fredefox/javalette

max_forks_repo_name: fredefox/javalette