text:
ENV["PKG_CONFIG_PATH"] = "/Users/dc/anaconda/envs/python35/lib/pkgconfig"

using OpenCV
using Images, ImageView
using Cxx

function opencv_to_image(img_opencv)

    converted_image = zeros(Float16, (3, rows(img_opencv), cols(img_opencv)));

    for i = 1:size(converted_image, 2)
        for j = 1:size(converted_image, 3)
            pixel_value = @cxx at_v3b(img_opencv, i, j)
            converted_image[:, i, j] = map(x -> Int(at(pixel_value, x)), [2, 1, 0]) ./ 255
        end
    end

    return converted_image
end

# loading an image
filename = joinpath(pwd(), "sample-images", "cat-3352842_640.jpg");
img_opencv = imread(filename);

# convert to Julia images
img_images = opencv_to_image(img_opencv);
imshow(img_images)


text:
using Glob;
using DelimitedFiles;
using Quadmath;
using DecFP;

if length(ARGS) != 3
  println("usage: julia statistical_analysis_mcmc.jl <outfile> <indir> <pattern>");
  exit(1);
end

outfile = open(ARGS[1], "w");
indir = ARGS[2];
pattern = Glob.GlobMatch(ARGS[3]);

data_series = Dict();
for infile in readdir(pattern, indir)
  for line in readlines(infile)
    var, val = map(strip, split(line, "="));
    val = eval(Meta.parse(val));
    if haskey(data_series, var)
      push!(data_series[var], val);
    else
      data_series[var] = [val];
    end
  end
end

avgs = Dict();
vars = Dict();
std_norms = Dict();
for (k, v) in data_series
  avgs[k] = sum(v) / length(v);
  vars[k] = sum(map(x -> (x - avgs[k]).^2, v)) / length(v);
  std_norms[k] = map(sqrt, vars[k]) ./ avgs[k];
end
for k in keys(avgs)
  @info "$k: μ = $(avgs[k]); σ^2 = $(vars[k]); σ / μ = $(std_norms[k])";
end

close(outfile);

ext: jl

max_stars_repo_name: grasingerm/polymer-stats

max_issues_repo_name: grasingerm/polymer-stats

max_forks_repo_name: grasingerm/polymer-stats


text:
# Issue #3582 - check that all versions of a package newer than the
# grandfathered list below are at least minpkgver and furthermore have a
# requires file listing a minimum Julia version that is at least minjuliaver
maxver_list_3582 = Dict([ # List of grandfathered packages
    ("ACME", v"0.1.2"),
    ("ASCIIPlots", v"0.0.3"),
    ("AWS", v"0.1.13"),
    ("AbstractDomains", v"0.0.3"),
    ("ActiveAppearanceModels", v"0.1.2"),
    ("AffineTransforms", v"0.1.3"),
    ("AmplNLWriter", v"0.0.3"),
    ("AndorSIF", v"0.0.3"),
    ("AnsiColor", v"0.0.2"),
    ("AppConf", v"0.1.1"),
    ("AppleAccelerate", v"0.1.1"),
    ("ApproxFun", v"0.0.8"),
    ("Arbiter", v"0.0.2"),
    ("Arduino", v"0.1.2"),
    ("ArgParse", v"0.3.1"),
    ("ArrayViews", v"0.6.4"),
    ("Arrowhead", v"0.0.1"),
    ("Atom", v"0.1.1"),
    ("AudioIO", v"0.1.1"),
    ("Augur", v"0.1.1"),
    ("AutoHashEquals", v"0.0.10"),
    ("AutoTypeParameters", v"0.0.3"),
    ("Autoreload", v"0.2.0"),
    ("AverageShiftedHistograms", v"0.2.2"),
    ("AxisAlgorithms", v"0.1.4"),
    ("BDF", v"0.1.2"),
    ("BEncode", v"0.1.1"),
    ("BIGUQ", v"0.1.0"),
    ("BSplines", v"0.0.3"),
    ("BackpropNeuralNet", v"0.0.3"),
    ("BaseTestDeprecated", v"0.1.0"),
    ("BayesNets", v"0.2.1"),
    ("BayesianDataFusion", v"1.1.0"),
    ("Bebop", v"0.0.1"),
    ("Benchmark", v"0.1.0"),
    ("BenchmarkLite", v"0.1.2"),
    ("Bezier", v"0.0.1"),
    ("BinDeps", v"0.3.21"),
    ("Bio", v"0.1.0"),
    ("BioSeq", v"0.4.0"),
    ("BiomolecularStructures", v"0.0.1"),
    ("Biryani", v"0.2.0"),
    ("BlackBoxOptim", v"0.1.3"),
    ("Blink", v"0.1.5"),
    ("Blocks", v"0.1.0"),
    ("BloomFilters", v"0.1.1"),
    ("Blosc", v"0.1.7"),
    ("BlossomV", v"0.0.3"),
    ("Bokeh", v"0.2.0"),
    ("Boltzmann", v"0.3.0"),
    ("Bootstrap", v"0.3.3"),
    ("BoundingBoxes", v"0.1.0"),
    ("Brim", v"1.1.0"),
    ("Brownian", v"0.0.1"),
    ("BufferedStreams", v"0.0.2"),
    ("BusinessDays", v"0.0.5"),
    ("CLBLAS", v"0.1.0"),
    ("CLFFT", v"0.1.0"),
    ("CPLEX", v"0.0.19"),
    ("CPUTime", v"0.0.5"),
    ("CRC", v"1.1.1"),
    ("CRC32", v"0.0.2"),
    ("CRF", v"0.1.1"),
    ("CRlibm", v"0.1.0"),
    ("CUBLAS", v"0.0.2"),
    ("CUDA", v"0.1.0"),
    ("CUDArt", v"0.2.3"),
    ("CUDNN", v"0.3.0"),
    ("CUFFT", v"0.0.4"),
    ("CURAND", v"0.0.4"),
    ("CUSOLVER", v"0.0.1"),
    ("CUSPARSE", v"0.3.1"),
    ("Cairo", v"0.2.35"),
    ("Calculus", v"0.1.15"),
    ("Calendar", v"0.4.3"),
    ("Cartesian", v"0.3.0"),
    ("CasaCore", v"0.0.3"),
    ("Catalan", v"0.0.3"),
    ("CauseMap", v"0.0.3"),
    ("Cbc", v"0.1.8"),
    ("CellularAutomata", v"0.1.2"),
    ("ChainedVectors", v"0.0.0"),
    ("Changepoints", v"0.1.0"),
    ("ChaosCommunications", v"0.0.1"),
    ("ChemicalKinetics", v"0.1.0"),
    ("Chipmunk", v"0.0.5"),
    ("Church", v"0.0.1"),
    ("CirruParser", v"0.0.2"),
    ("Clang", v"0.1.0"),
    ("Cliffords", v"0.2.3"),
    ("Clp", v"0.1.1"),
    ("ClusterManagers", v"0.0.5"),
    ("Clustering", v"0.5.0"),
    ("CodeTools", v"0.1.0"),
    ("Codecs", v"0.2.0"),
    ("CoinOptServices", v"0.0.8"),
    ("Color", v"0.4.8"),
    ("ColorBrewer", v"0.2.1"),
    ("ColorTypes", v"0.1.7"),
    ("ColorVectorSpace", v"0.0.5"),
    ("Colors", v"0.5.4"),
    ("Combinatorics", v"0.1.2"),
    ("CommonCrawl", v"0.0.1"),
    ("Compat", v"0.8.8"),
    ("CompilerOptions", v"0.1.0"),
    ("Compose", v"0.3.18"),
    ("CompressedSensing", v"0.0.2"),
    ("Conda", v"0.2.5"),
    ("ConfParser", v"0.0.8"),
    ("ConfidenceWeighted", v"0.0.2"),
    ("ConjugatePriors", v"0.1.2"),
    ("ConnectSDK", v"0.1.5"),
    ("ContinuedFractions", v"0.0.0"),
    ("Contour", v"0.0.8"),
    ("Convex", v"0.1.0"),
    ("CoreNLP", v"0.1.0"),
    ("Cosmology", v"0.1.4"),
    ("CovarianceMatrices", v"0.0.5"),
    ("Coverage", v"0.2.3"),
    ("CoverageBase", v"0.0.3"),
    ("Cpp", v"0.1.0"),
    ("CrossDecomposition", v"0.0.1"),
    ("Crypto", v"0.0.1"),
    ("Cubature", v"1.1.0"),
    ("Curl", v"0.0.3"),
    ("CurveFit", v"0.0.1"),
    ("DASSL", v"0.0.4"),
    ("DCEMRI", v"0.1.2"),
    ("DICOM", v"0.0.1"),
    ("DReal", v"0.0.2"),
    ("DSGE", v"0.1.1"),
    ("DSP", v"0.0.11"),
    ("DWARF", v"0.0.0"),
    ("DataArrays", v"0.2.20"),
    ("DataFrames", v"0.6.10"),
    ("DataFramesMeta", v"0.1.0"),
    ("DataStructures", v"0.3.14"),
    ("Dates", v"0.4.4"),
    ("Datetime", v"0.1.7"),
    ("Debug", v"0.1.6"),
    ("DecFP", v"0.1.1"),
    ("Decimals", v"0.0.2"),
    ("DecisionTree", v"0.4.2"),
    ("DeclarativePackages", v"0.1.2"),
    ("DevIL", v"0.3.0"),
    ("Devectorize", v"0.4.2"),
    ("DictFiles", v"0.1.0"),
    ("DictUtils", v"0.0.2"),
    ("Dierckx", v"0.1.9"),
    ("Digits", v"0.1.4"),
    ("DimensionalityReduction", v"0.1.2"),
    ("DirichletProcessMixtures", v"0.0.1"),
    ("DiscreteFactor", v"0.0.0"),
    ("Discretizers", v"0.0.2"),
    ("Distance", v"0.5.1"),
    ("Distances", v"0.2.2"),
    ("DistributedArrays", v"0.1.5"),
    ("Distributions", v"0.8.10"),
    ("Diversity", v"0.2.8"),
    ("DocOpt", v"0.1.3"),
    ("Docile", v"0.5.23"),
    ("Docker", v"0.0.1"),
    ("Dopri", v"0.1.2"),
    ("DoubleDouble", v"0.1.0"),
    ("Drawing", v"0.1.4"),
    ("DualNumbers", v"0.1.5"),
    ("DustExtinction", v"0.1.0"),
    ("Dynare", v"0.0.1"),
    ("ECOS", v"0.5.3"),
    ("EEG", v"0.0.1"),
    ("ELF", v"0.0.0"),
    ("ERFA", v"0.1.2"),
    ("EcologicalNetwork", v"1.0.1"),
    ("EconDatasets", v"0.0.2"),
    ("ElasticFDA", v"0.1.0"),
    ("Elliptic", v"0.2.0"),
    ("Elly", v"0.0.4"),
    ("EmpiricalRisks", v"0.2.4"),
    ("Equations", v"0.1.1"),
    ("Escher", v"0.2.1"),
    ("Etcd", v"0.0.1"),
    ("Evolutionary", v"0.1.2"),
    ("EvolvingGraphs", v"0.0.9"),
    ("Example", v"0.4.1"),
    ("ExcelReaders", v"0.3.1"),
    ("Expect", v"0.1.2"),
    ("ExpressionUtils", v"0.0.0"),
    ("ExtremelyRandomizedTrees", v"0.1.0"),
    ("FITSIO", v"0.8.4"),
    ("FLANN", v"0.0.4"),
    ("FMIndexes", v"0.0.1"),
    ("FTPClient", v"0.1.1"),
    ("FaceDatasets", v"0.1.4"),
    ("FactCheck", v"0.4.3"),
    ("FactorModels", v"0.0.2"),
    ("Faker", v"0.0.3"),
    ("FastAnonymous", v"0.3.2"),
    ("FastArrayOps", v"0.1.0"),
    ("FastGaussQuadrature", v"0.0.3"),
    ("FastaIO", v"0.1.5"),
    ("FileFind", v"0.0.0"),
    ("FileIO", v"0.0.6"),
    ("FinancialMarkets", v"0.1.1"),
    ("FiniteStateMachine", v"0.1.1"),
    ("FixedEffectModels", v"0.2.2"),
    ("FixedPoint", v"0.0.1"),
    ("FixedPointNumbers", v"0.0.12"),
    ("FixedSizeArrays", v"0.0.7"),
    ("Fixtures", v"0.0.2"),
    ("Fontconfig", v"0.0.2"),
    ("Formatting", v"0.1.5"),
    ("ForwardDiff", v"0.1.2"),
    ("FreeType", v"1.0.3"),
    ("FunctionalCollections", v"0.1.3"),
    ("FunctionalData", v"0.1.0"),
    ("FunctionalDataUtils", v"0.1.0"),
    ("FunctionalUtils", v"0.0.0"),
    ("GARCH", v"0.1.2"),
    ("GLAbstraction", v"0.0.6"),
    ("GLFW", v"1.0.0-alpha.7"),
    ("GLM", v"0.4.8"),
    ("GLMNet", v"0.0.5"),
    ("GLPK", v"0.2.17"),
    ("GLPKMathProgInterface", v"0.1.16"),
    ("GLPlot", v"0.0.5"),
    ("GLText", v"0.0.4"),
    ("GLUT", v"0.4.0"),
    ("GLVisualize", v"0.0.2"),
    ("GLWindow", v"0.0.6"),
    ("GR", v"0.14.0"),
    ("GSL", v"0.2.0"),
    ("GZip", v"0.2.20"),
    ("Gadfly", v"0.3.18"),
    ("Gaston", v"0.0.0"),
    ("GaussQuadrature", v"0.2.0"),
    ("GaussianMixtures", v"0.0.12"),
    ("GaussianProcesses", v"0.1.4"),
    ("GeneticAlgorithms", v"0.0.3"),
    ("GeoIP", v"0.2.2"),
    ("GeoInterface", v"0.0.1"),
    ("GeoJSON", v"0.0.4"),
    ("GeoStats", v"0.0.2"),
    ("GeoStatsImages", v"0.0.2"),
    ("Geodesy", v"0.0.1"),
    ("GeometricalPredicates", v"0.0.6"),
    ("GeometryTypes", v"0.0.3"),
    ("GetC", v"1.1.1"),
    ("Gettext", v"0.1.0"),
    ("GibbsSeaWater", v"0.0.4"),
    ("GitHub", v"1.0.3"),
    ("Glob", v"1.0.2"),
    ("GnuTLS", v"0.0.5"),
    ("GoogleCharts", v"0.0.7"),
    ("GradientBoost", v"0.0.1"),
    ("GraphCentrality", v"0.1.0"),
    ("GraphLayout", v"0.2.0"),
    ("GraphMatrices", v"0.1.0"),
    ("GraphViz", v"0.0.4"),
    ("Graphics", v"0.1.5"),
    ("Graphs", v"0.6.0"),
    ("GreatCircle", v"0.0.1"),
    ("Grid", v"0.4.0"),
    ("Gtk", v"0.9.3"),
    ("GtkUtilities", v"0.0.7"),
    ("Gumbo", v"0.1.2"),
    ("Gurobi", v"0.1.31"),
    ("HDF5", v"0.6.6"),
    ("HDFS", v"0.1.0"),
    ("HTTP", v"0.0.2"),
    ("HTTPClient", v"0.1.6"),
    ("Hadamard", v"0.1.2"),
    ("HarwellRutherfordBoeing", v"0.0.1"),
    ("Helpme", v"0.0.13"),
    ("HexEdit", v"0.0.6"),
    ("Hexagons", v"0.0.4"),
    ("Hiccup", v"0.0.3"),
    ("Hinton", v"0.1.1"),
    ("Homebrew", v"0.3.5"),
    ("HopfieldNets", v"0.0.0"),
    ("HttpCommon", v"0.2.5"),
    ("HttpParser", v"0.1.1"),
    ("HttpServer", v"0.1.5"),
    ("Humanize", v"0.4.0"),
    ("Hwloc", v"0.3.0"),
    ("HyperDualNumbers", v"0.1.7"),
    ("HyperLogLog", v"0.0.0"),
    ("HypothesisTests", v"0.2.10"),
    ("ICU", v"0.4.4"),
    ("IDRsSolver", v"0.1.3"),
    ("IDXParser", v"0.1.0"),
    ("IJulia", v"1.1.10"),
    ("IJuliaPortrayals", v"0.0.4"),
    ("IPNets", v"0.2.0"),
    ("IPPCore", v"0.2.1"),
    ("IPPDSP", v"0.0.1"),
    ("IProfile", v"0.3.1"),
    ("ImageMagick", v"0.0.1"),
    ("ImageQuilting", v"0.2.3"),
    ("ImageView", v"0.1.20"),
    ("Images", v"0.4.50"),
    ("ImagineFormat", v"0.0.1"),
    ("Immerse", v"0.0.8"),
    ("ImmutableArrays", v"0.0.12"),
    ("ImplicitEquations", v"0.0.3"),
    ("IndependentRandomSequences", v"0.0.1"),
    ("IndexableBitVectors", v"0.1.0"),
    ("IndexedArrays", v"0.1.0"),
    ("InformedDifferentialEvolution", v"0.1.0"),
    ("IniFile", v"0.2.5"),
    ("InplaceOps", v"0.0.5"),
    ("Instruments", v"0.0.1"),
    ("IntArrays", v"0.0.1"),
    ("IntModN", v"0.0.2"),
    ("Interact", v"0.2.1"),
    ("InterestRates", v"0.0.2"),
    ("Interfaces", v"0.0.4"),
    ("Interpolations", v"0.3.3"),
    ("IntervalTrees", v"0.0.5"),
    ("Ipopt", v"0.1.18"),
    ("Isotonic", v"0.0.1"),
    ("IterationManagers", v"0.0.1"),
    ("IterativeSolvers", v"0.2.1"),
    ("Iterators", v"0.1.10"),
    ("Ito", v"0.0.2"),
    ("JDBC", v"0.0.3"),
    ("JFVM", v"0.1.0"),
    ("JLD", v"0.5.9"),
    ("JLDArchives", v"0.0.8"),
    ("JPLEphemeris", v"0.2.1"),
    ("JSON", v"0.6.1"),
    ("JWAS", v"0.0.3"),
    ("Jacobi", v"0.2.0"),
    ("Jags", v"0.2.0"),
    ("JavaCall", v"0.3.5"),
    ("JellyFish", v"0.0.1"),
    ("Jewel", v"1.0.8"),
    ("JointMoments", v"0.2.5"),
    ("JuMP", v"0.10.3"),
    ("JuMPChance", v"0.2.2"),
    ("JuMPeR", v"0.2.1"),
    ("JudyDicts", v"0.0.0"),
    ("JuliaFEM", v"0.0.1"),
    ("JuliaParser", v"0.6.3"),
    ("JuliaWebAPI", v"0.0.6"),
    ("JuliaWebRepl", v"0.0.0"),
    ("JulieTest", v"0.0.2"),
    ("Jumos", v"0.2.1"),
    ("KDTrees", v"0.5.13"),
    ("KLDivergence", v"0.0.0"),
    ("KNITRO", v"0.0.10"),
    ("KShiftsClustering", v"0.1.0"),
    ("KernSmooth", v"0.0.3"),
    ("KernelDensity", v"0.2.0"),
    ("KernelEstimator", v"0.1.7"),
    ("KrylovMethods", v"0.1.0"),
    ("LARS", v"0.0.3"),
    ("LIBSVM", v"0.0.1"),
    ("LLLplus", v"0.1.1"),
    ("LMDB", v"0.0.4"),
    ("LNR", v"0.0.2"),
    ("LRUCache", v"0.0.1"),
    ("LaTeX", v"0.1.0"),
    ("LaTeXStrings", v"0.1.6"),
    ("LambertW", v"0.0.4"),
    ("Languages", v"0.0.5"),
    ("Lasso", v"0.0.4"),
    ("Lazy", v"0.10.1"),
    ("LazySequences", v"0.1.0"),
    ("LeastSquaresOptim", v"0.0.1"),
    ("Lens", v"0.0.3"),
    ("LevelDB", v"1.0.1"),
    ("Levenshtein", v"0.0.2"),
    ("Lexicon", v"0.1.18"),
    ("LibBSON", v"0.1.7"),
    ("LibCURL", v"0.1.6"),
    ("LibExpat", v"0.1.4"),
    ("LibGEOS", v"0.0.4"),
    ("LibGit2", v"0.3.8"),
    ("LibHealpix", v"0.0.1"),
    ("LibTrading", v"0.0.1"),
    ("Libz", v"0.0.2"),
    ("LifeTable", v"0.0.2"),
    ("LightGraphs", v"0.3.7"),
    ("LightXML", v"0.3.0"),
    ("LineEdit", v"0.0.1"),
    ("LinearLeastSquares", v"0.0.10"),
    ("LinearMaps", v"0.1.1"),
    ("LinearOperators", v"0.1.0"),
    ("LinearResponseVariationalBayes", v"0.0.1"),
    ("LinguisticData", v"0.0.2"),
    ("Lint", v"0.1.69"),
    ("Loess", v"0.0.7"),
    ("LogParser", v"0.2.0"),
    ("Logging", v"0.2.0"),
    ("Lora", v"0.5.0"),
    ("Loss", v"0.0.1"),
    ("LowDimNearestNeighbors", v"0.0.1"),
    ("LowRankModels", v"0.1.2"),
    ("LsqFit", v"0.0.2"),
    ("Lumberjack", v"1.0.1"),
    ("Lumira", v"0.0.2"),
    ("MAT", v"0.2.14"),
    ("MATLAB", v"0.2.4"),
    ("MATLABCluster", v"0.0.1"),
    ("MCMC", v"0.3.0"),
    ("MDCT", v"0.0.2"),
    ("MDPs", v"0.1.1"),
    ("MFCC", v"0.1.1"),
    ("MIDI", v"0.0.3"),
    ("MIToS", v"0.1.0"),
    ("MLBase", v"0.5.3"),
    ("MLKernels", v"0.0.3"),
    ("MNIST", v"0.0.2"),
    ("MPFI", v"0.0.1"),
    ("MPI", v"0.3.2"),
    ("MUMPS", v"0.0.2"),
    ("MachineLearning", v"0.0.3"),
    ("MacroTools", v"0.2.0"),
    ("Mads", v"0.1.0"),
    ("Mamba", v"0.6.3"),
    ("Mandrill", v"0.1.0"),
    ("ManifoldLearning", v"0.1.0"),
    ("MapLight", v"0.0.2"),
    ("Markdown", v"0.3.0"),
    ("MarketData", v"0.3.6"),
    ("MarketTechnicals", v"0.4.1"),
    ("Match", v"0.1.4"),
    ("MathProgBase", v"0.3.19"),
    ("Mathematica", v"0.2.0"),
    ("MatlabCompat", v"0.1.2"),
    ("MatpowerCases", v"0.3.2"),
    ("MatrixDepot", v"0.4.3"),
    ("MatrixMarket", v"0.0.1"),
    ("MatrixNetworks", v"0.0.1"),
    ("MbedTLS", v"0.2.0"),
    ("MeCab", v"0.1.7"),
    ("Meddle", v"0.0.6"),
    ("Media", v"0.1.1"),
    ("MelGeneralizedCepstrums", v"0.0.1"),
    ("Memcache", v"0.0.2"),
    ("Memoize", v"0.0.1"),
    ("MeshIO", v"0.0.2"),
    ("Meshes", v"0.1.5"),
    ("Meshing", v"0.0.0"),
    ("MessageUtils", v"0.0.2"),
    ("MetaTools", v"0.0.1"),
    ("MetadataTools", v"0.2.2"),
    ("Metis", v"0.0.10"),
    ("Millboard", v"0.0.6"),
    ("Mimi", v"0.0.2"),
    ("MinimalPerfectHashes", v"0.1.2"),
    ("MixedModels", v"0.4.0"),
    ("MixtureModels", v"0.2.0"),
    ("Mocha", v"0.1.2"),
    ("Mocking", v"0.0.1"),
    ("ModernGL", v"0.0.8"),
    ("MolecularDynamics", v"0.1.3"),
    ("Monads", v"0.0.0"),
    ("Mongo", v"0.1.5"),
    ("Mongrel2", v"0.0.0"),
    ("Morsel", v"0.0.6"),
    ("Mosek", v"0.2.0"),
    ("MsgPack", v"0.0.5"),
    ("MsgPackRpcClient", v"0.0.0"),
    ("MultiNest", v"0.2.0"),
    ("MultiPoly", v"0.0.1"),
    ("Multirate", v"0.0.2"),
    ("MultivariateStats", v"0.2.2"),
    ("Munkres", v"0.1.0"),
    ("Murmur3", v"0.1.0"),
    ("Mustache", v"0.0.15"),
    ("MutableStrings", v"0.0.0"),
    ("Mux", v"0.1.1"),
    ("MySQL", v"0.0.2"),
    ("NBInclude", v"1.0.1"),
    ("NEOS", v"0.0.1"),
    ("NFFT", v"0.0.2"),
    ("NHST", v"0.0.2"),
    ("NIDAQ", v"0.0.2"),
    ("NIfTI", v"0.0.4"),
    ("NLopt", v"0.2.3"),
    ("NLreg", v"0.1.1"),
    ("NLsolve", v"0.5.0"),
    ("NMEA", v"0.0.6"),
    ("NMF", v"0.2.5"),
    ("NPZ", v"0.1.0"),
    ("NRRD", v"0.0.2"),
    ("NURBS", v"0.0.1"),
    ("NaNMath", v"0.1.1"),
    ("NaiveBayes", v"0.1.0"),
    ("Named", v"0.0.0"),
    ("NamedArrays", v"0.4.8"),
    ("NamedDimensions", v"0.0.3"),
    ("NamedTuples", v"0.0.3"),
    ("Nemo", v"0.4.1"),
    ("Neovim", v"0.0.2"),
    ("NetCDF", v"0.2.1"),
    ("Netpbm", v"0.0.2"),
    ("Nettle", v"0.2.4"),
    ("NeuralynxNCS", v"0.0.1"),
    ("NormalizeQuantiles", v"0.2.0"),
    ("NullableArrays", v"0.0.2"),
    ("NumFormat", v"0.0.4"),
    ("NumericExtensions", v"0.6.2"),
    ("NumericFuns", v"0.2.4"),
    ("OAuth", v"0.3.0"),
    ("OCCA", v"0.0.1"),
    ("ODBC", v"0.3.11"),
    ("ODE", v"0.2.1"),
    ("OEIS", v"0.0.2"),
    ("OIFITS", v"0.2.0"),
    ("OSC", v"0.0.1"),
    ("OSXNotifier", v"0.0.1"),
    ("OffsetArrays", v"0.1.3"),
    ("OnlineMoments", v"0.1.0"),
    ("OnlineStats", v"0.3.0"),
    ("OpenCL", v"0.3.6"),
    ("OpenFOAM", v"0.0.1"),
    ("OpenGL", v"2.0.3"),
    ("OpenSSL", v"0.0.0"),
    ("OpenSecrets", v"0.0.1"),
    ("OpenSlide", v"0.0.1"),
    ("OpenStreetMap", v"0.8.2"),
    ("Optim", v"0.4.4"),
    ("OptimPack", v"0.2.0"),
    ("Options", v"0.2.6"),
    ("Orchestra", v"0.0.5"),
    ("PAINTER", v"0.2.0"),
    ("PDMats", v"0.4.2"),
    ("PEGParser", v"0.1.2"),
    ("PGFPlots", v"1.2.2"),
    ("PGM", v"0.0.1"),
    ("PLX", v"0.0.5"),
    ("POMDPs", v"0.1.0"),
    ("PTools", v"0.0.0"),
    ("PValueAdjust", v"2.0.0"),
    ("Packing", v"0.0.4"),
    ("PairwiseListMatrices", v"0.1.1"),
    ("Pandas", v"0.2.0"),
    ("ParallelSparseMatMul", v"0.0.2"),
    ("Parameters", v"0.2.1"),
    ("Pardiso", v"0.0.2"),
    ("ParserCombinator", v"1.7.11"),
    ("Patchwork", v"0.2.2"),
    ("PatternDispatch", v"0.1.0"),
    ("Pcap", v"0.0.3"),
    ("PdbTool", v"0.1.0"),
    ("Pedigrees", v"0.0.1"),
    ("Permutations", v"0.0.1"),
    ("PhyloNetworks", v"0.0.1"),
    ("Phylogenetics", v"0.0.2"),
    ("PicoSAT", v"0.1.0"),
    ("PiecewiseAffineTransforms", v"0.2.0"),
    ("PiecewiseIncreasingRanges", v"0.0.4"),
    ("Pipe", v"0.0.3"),
    ("Playground", v"0.0.4"),
    ("Plotly", v"0.0.3"),
    ("Plots", v"0.4.2"),
    ("PolarFact", v"0.0.6"),
    ("Polyglot", v"0.0.1"),
    ("Polynomial", v"0.1.1"),
    ("Polynomials", v"0.0.6"),
    ("PowerSeries", v"0.1.14"),
    ("ProfileView", v"0.1.1"),
    ("ProgressMeter", v"0.2.3"),
    ("ProgressiveAligner", v"0.3.0"),
    ("ProjectTemplate", v"0.0.1"),
    ("ProjectiveDictionaryPairLearning", v"0.3.4"),
    ("PropertyGraph", v"0.1.0"),
    ("ProtoBuf", v"0.2.0"),
    ("PublicSuffix", v"0.0.2"),
    ("Push", v"0.0.1"),
    ("PyCall", v"1.2.0"),
    ("PyLexYacc", v"0.0.2"),
    ("PyPlot", v"2.1.1"),
    ("PySide", v"0.0.2"),
    ("QuDirac", v"0.1.3"),
    ("Quandl", v"0.5.4"),
    ("QuantEcon", v"0.3.0"),
    ("QuantumLab", v"0.0.1"),
    ("QuartzImageIO", v"0.0.2"),
    ("Quaternions", v"0.1.1"),
    ("QuickCheck", v"0.0.0"),
    ("QuickShiftClustering", v"0.1.0"),
    ("RCall", v"0.3.2"),
    ("RDF", v"0.0.1"),
    ("RDatasets", v"0.1.3"),
    ("REPL", v"0.0.2"),
    ("REPLCompletions", v"0.0.3"),
    ("RLEVectors", v"0.1.0"),
    ("RNGTest", v"1.0.0"),
    ("ROCAnalysis", v"0.0.1"),
    ("Rainflow", v"0.1.0"),
    ("RandomCorrelationMatrices", v"0.2.0"),
    ("RandomFerns", v"0.1.0"),
    ("RandomMatrices", v"0.1.0"),
    ("Ratios", v"0.0.4"),
    ("RdRand", v"0.0.0"),
    ("React", v"0.1.6"),
    ("Reactive", v"0.2.4"),
    ("Redis", v"0.0.2"),
    ("Reel", v"0.1.0"),
    ("Reexport", v"0.0.3"),
    ("RegERMs", v"0.0.2"),
    ("Regression", v"0.3.0"),
    ("Requests", v"0.3.3"),
    ("Requires", v"0.2.0"),
    ("Resampling", v"0.0.0"),
    ("Revealables", v"0.0.1"),
    ("ReverseDiffOverload", v"0.0.1"),
    ("ReverseDiffSource", v"0.1.4"),
    ("ReverseDiffSparse", v"0.2.11"),
    ("Rif", v"0.0.12"),
    ("Rmath", v"0.0.0"),
    ("RobotOS", v"0.3.5"),
    ("RobustShortestPath", v"0.2.2"),
    ("RobustStats", v"0.0.1"),
    ("RomanNumerals", v"0.1.0"),
    ("Roots", v"0.1.26"),
    ("RouletteWheels", v"0.0.6"),
    ("RudeOil", v"0.1.0"),
    ("RunTests", v"0.0.3"),
    ("SALSA", v"0.0.5"),
    ("SCS", v"0.1.1"),
    ("SDE", v"0.3.1"),
    ("SDL", v"0.1.5"),
    ("SFML", v"0.1.0"),
    ("SGDOptim", v"0.2.2"),
    ("SGP4", v"0.0.3"),
    ("SHA", v"0.2.1"),
    ("SIUnits", v"0.0.6"),
    ("SMTPClient", v"0.0.0"),
    ("SPTK", v"0.0.3"),
    ("SQLite", v"0.2.1"),
    ("SVM", v"0.0.1"),
    ("SVMLightLoader", v"0.2.1"),
    ("Sampling", v"0.0.8"),
    ("SaveREPL", v"0.0.1"),
    ("ScikitLearnBase", v"0.1.1"),
    ("Seismic", v"0.1.1"),
    ("SemidefiniteProgramming", v"0.1.0"),
    ("SerialPorts", v"0.0.7"),
    ("Shannon", v"0.3.0"),
    ("ShapeModels", v"0.0.3"),
    ("Shapefile", v"0.0.3"),
    ("ShowSet", v"0.0.1"),
    ("Showoff", v"0.0.7"),
    ("Sigma", v"0.0.1"),
    ("SigmoidalProgramming", v"0.0.1"),
    ("SignedDistanceFields", v"0.0.1"),
    ("Silo", v"0.1.0"),
    ("SimJulia", v"0.3.14"),
    ("Sims", v"0.1.0"),
    ("SingularIntegralEquations", v"0.0.1"),
    ("SkyCoords", v"0.1.1"),
    ("SliceSampler", v"0.0.0"),
    ("SloanDigitalSkySurvey", v"0.0.3"),
    ("Slugify", v"0.1.1"),
    ("Smile", v"0.1.3"),
    ("SmoothingKernels", v"0.0.0"),
    ("SnFFT", v"0.0.1"),
    ("Snappy", v"0.0.2"),
    ("SnoopCompile", v"0.0.3"),
    ("Sobol", v"0.1.3"),
    ("Sodium", v"0.0.0"),
    ("SoftConfidenceWeighted", v"0.1.2"),
    ("SolveDSGE", v"0.0.1"),
    ("SortingAlgorithms", v"0.0.6"),
    ("Soundex", v"0.0.0"),
    ("Sparklines", v"0.1.2"),
    ("Sparrow", v"0.0.1"),
    ("SparseGrids", v"0.1.0"),
    ("SparseVectors", v"0.4.2"),
    ("SpecialMatrices", v"0.1.3"),
    ("StackedNets", v"0.0.1"),
    ("Stan", v"0.3.1"),
    ("Stats", v"0.1.0"),
    ("StatsBase", v"0.7.4"),
    ("StatsFuns", v"0.2.2"),
    ("StatsdClient", v"0.0.2"),
    ("StochasticSearch", v"0.2.0"),
    ("Stochy", v"0.0.2"),
    ("StrPack", v"0.0.1"),
    ("StreamStats", v"0.0.2"),
    ("StructsOfArrays", v"0.0.3"),
    ("Subsequences", v"0.0.1"),
    ("SuffixArrays", v"0.0.1"),
    ("Sundials", v"0.2.0"),
    ("SunlightAPIs", v"0.0.3"),
    ("Switch", v"0.0.1"),
    ("SymPy", v"0.2.40"),
    ("Synchrony", v"0.0.1"),
    ("SynthesisFilters", v"0.0.1"),
    ("SystemImageBuilder", v"0.0.7"),
    ("TOML", v"0.3.0"),
    ("Taro", v"0.2.1"),
    ("Tau", v"0.0.3"),
    ("TaylorSeries", v"0.1.2"),
    ("TensorDecompositions", v"0.0.1"),
    ("TensorOperations", v"0.3.1"),
    ("TermWin", v"0.0.31"),
    ("TerminalExtensions", v"0.0.3"),
    ("Terminals", v"0.0.1"),
    ("TestImages", v"0.0.8"),
    ("TexExtensions", v"0.0.3"),
    ("TextAnalysis", v"0.0.5"),
    ("TextPlots", v"0.3.0"),
    ("TextWrap", v"0.1.6"),
    ("ThermodynamicsTable", v"0.0.4"),
    ("ThingSpeak", v"0.0.2"),
    ("ThreeJS", v"0.1.1"),
    ("Thrift", v"0.0.6"),
    ("TikzGraphs", v"0.1.1"),
    ("TikzPictures", v"0.2.5"),
    ("TimeData", v"0.7.0"),
    ("TimeModels", v"0.0.3"),
    ("TimeSeries", v"0.7.4"),
    ("TimeZones", v"0.1.0"),
    ("Timestamps", v"0.0.4"),
    ("Tk", v"0.3.8"),
    ("TopicModels", v"0.0.1"),
    ("TrafficAssignment", v"0.2.1"),
    ("Trie", v"0.0.0"),
    ("Twitter", v"0.2.2"),
    ("TwoBasedIndexing", v"0.0.1"),
    ("TypeCheck", v"0.0.3"),
    ("Typeclass", v"0.0.1"),
    ("UAParser", v"0.3.0"),
    ("URIParser", v"0.1.1"),
    ("URITemplate", v"0.0.1"),
    ("URLParse", v"0.0.0"),
    ("UTF16", v"0.3.0"),
    ("UUID", v"0.1.0"),
    ("UnicodePlots", v"0.0.5"),
    ("Units", v"0.2.6"),
    ("VLFeat", v"0.0.6"),
    ("VML", v"0.0.1"),
    ("VStatistic", v"1.0.0"),
    ("ValidatedNumerics", v"0.1.3"),
    ("ValueDispatch", v"0.0.1"),
    ("VarianceComponentTest", v"0.1.3"),
    ("Vega", v"0.5.4"),
    ("VennEuler", v"0.0.1"),
    ("VideoIO", v"0.0.16"),
    ("VoronoiDelaunay", v"0.0.3"),
    ("Voting", v"0.0.1"),
    ("WAV", v"0.7.0"),
    ("WCSLIB", v"0.2.1"),
    ("WORLD", v"0.2.2"),
    ("Wallace", v"0.0.1"),
    ("Watcher", v"0.1.0"),
    ("WaveletMatrices", v"0.1.0"),
    ("Wavelets", v"0.4.1"),
    ("Weave", v"0.0.4"),
    ("WebSockets", v"0.1.2"),
    ("WinRPM", v"0.1.15"),
    ("Winston", v"0.11.13"),
    ("WoodburyMatrices", v"0.1.5"),
    ("WordNet", v"0.0.1"),
    ("WorldBankData", v"0.0.5"),
    ("WriteVTK", v"0.3.0"),
    ("XClipboard", v"0.0.3"),
    ("XGBoost", v"0.1.0"),
    ("XSV", v"0.0.2"),
    ("XSim", v"0.0.3"),
    ("YAML", v"0.1.10"),
    ("YT", v"0.2.0"),
    ("Yelp", v"0.3.0"),
    ("Yeppp", v"0.1.0"),
    ("ZChop", v"0.0.2"),
    ("ZMQ", v"0.3.4"),
    ("ZVSimulator", v"0.0.0"),
    ("ZipFile", v"0.2.6"),
    ("Zlib", v"0.1.12"),
    ("kNN", v"0.0.0"),
    ])


text:
module ODESolversTests

using GridapODEs.ODETools: GenericODESolution
using GridapODEs.ODETools: BackwardEuler
using GridapODEs.ODETools: BackwardEulerNonlinearOperator
using GridapODEs.ODETools: solve!

using Test
using Gridap
using GridapODEs
using GridapODEs.ODETools

include("ODEOperatorMocks.jl")

op = ODEOperatorMock(1.0,0.0,1.0)

include("ODESolverMocks.jl")

t0 = 0.0
tF = 1.0
dt = 0.1

u0 = ones(2)*2

nls = NLSolverMock()

solver = BackwardEuler(nls,dt)

steps = solve(solver,op,u0,t0,tF)

uf = copy(u0)
uf.=1.0
current, state = Base.iterate(steps)
uf, tf = current
uf, u0, tf, cache = state
cache
@test tf==t0+dt
@test all(uf.≈1+11/9)
# current, state = Base.iterate(steps)
current, state = Base.iterate(steps,state)
uf, tf = current
@test tf≈t0+2*dt
uf, u0, tf, cache = state

_t_n = t0
for (u_n, t_n) in steps
  global _t_n
  _t_n += dt
  @test t_n≈_t_n
end

steps

@test test_ode_solution(steps)
# println("The solution at time $(t_n) is $(u_n)")

end


text:
struct IBuffer
    disp::Array{RUInt, 3}
    zbuf::Matrix{Float64}
    IBuffer(r::Int, c::Int) = new(zeros(3, c, r), fill(-Inf, c, r))
end
IBuffer() = IBuffer(DIMR, DIMC)

function dump_ppm_p3(d::IBuffer, io::IO)
    _, w, h = size(d.disp)
    write(io, "P3 $w $h $MAXCOLOR\n")
    writedlm(io, d.disp)
end

function dump_ppm_p6(d::IBuffer, io::IO)
    _, w, h = size(d.disp)
    write(io, collect(UInt8, "P6 $w $h $MAXCOLOR\n"))
    write(io, UInt8.(d.disp))
end

function plot!(d::IBuffer, point::Vector{RInt}, color::Vector{Float64})
    # origin should be in lower left instead of upper left
    point = point[1], point[3], size(d.disp, 2) - point[2] - 1

    1 < point[2] < size(d.disp, 2) || return
    1 < point[3] < size(d.disp, 3) || return
    point[1] > d.zbuf[point[2], point[3]] || return

    d.disp[:, point[2], point[3]] = color
    d.zbuf[point[2], point[3]] = point[1]
end

max_stars_repo_name: AnAverageHuman/jlgraphics

max_issues_repo_name: AnAverageHuman/jlgraphics

max_forks_repo_name: AnAverageHuman/jlgraphics


text:
module SubmodularMaximization

#
# Hack in python imports for now
#
using PyCall

const tikzplotlib = PyNULL()
const ag = PyNULL()

function __init__()
  try
    copy!(tikzplotlib, pyimport("tikzplotlib"))
  catch e
    println("Could not import tikzplotlib, trying matploblib2tikz instead")
    copy!(tikzplotlib, pyimport("matplotlib2tikz"))
  end

  copy!(ag, pyimport("mpl_toolkits.axes_grid1"))
end
#
# End hack
#

using Base.Iterators

import Base.<

# Abstract interface
export  PartitionProblem, PartitionElement, ElementArray, Solution,
  get_num_agents, solve_block, objective, evaluate_solution, empty

# Explicit interface
export ExplicitPartitionProblem, get_element, get_agent, get_center

# General methods that probably need updates
export marginal_gain, compute_weight, compute_weight_matrix, mean_weight,
total_weight, extract_triangle, visualize_solution

# Agent specification for coverage problems
export Agent, generate_agents,
  generate_colors,
  visualize_agents,
  get_element_indices,
  independent

# Solvers
export solve_optimal, solve_worst, solve_myopic, solve_random, solve_sequential

# Max now uses isless to exclude types that do not have a total order. We would
# like to have something like this defined for solutions but probably should not
# break things. This is a good compromise
partial_max(a, b) = ifelse(b < a, a, b)
partial_min(a, b) = ifelse(b > a, a, b)

# Interface
# get_block(Agent) = <array of objects associated with agents' block of the
#                     partition matroid>
# get_center(Agent) = <agent center>
#   (Note really a general property but currently defined for all agents)
# plot_element(x) = <Nothing>
# make_agent(agent_specification) = < agent >::AgentType
struct Agent{T}
  center::Array{Float64, 1}
  radius::Float64
  sensors::Array{T, 1}
end

get_block(agent::Agent) = agent.sensors
get_center(agent::Agent) = agent.center

function generate_agents(agent_specification, num_agents)
  [make_agent(agent_specification) for agent in 1:num_agents]
end

#
#
# Abstract partition matroid problems
#
# This interface is suitable for cases where the matroid is defined implicitly
# and solved suboptimally
#
# Interface
#
abstract type PartitionProblem{PartitionElement} end

# Define dependent types
PartitionElement(::PartitionProblem{T}) where T = T
# Subtypes should redefine this method
PartitionElement(::Type{<:PartitionProblem{T}}) where T = T

# Defines the structure of a solution for the given matroid or its type
ElementArray(::T) where T = ElementArray(T)
ElementArray(::Type{T}) where T = Vector{PartitionElement(T)}

# Solutions consist of their value and a set of solution elements
struct Solution{PartitionElement}
  value::Float64
  elements::Vector{PartitionElement}
end

objective(p::PartitionProblem, X) = error("Objective not defined for ",
                                          typeof(p))
# Define the solution for individual solution elements
objective(p::PartitionProblem{T}, X::T) where T = objective(p, [X])

evaluate_solution(p::PartitionProblem, X) =
  Solution(objective(p, X), X)

# Compare solutions by value
<(a::Solution, b::Solution) = a.value < b.value

# empty array (vector) of solution elements
empty(::T) where T <: PartitionProblem = ElementArray(T)()
empty(::Type{T}) where T <: PartitionProblem = ElementArray(T)()

# By default, store the representation of the matroid in something like a vector
# vector
get_num_agents(p::PartitionProblem) = length(p.partition_matroid)

# This should be an optimal or subotimal solver that outputs the appropriate
# PartitionElement for a block given prior selections
solve_block(p::PartitionProblem, block::Integer, selections::Vector) =
  error("Single agent (block) solver not defined for ", typeof(p))

#
# Concrete partition matroid problems
#
# The objective provides f({x} | Y)
# as objective(x, Y)
#
# The inputs are elements of the blocks
#
# The partition matroid is a Vector of the blocks of the partition matroid.
# The blocks contain whatever the elements of the ground set correspond to.
# For example, the blocks may contain specifications of coverage regions.

# Solution elemnts for concrete partition matroids are indices within the array
# of blocks
#
# (agent_index, block_index)
const ExplicitSolutionElement = Tuple{Int64,Int64}
struct ExplicitPartitionProblem <: PartitionProblem{ExplicitSolutionElement}
  objective::Function
  partition_matroid::Vector
end

get_element(problem::ExplicitPartitionProblem, x) =
  get_element(problem.partition_matroid, x)
get_element(partition_matroid, x) =
  get_block(partition_matroid[x[1]])[x[2]]

get_agent(problem::ExplicitPartitionProblem, x) =
  get_agent(problem.partition_matroid, x)
get_agent(partition_matroid::Vector, x) = partition_matroid[x]

get_center(p::PartitionProblem, x) = get_center(get_agent(p, x))

objective(p::ExplicitPartitionProblem, X::Vector{ExplicitSolutionElement}) =
  p.objective(map(x->get_element(p.partition_matroid, x), X))

marginal_gain(f, x, Y) = f(vcat([x], Y)) - f(Y)

compute_weight(f, x, y) = f([x]) - marginal_gain(f, x, [y])

compute_weight(f, X::Array, Y::Array) =
  maximum([compute_weight(f, x, y) for x in X, y in Y])

# Solve explicit partition matroids by iteration over blocks given a set of
# prior selections
function solve_block(p::ExplicitPartitionProblem, block_index::Integer,
                     selections::Vector)

  block::ElementArray(p) = get_element_indices(p, block_index)

  _, index = findmax(map(x->objective(p, [selections; x]), block))

  block[index]
end

function compute_weight_matrix(p::PartitionProblem)
  indices = get_element_indices(p.partition_matroid)

  n = length(p.partition_matroid)
  weights = zeros(n, n)

  f(x) = objective(p, x)

  for ii in 2:n, jj in 1:ii-1
    w = compute_weight(f, indices[ii], indices[jj])

    weights[ii, jj] = w
    weights[jj, ii] = w
  end

  weights
end

function mean_weight(W::Array)
  n = size(W,1)

  twice_edges = n * (n - 1)

  sum(W) / twice_edges
end

total_weight(W::Array) = sum(W) / 2

mean_weight(p::PartitionProblem) = mean_weight(compute_weight_matrix(p))
total_weight(p::PartitionProblem) = total_weight(compute_weight_matrix(p))

function extract_triangle(A)
  values = Float64[]
  for ii in 2:size(A, 1), jj in 1:ii-1
    push!(values, A[ii, jj])
  end
  values
end

# indexing and solver tools

# Construct index set for ease in manipulation of the matroid
#
# The resulting index is an array of arrays whereas each array corresponds
# to indices for an element in a block of the partition matroid
get_element_indices(p::ExplicitPartitionProblem, xs...) =
  get_element_indices(p.partition_matroid, xs...)

function get_element_indices(agents::Vector, block::Integer)
  map(1:length(get_block(agents[block]))) do block_index
    (block, block_index)
  end
end
function get_element_indices(agents::Vector)
  map(agents, 1:length(agents)) do agent, agent_index
    get_element_indices(agents, agent_index)
  end
end

# A set is independent if it contains at most one assignment to each agent
# Tuple consist of agent and agent-index
independent(x) = length(x) == length(Set(map(first, x)))

# Returns true if any element of Y can be added to X
can_augment(x, Y::Vector) = any(y->independent(vcat(x, y)), Y)
# Can agent index add solution elements to x in a partition matroid
can_augment(x, index::Int64) = !in(index, map(first, x))
# Can a given solution be added to x
can_augment(x, e::ExplicitSolutionElement) = can_augment(x, first(e))

include("src/utils.jl")
include("src/visualization.jl")
include("src/normal_lookup_table.jl")
include("src/solvers.jl")

# Support for solvers with range-based communication graphs
export make_adjacency_matrix, plot_adjacency, plot_shortest_path,
make_hop_adjacency, neighbors, shortest_path, path_distance, is_connected,
generate_connected_problem, solve_multi_hop

export communication_span, communication_messages, communication_volume

export MultiHopSolver, SequentialCommunicationSolver, AuctionSolver,
LocalAuctionSolver

include("src/communications_graphs_solvers.jl")

include("src/coverage/coverage.jl")
include("src/coverage/probabilistic_coverage.jl")

include("src/target_tracking/target_tracking.jl")
include("src/target_tracking/filtering.jl")
include("src/target_tracking/information.jl")
include("src/target_tracking/target_coverage.jl")
include("src/target_tracking/single_robot_solver.jl")
include("src/target_tracking/multi_robot_solvers.jl")
include("src/target_tracking/multi_robot_target_tracking_problem.jl")
include("src/target_tracking/multi_robot_target_coverage_problem.jl")
include("src/target_tracking/pairwise_weights.jl")
include("src/target_tracking/experiment_tools.jl")
include("src/target_tracking/visualization.jl")

end

max_stars_repo_name: mcorah/MultiAgentSensing

max_issues_repo_name: mcorah/MultiAgentSensing

max_forks_repo_name: mcorah/MultiAgentSensing


text:
# ### subplot (3)

#md # ![FILE_NAME.png](images/FILE_NAME.png)

a = plot(sin, 0, 2pi, xlabel="x1")
b = plot(cos, 0, 2pi, xlabel="x2")
c = histogram(randn(1000), xlabel="x3")
d = plot(x->exp(-x^2), -3, 3, xlabel="x4")

plot(a, b, c, d, layout=(4,1), size=(300, 800))


text:
# UnitCommitment.jl: Optimization Package for Security-Constrained Unit Commitment
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.

import Random
import UnitCommitment: XavQiuAhm2021

using Distributions
using UnitCommitment, Cbc, JuMP

get_instance() = UnitCommitment.read_benchmark("matpower/case118/2017-02-01")
system_load(instance) = sum(b.load for b in instance.buses)
test_approx(x, y) = @test isapprox(x, y, atol = 1e-3)

@testset "XavQiuAhm2021" begin
    @testset "cost and load share" begin
        instance = get_instance()

        # Check original costs
        unit = instance.units[10]
        test_approx(unit.min_power_cost[1], 825.023)
        test_approx(unit.cost_segments[1].cost[1], 36.659)
        test_approx(unit.startup_categories[1].cost[1], 7570.42)

        # Check original load share
        bus = instance.buses[1]
        prev_system_load = system_load(instance)
        test_approx(bus.load[1] / prev_system_load[1], 0.012)

        Random.seed!(42)
        randomize!(
            instance,
            XavQiuAhm2021.Randomization(randomize_load_profile = false),
        )

        # Check randomized costs
        test_approx(unit.min_power_cost[1], 831.977)
        test_approx(unit.cost_segments[1].cost[1], 36.968)
        test_approx(unit.startup_categories[1].cost[1], 7634.226)

        # Check randomized load share
        curr_system_load = system_load(instance)
        test_approx(bus.load[1] / curr_system_load[1], 0.013)

        # System load should not change
        @test prev_system_load ≈ curr_system_load
    end

    @testset "load profile" begin
        instance = get_instance()

        # Check original load profile
        @test round.(system_load(instance), digits = 1)[1:8] ≈
              [3059.5, 2983.2, 2937.5, 2953.9, 3073.1, 3356.4, 4068.5, 4018.8]

        Random.seed!(42)
        randomize!(instance, XavQiuAhm2021.Randomization())

        # Check randomized load profile
        @test round.(system_load(instance), digits = 1)[1:8] ≈
              [4854.7, 4849.2, 4732.7, 4848.2, 4948.4, 5231.1, 5874.8, 5934.8]
    end
end


text:
# ccall will call the Conversions we have defined
# TODO: I am dubious about all of this; check it all.

using Base.Cartesian.@ntuple

@inline vinit8{T}(x::T) = @ntuple 8 k->k==1 ? VecElement{T}(x) : VecElement{T}(zero(T))
@inline vinit4{T}(x::T) = @ntuple 4 k->k==1 ? VecElement{T}(x) : VecElement{T}(zero(T))
@inline vinit2{T}(x::T) = @ntuple 2 k->k==1 ? VecElement{T}(x) : VecElement{T}(zero(T))

##Float64
typealias __m256d NTuple{4, VecElement{Float64}}
@inline Base.convert(::Type{__m256d}, x::Float64) = __m256d(vinit4(x))
@inline Base.convert(::Type{Float64}, x::__m256d) = first(x).value

typealias __m128d NTuple{2, VecElement{Float64}}
@inline Base.convert(::Type{__m128d}, x::Float64) = __m128d(vinit2(x))
@inline Base.convert(::Type{Float64}, x::__m128d) = first(x).value

##Float32
typealias __m256 NTuple{8, VecElement{Float32}}
@inline Base.convert(::Type{__m256}, x::Float32) = __m256(vinit8(x))
@inline Base.convert(::Type{Float32}, x::__m256) = first(x).value

typealias __m128 NTuple{4, VecElement{Float32}}
@inline Base.convert(::Type{__m128}, x::Float32) = __m128(vinit4(x))
@inline Base.convert(::Type{Float32}, x::__m128) = first(x).value

##Int32
typealias __m256i NTuple{8, VecElement{Int32}}
@inline Base.convert(::Type{__m256i}, x::Int32) = __m256i(vinit8(x))
@inline Base.convert(::Type{Int32}, x::__m256i) = first(x).value

typealias __m128i NTuple{4, VecElement{Int32}}
@inline Base.convert(::Type{__m128i}, x::Int32) = __m128i(vinit4(x))
@inline Base.convert(::Type{Int32}, x::__m128i) = first(x).value

##########

if SIMD_ARCH == "sse2"
	typealias VDouble __m128d
	typealias VInt __m128i
	typealias VFloat __m128
	typealias VInt2 __m128i

elseif SIMD_ARCH == "avx" || SIMD_ARCH == "fma4"
	typealias VDouble __m256d
	typealias VInt __m128i
	typealias VFloat __m256

	immutable VInt2
		x::VInt
		y::VInt
	end
elseif SIMD_ARCH == "avx2"
	typealias VDouble __m256d
	typealias VInt __m128i
	typealias VFloat __m256
	typealias VInt2 __m256i
elseif SIMD_ARCH == "purec"
	typealias VDouble Float64
	typealias VInt Int32
	typealias VFloat Float32
	typealias VInt2 Int32
else
	error("SIMD instruction set: $(SIMD_ARCH). Not Supported. This error should never occur. Please report this bug.")
end

###########
#Always:

immutable VDouble2
	x::VDouble
	y::VDouble
end
Base.convert(::Type{Tuple{Float64,Float64}}, d::VDouble2) = (convert(Float64, d.x), convert(Float64, d.y))

immutable VFloat2
	x::VFloat
	y::VFloat
end
Base.convert(::Type{Tuple{Float32,Float32}}, d::VFloat2) = (convert(Float32, d.x), convert(Float32, d.y))


text:
################################################################################
#
# Generate synthetic data for the Gaussian lens model
#
################################################################################

### Module loading

using LinearAlgebra, JUDI.TimeModeling, Distributed, JLD2, PyPlot, Images
@everywhere push!(LOAD_PATH, string(pwd(), "/src/"))
using TWRIdual

### Smoothing and thonsen smooth erroring function
function smooth(v; sigma=5)
    return Float32.(imfilter(v, Kernel.gaussian(sigma)))
end

### Set true model

n = (201, 201)
d = (10f0, 10f0)
o = (0f0, 0f0)
val = 0.5f0
x = reshape((collect(1:n[1]).-1f0).*d[1], :, 1)
z = reshape((collect(1:n[2]).-1f0).*d[2], 1, :)
v = 2f0.-val*exp.(-((x./1000f0.-1f0)/0.25f0).^2f0.-((z./1000f0.-1f0)/0.5f0).^2f0)
m_true = 1f0./v.^2f0

epsilon = smooth(.5f0 .* (2f0 .- v))
delta = smooth(.35f0 .* (2f0 .- v))
z = range(-1, 1, length=n[1])
theta = smooth(2f0 .* (2f0 .- v)) .*z

model_true = Model_TTI(n, d, o, m_true; epsilon=epsilon, delta=delta, theta=theta)

### Acquisition geometry

# Sources
# ix_src = 3:4:199
ix_src = 3:14:199
nsrc = length(ix_src)
iz_src = 3
x_src = convertToCell((ix_src.-1)*d[1])
y_src = convertToCell(range(0f0, stop = 0f0, length = nsrc))
z_src = convertToCell(range((iz_src-1)*d[2], stop = (iz_src-1)*d[2], length = nsrc))

# Source wavelet
dt = 1f0
T = 2000f0 # total recording time [ms]
freq_peak = 0.006f0
wavelet = ricker_wavelet(T, dt, freq_peak)

# Receivers
ix_rcv = 3:199
iz_rcv = 199
nrcv = length(ix_rcv)
x_rcv = (ix_rcv.-1)*d[1]
y_rcv = 0f0
z_rcv = range((iz_rcv-1)*d[2], stop = (iz_rcv-1)*d[2], length = nrcv)

# Geometry structures
src_geom = Geometry(x_src, y_src, z_src; dt = dt, t = T)
rcv_geom = Geometry(x_rcv, y_rcv, z_rcv; dt = dt, t = T, nsrc = nsrc)

# Source function
fsrc = judiVector(src_geom, wavelet)

# Set up info structure for linear operators
ntComp = get_computational_nt(src_geom, rcv_geom, model_true)
info = Info(prod(n), nsrc, ntComp)

# Setup operators
F = judiModeling(info,model_true, src_geom,rcv_geom)
dat = F*fsrc

### Saving data

@save string("./data/GaussLens_data_tti.jld") model_true fsrc dat


text:
module QueensAlwaysPuzzleMe

using Distributed, BenchmarkTools

# There is also a simple (i.e. not distributed) version:
# https://github.com/PeterLuschny/IntegerSequences.jl/blob/master/demos/SimpleQueens.jl
# For some background see https://wp.me/paipV7-E and https://oeis.org/A319284

function solve!(profile, level, size, start, cols, diag4, diag1)

    if level > 0
        for i in start:size
            save = cols & (1 << i) +
            diag1 & (1 << (i + level)) +
            diag4 & (1 << (32 + i - level))

            if save == 0

                cols  = xor(cols,  1 << i)
                diag1 = xor(diag1, 1 << (i + level))
                diag4 = xor(diag4, 1 << (32 + i - level))

                solve!(profile, level - 1, size, 0, cols, diag4, diag1)

                cols  = xor(cols,  1 << i)
                diag1 = xor(diag1, 1 << (i + level))
                diag4 = xor(diag4, 1 << (32 + i - level))

                profile[level + 1] += 1

                cols == 0 && return
            end
        end
    else
        for i in 0:size
            save = cols & (1<<i) + diag1 & (1<<i) + diag4 & (1<<(32+i))
            save == 0 && (profile[1] += 1)
        end
    end
end

function distributed_search(n::Int, k::Int)

    profile = zeros(Int, n + 1)
    cols = diag4 = diag1 = Int(0)
    solve!(profile, n - 1, n - 1, k, cols, diag4, diag1)
    return profile
end

function queens(n::Int)

    n == 0 && return [1]

    profile = Distributed.@distributed (+) for k = 0:n-1
        distributed_search(n, k)
    end

    profile[n+1] = 1  # add the root
    [profile[n-i+1] for i = 0:n]
end

function ProfileQueens(up_to)
    for n in 0:up_to
        profile = queens(n)
        #show_profile(n, profile)
    end
end

"""
julia> show_profile(7, queens(7))
    size:      7
    profile:   [1, 7, 30, 76, 140, 164, 94, 40]
    nodes:     552
    solutions: 40
"""
function show_profile(n, p)
    println("size:      ", n)
    println("profile:   ", p)
    println("nodes:     ", sum(p))
    println("solutions: ", p[n+1])
    println()
end

"""
julia> BechmarkQueens()
    Number of cpu-threads : 4
    Number of threads used: 4
    95.699 ms (589 allocations: 48.88 KiB)
"""
function BechmarkQueens()
    println("Number of cpu-threads : ", Base.Sys.CPU_THREADS)
    println("Number of threads used: ", Threads.nthreads())
    println()

    @btime ProfileQueens(12)
end

BechmarkQueens()

end # module

max_stars_repo_name: OpenLibMathSeq/Sequences

max_issues_repo_name: OpenLibMathSeq/Sequences


text:
using Gadfly, RDatasets

plot(dataset("mlmRev", "Chem97"),
     x=:GCSEScore,
     ygroup=:Age,
     color=:Gender,
     Geom.subplot_grid(Geom.histogram, free_y_axis=true))


text:
import Base.zero

export
    AV_PERM_READ,
    AV_PERM_WRITE,
    AV_PERM_PRESERVE,
    AV_PERM_REUSE,
    AV_PERM_REUSE2,
    AV_PERM_NEG_LINESIZES,
    AVFilterContext,
    AVFilterLink,
    AVFilterPad,
    AVFilterFormats,
    Array_8_Ptr,
    Array_8_Cint,
    AVFilterBuffer,
    AVFilterBufferRefAudioProps,
    AVFilterBufferRefVideoProps,
    AVFilterBufferRef,
    AVFilter,
    AVFilterGraph,
    AVFilterInOut

const AV_PERM_READ = 0x01
const AV_PERM_WRITE = 0x02
const AV_PERM_PRESERVE = 0x04
const AV_PERM_REUSE = 0x08
const AV_PERM_REUSE2 = 0x10
const AV_PERM_NEG_LINESIZES = 0x20

typealias AVFilterContext AVFilterContext
typealias AVFilterLink AVFilterLink
typealias AVFilterPad AVFilterPad
typealias AVFilterFormats Void

immutable Array_8_Ptr
    d1::Ptr{UInt8}
    d2::Ptr{UInt8}
    d3::Ptr{UInt8}
    d4::Ptr{UInt8}
    d5::Ptr{UInt8}
    d6::Ptr{UInt8}
    d7::Ptr{UInt8}
    d8::Ptr{UInt8}
end

zero(::Type{Array_8_Ptr}) = Array_8_Ptr(fill(C_NULL,8)...)

immutable Array_8_Cint
    d1::Cint
    d2::Cint
    d3::Cint
    d4::Cint
    d5::Cint
    d6::Cint
    d7::Cint
    d8::Cint
end

zero(::Type{Array_8_Cint}) = Array_8_Cint(fill(zero(Cint),8)...)

immutable AVFilterBuffer
    data::Array_8_Ptr
    extended_data::Ptr{Ptr{UInt8}}
    linesize::Array_8_Cint
    priv::Ptr{Void}
    free::Ptr{Void}
    format::Cint
    w::Cint
    h::Cint
    refcount::UInt32
end

immutable AVFilterBufferRefAudioProps
    channel_layout::UInt64
    nb_samples::Cint
    sample_rate::Cint
    planar::Cint
end

immutable AVFilterBufferRefVideoProps
    w::Cint
    h::Cint
    pixel_aspect::AVRational
    interlaced::Cint
    top_field_first::Cint
    pict_type::AVPictureType
    key_frame::Cint
end

immutable AVFilterBufferRef
    buf::Ptr{AVFilterBuffer}
    data::Array_8_Ptr
    extended_data::Ptr{Ptr{UInt8}}
    linesize::Array_8_Cint
    video::Ptr{AVFilterBufferRefVideoProps}
    audio::Ptr{AVFilterBufferRefAudioProps}
    pts::Int64
    pos::Int64
    format::Cint
    perms::Cint
    _type::AVMediaType
end

immutable AVFilter
    name::Ptr{UInt8}
    description::Ptr{UInt8}
    inputs::Ptr{AVFilterPad}
    outputs::Ptr{AVFilterPad}
    init::Ptr{Void}
    uninit::Ptr{Void}
    query_formats::Ptr{Void}
    priv_size::Cint
end

immutable AVFilterGraph
    av_class::Ptr{AVClass}
    filter_count::UInt32
    filters::Ptr{Ptr{AVFilterContext}}
    scale_sws_opts::Ptr{UInt8}
end

immutable AVFilterInOut
    name::Ptr{UInt8}
    filter_ctx::Ptr{AVFilterContext}
    pad_idx::Cint
    next::Ptr{AVFilterInOut}
end


text:
# vim: set et ts=2 sw=2;

# Non-parametric optimizers
# ## Uses
using Test
using Random
using Parameters
using ResumableFunctions

# ## Config
@with_kw mutable struct It
  data = (file="auto93.csv", dir="data",some=128,best=.75)
  char = (skip='?',less='<',more='>',num=':',klass='!')
  str  = (skip="?")
  some = (max=64,bins=.5, cohen=0.3, trivial=1.05)
  divs = (few=126)
  seed = 1
end

# ## Globals
it=It()
Random.seed!(it.seed)
no = nothing

# -------------------------------------------------------------------
# ## Columns
# Count all the symbols. Keep a sample of the numbers.
@with_kw mutable struct Some pos=0;txt="";w=1;n=0;_all=[];ok=true end
@with_kw mutable struct Sym  pos=0;txt="";w=1;n=0;seen=Dict() end
@with_kw mutable struct Skip pos=0;txt="";w=1;n=0 end

function inc!(i,x::Array) for y in x inc!(i,y) end; i end
function inc!(i,x)
  inc1!(i::Skip, x) = i
  inc1!(i::Sym,  x) = begin
    new = i.seen[x] = 1 + get(i.seen,x,0)
    if new > i.n i.n, i.mode = now, x end end
  inc1!(i::Some, x) = begin
    m = length(i._all)
    if m < it.some.max
      i.ok=false; push!(i._all, x);
    elseif rand() < m/i.n
      i.ok=false; i._all[int(m*rand())+1]=x end
  end
  x==it.char.skip ? x : begin i.n += 1; inc1!(i,x); x end end

function mid(i::Sym) i.mode end
function var(i::Sym) sum(-v/i.n*log(2,v/i.n) for (_,v) in i.seen) end

function mid( i::Some)   a=all(i); per(a,.5) end
function var( i::Some)   a=all(i); (per(a,.9) - per(a,.1)) / 2.56 end
function norm(i::Some,x) a=all(i);
  x==it.char.skip ? x : (x-a[1])/(a[end]-a[1]+1E-32) end

function all(i::Some)
  i._all = i.ok ? i._all : sort(i._all)
  i.ok = true
  i._all end

function combine(i::Some,j::Some, small,lo)
  mi, mj = mid(i), mid(j)
  if (abs(mi) - abs(mj) < small) || (mi < lo && mi < lo)
    inc!(Some(), [i._all;j._all]) end end

# -------------------------------------------------------------------
# ## Table
# Load rows, Summarize the columns.
@with_kw mutable struct Table ys=[]; xs=[]; rows=[]; cols=[] end
@with_kw mutable struct Row   has=[]; gt=0; tag=no end

function data(file; t=Table())
  col(;txt="", pos=0, c=it.char) = begin
    what = c.less in txt||c.more in txt||c.num in txt ? Some : Sym
    what = c.skip in txt ? Skip : what
    now = what(txt=txt, pos=pos, w= c.less in txt ? -1 : 1)
    at  = c.less in txt||c.more in txt||c.klass in txt ? t.ys : t.xs
    push!(at, now)
    now
  end
  cols(a)  = [col(txt=txt, pos=pos) for (pos,txt) in enumerate(a)]
  cells(a) = Row(has= [inc!(c, a[c.pos]) for c in t.cols])
  for a in csv(it.data.dir * "/" * file)
    length(t.cols)==0 ? t.cols=cols(a) : push!(t.rows, cells(a)) end
  t end

# -------------------------------------------------------------------
# ## Classify
# Score rows by how they are better than others.
# Tag the `best` percent rows.
function tag(t::Table)
  function gt(row1, row2)
    "Zitler's continous domination predicate (from IBEA, 2005)."
    s1, s2, n = 0, 0, length(t.ys)
    for col in t.ysz
      a, b = row1.has[col.pos], row2.has[col.pos]
      a, b = norm(col, a), norm(col, b)
      s1  -= ℯ ^ (col.w * (a - b) / n)
      s2  -= ℯ ^ (col.w * (b - a) / n) end
    s1/n < s2/n
  end
  n = it.data.some
  print(":::",any(t.rows))
  for row in t.rows
    row.gt = sum(gt(row, any(t.rows)) for _ in 1:n)/n  end
  for (n, row) in enumerate(sort(t.rows, by = x -> x.gt))
    row.tag = n > length(t.rows) * it.data.best end
  t end

# -------------------------------------------------------------------
# ## Discretize
# Score rows by how they are better than others.
# Tag the `best` percent rows.
@with_kw mutable struct Span
   lo=typemax(Int); hi=typemin(Int); _has=[] end

function discretize(x::Some, t:Table)
  function div(xsmall,ysmall,ymin,xy)
    n = length(xy) * the data.xchop
    while n < 4 && n <= length(xy)/2 n+= 1.2 end
    n, now, tmp = int(n), int(n), []
    b4, span    = 1, Span(lo=xy[1][1])
    while now < length(xy) - n
      x=xy[now][1]
      span.hi = x
      now += 1
      if (now - b4 => n    && now < len(xy) - 2 &&
          x != xy[now][1]  && span.hi - span.lo > xsmall)
        span._has= [z[2] for z in xy[b4:now]]
        tmp += [span]
        span = Span(lo=xy[now][1])
        b4   = now
        now += n end end
     tmp += [Span(lo=xy[b4][1],hi=xy[end][1],
                  _has=[z[2] for z in xy[b4:]])]
     merge(tmp,ysmall,ymin) end

  function merge(b4, ysmall, ymin)
    j, now = 0, []
    while j < length(b4)
      a=b4[j]
      if j < length(b4)
        b = b4[j+1]
        c  = combine(a._has,b._has, ysmall, ymin)
        if c != nothing
          now += [Span(lo=a.lo,hi=
    end
    length(now) == length(b4) ? b4 : merge(now,ymin,small)

  for row in rows:
    inc!(y, row.gt)
    push!(xy, (row.has[x.pos], row.gt)) end
  tmp = div(var(x)*it.some.xsmall,
            var(y)*it.some.ysmall,
            per(all(y), it.data.best),
            sort(xy))
  tmp[1].lo = typemin(Int)
  tmp[end].hi = typemax(Int)
  tmp end

 # -------------------------------------------------------------------
# ## Misc Utils
# ### One-liners.
same(s)  = s                                  #noop
int(x)   = floor(Int,x)                       #round
per(a,n) = a[int(length(a)*n)+1]                #percentile
thing(x) = try parse(Float64,x) catch _ x end #coerce
say(i)   = println(o(i))                      #print+nl
any(a)   = a[ int(length(a) * rand()) + 1 ]   #pick any one
few(a,n=it.divs.few) =                        #pick many
  length(a)<n ? a : [any(a) for _ in 1:n]

# ### How to print a struct
# Skips any fields starting with "`_`".
o(i::String)     = i
o(i::SubString)  = i
o(i::Char)       = string(i)
o(i::Number)     = string(i)
o(i::Array)      = "["*join(map(o,i),", ")*"]"
o(i::NamedTuple) = "("*join(map(o,i),", ")*")"
o(i::Dict)       = "{"*join(["$k="*o(v) for (k,v) in i],", ")*"}"
o(i::Span)       = begin
  if i.lo <= typemin(Int) return "<= $(i.hi)"
  if i.hi <= typemax(Int) return ">= $(i.lp)"
  "[$(i.lo)..$(i.hi)]" end
o(i) = begin
  s, pre="$(typeof(i)){", ""
  for f in sort([x for x in fieldnames(typeof(i))
                  if !("$x"[1] == '_')])
    s = s * pre * "$f=$(o(getfield(i,f)))"
    pre=", " end
  return s * "}" end

# ### How to read a CSV File
# Skip blank lines. Coerce numeric strings to numbers.
@resumable function csv(file;zap=r"(\s+|#.*)") #iterate on file
  b4=""
  for line in eachline(file)
    line = replace(line,zap =>"")
    if length(line) != 0
      if line[end] == ',' # if line ends with ",",
        b4 = b4 * line    # join it to next
      else
        @yield [thing(x) for x in split(b4*line,",")]
        b4 = "" end end end end

# ## Tests
go()  = include("jump.jl")
function run()
  t=tag(data("auto.csv"))
  for r in sort(t.rows, by = x -> x.gt)
    print(r.tag) end end

# ## Command line

max_stars_repo_name: timm/jut

max_issues_repo_name: timm/jut

max_forks_repo_name: timm/jut


text:
@compat abstract type Space{T<:Real} end
@compat type ChebyshevZeroOneBV{T<:Real} <: Space{T}
end
ChebyshevZeroOneBV{T<:Real}(::Type{T}) = ChebyshevZeroOneBV{T}()

@compat abstract type EntryBounds{S<:Space,T<:Real} end
@compat type AnalyticEntryBounds{S<:Space,T<:Real}<:EntryBounds{S,T}
  sp::S
  δ::T
  P::T
  H::T
end

# Entry bounds
entrybound{S<:ChebyshevZeroOneBV}(a::AnalyticEntryBounds{S},j,k) = (a.H*t(j)*exp((k-1)*a.P-(j-1)*a.δ))

# BV norm of EN
function logEnorm{S<:ChebyshevZeroOneBV}(a::AnalyticEntryBounds{S},NP)
  N = NP-1; #recall we start at 0 in the polynomial basis and 1 in the matrix indexing
  log(sqrt(2)*a.H) + log(1-exp(-2a.P*N))/2 - log(1-exp(-2a.P))/2 + a.P*N-a.δ*(N+1) +
    log(sqrt(N^2 *exp(-4a.δ) + (1-2N-2N^2)*exp(-2a.δ) + (N+1)^2)/(1-exp(-2a.δ)) + 1/2) - log(1-exp(-2a.δ))/2
end

# Pointwise aliasing error
t(j) = (1+(j!=0))
aliaserror{S<:ChebyshevZeroOneBV}(a::AnalyticEntryBounds{S},j,k,N_interp) =
  a.H * t(j-1) * exp(a.P*(k-1)) * 2cosh(a.δ*(j-1)) /(exp(2a.δ*N_interp)-1)

@compat abstract type LYBounds{S<:Space,T<:Real} end
@compat type FirstOrderLYBounds{S<:Space,T<:Real}<:LYBounds{S,T}
  sp::S
  λ::T
  C1::T
end

function Snorm{S<:ChebyshevZeroOneBV,T<:Real}(b::FirstOrderLYBounds{S,T})
  R = 2*b.C1/(1-1/b.λ)
  ξ = exp(-R)*(1-1/b.λ)/2
  C_L = 4exp(R) * (1+R)
  C_dash =  1+b.C1/3(1-1/b.λ)
  #Γ = 1-ξ
  #Lsum_norm = (C_dash* log(C_L) + 1)/ξ
  m_lsum = ceil((2/log(b.λ)).hi);
  n_lsum = ceil((
        (4+2log(max(b.C1/(1-1/b.λ),1)*sqrt(C_L)))/ξ
      ).hi)
  Lsum_norm = (m_lsum+n_lsum)*C_dash/convert(T,3//5)
  1 + Lsum_norm*(3+C_dash)
end

# Strong convergence norm
function logSEnorm(a::EntryBounds,b::LYBounds,N)
  logenorm = logEnorm(a,N)
  logenorm - log(1/Snorm(b) - exp(logenorm))
end


text:
# Compute F-statistic, given vector of vectors
#ANOVA
function f(R)
    X = vcat(R...)
    N = length(X)
    nj = length.(R)
    X̅ = mean(X)
    X̅j = mean.(R)
    k = length(R)
    top = sum(nj .*(X̅j .- X̅) .^2) /(k-1)
    bottom = sum([sum((R[i] .- X̅j[i]) .^2) for i in 1:k])/(N-k)
    return top/bottom
end
function f_slow(R,N,nj,X̅,k)
    X̅j = mean.(R)
    top = sum(nj .*(X̅j .- X̅) .^2) /(k-1)
    bottom = sum([sum((R[i] .- X̅j[i]) .^2) for i in 1:k])/(N-k)
    return top/bottom
end

function f(R,N,nj,X̅,k)
    X̅j = mean.(R)
    top = 0.0
    bottom = 0.0
    @inbounds for i in 1:k
        top += nj[i] * (X̅j[i] - X̅)^2
        for j in 1:nj[i]
            bottom += (R[i][j] - X̅j[i])^2
        end
    end
    top/= (k-1)
    bottom /= (N-k)
    return top/bottom
end

#Pairwise ANOVA
function f_pairs(R)
    n = length(R)
    F = zeros(n,n)
    for j in 1:n-1
        for i in j+1:n
            F[i,j] = f([R[i],R[j]])
        end
    end
    return F
end
function f_pairs(R ::Vector,N ::Array{Int},nj ::Matrix{Tuple},X̅ ::Matrix{Float64})
    n = length(R)
    F = zeros(n,n)
    for j in 1:n-1
        for i in j+1:n
            F[i,j] = f([R[i],R[j]],N[i,j],nj[i,j],X̅[i,j],2)
        end
    end
    return F
end
# get parameter values corresponding to each pairwise combination of groups
function get_pars(R)
    n = length(R)
    N_p = Array{Int}(undef,n,n)
    nj_p= Array{Tuple}(undef,n,n)
    X̅_p = Array{Float64}(undef,n,n)

    for j in 1:n-1
        for i in j+1:n
            N_p[i,j] = length(R[i]) + length(R[j])
            nj_p[i,j] = (length(R[i]) , length(R[j]))
            X̅_p[i,j] = mean(vcat(R[i]...,R[j]...))
        end
    end
    return N_p,nj_p,X̅_p
end


text:
export Euler
export step!

"""
    Euler(arguments;realdata)

Explicit Euler solver.

Constructs an object of type `TimeSolver` to be used in `Problem(model, initial, param; solver::TimeSolver)`

Arguments can be either
0. an object of type `AbstractModel`;
1. an `Array` of size `(N,m)` where `N` is the number of collocation points and `m` the number of data (equations solved);
2. a `Tuple` `(N,m)` as above;
3. an integer `N` and an integer `m` as above (the latter is optional, by default `m=2`).
4. a `NamedTuple` containing a key `N` and an integer `m` (the latter is optional, by default `m=2`).

The keyword argument `realdata` is optional, and determines whether pre-allocated vectors are real- or complex-valued.
By default, they are either determined by the model or the type of the array in case `0.` and `1.`, complex-valued otherwise.

"""
struct Euler <: TimeSolver

    U1 :: Array
    U2 :: Array

    function Euler( U :: Array; realdata=nothing )
        U1 = copy(U)
        U2 = copy(U)
        if realdata==true
            U1 = real.(U1);U2 = real.(U2)
        end
        if realdata==false
            U1 = complex.(U1);U2 = complex.(U2)
        end
        new( U1, U2)
    end

    function Euler( model :: AbstractModel; realdata=nothing )
        U=model.mapto(Init(x->0*x,x->0*x))
        Euler(U; realdata=realdata)
    end
    function Euler( datasize; realdata=false )
        U = zeros(Float64, datasize)
        Euler(U; realdata=realdata)
    end

    function Euler( N::Int, m=2::Int; realdata=false )
        datasize = (N,m)
        Euler(datasize; realdata=realdata)
    end
    function Euler( param::NamedTuple, datasize=2::Int; realdata=false )
        datasize = (param.N,datasize)
        Euler(datasize; realdata=realdata)
    end
end

function step!(solver :: Euler,
                model :: AbstractModel,
                U  ,
                dt )

    solver.U1 .= U
    model.f!( solver.U1 )
    U .+= dt .* solver.U1

end


text:
cube = map(c -> c == '#', vcat(permutedims.(collect.(readlines("day17/input.txt")))...))
# cube = map(c -> c == '#', vcat(permutedims.(collect.(readlines("day17/small.txt")))...))
cube = reshape(cube, size(cube)..., 1, 1)

function step_cube(cube)
    # pad cube
    cube_new = zeros(Bool, size(cube) .+ 2)
    # copy data into new cube
    for r in 1:size(cube, 1), c in 1:size(cube, 2), p in 1:size(cube, 3), w in 1:size(cube, 4)
        cube_new[r+1, c+1, p+1, w+1] = cube[r, c, p, w]
    end
    # retain cube for study
    cube_study = copy(cube_new)
    # run thru dims
    mr, mc, mp, mw = size(cube_new)
    for r in 1:size(cube_new, 1), c in 1:size(cube_new, 2), p in 1:size(cube_new, 3), w in 1:size(cube_new, 4)
        neighbors = cube_study[max(1, r-1):min(r+1, mr), max(1, c-1):min(c+1, mc), max(1, p-1):min(p+1, mp), max(1, w-1):min(w+1, mw)]
        if cube_study[r, c, p, w] && !(count(neighbors) in [3, 4])
            cube_new[r, c, p, w] = false
        elseif !cube_study[r, c, p, w] && count(neighbors) == 3
            cube_new[r, c, p, w] = true
        end
    end
    return cube_new
end

for i in 1:6
    global cube
    cube = step_cube(cube)
end

println(count(cube))


text:
macro checkpoint(alg, adtool, loop)
    ex = quote
        function tobedifferentiated(inputs)
            local F_H = similar(inputs)
            local F = inputs
            $(loop.args[2])
            outputs = F
            return outputs
        end
        if isa($alg, Revolve)
            storemap = Dict{Int32,Int32}()
            check = 0
            F_Check = Array{Any, 2}(undef, 3, $alg.acp)
            F_final = Array{Float64, 1}(undef, 2)
            while true
                next_action = next_action!($alg)
                if (next_action.actionflag == Checkpointing.store)
                    check = check+1
                    storemap[next_action.iteration-1]=check
                    $alg.fstore(F,F_Check,t,check)
                elseif (next_action.actionflag == Checkpointing.forward)
                    for j= next_action.startiteration:(next_action.iteration - 1)
                        $(loop.args[2])
                    end
                elseif (next_action.actionflag == Checkpointing.firstuturn)
                    $(loop.args[2])
                    F_final .= F
                    L .= [0, 1]
                    t = 1.0-h
                    L_H .= L
                    L = Checkpointing.jacobian(tobedifferentiated, F_H, $adtool)[2,:]
                elseif (next_action.actionflag == Checkpointing.uturn)
                    L_H .= L
                    F_H = F
                    res = Checkpointing.jacobian(tobedifferentiated, F_H, $adtool)
                    L =  transpose(res)*L
                    t = t - h
                    if haskey(storemap,next_action.iteration-1-1)
                        delete!(storemap,next_action.iteration-1-1)
                        check=check-1
                    end
                elseif (next_action.actionflag == Checkpointing.restore)
                    F, t = $alg.frestore(F_Check,storemap[next_action.iteration-1])
                elseif next_action.actionflag == Checkpointing.done
                    if haskey(storemap,next_action.iteration-1-1)
                        delete!(storemap,next_action.iteration-1-1)
                        check=check-1
                    end
                    break
                end
            end
            F .= F_final
        elseif isa($alg, Periodic)
            check = 0
            F_Check = Array{Any, 2}(undef, 3, $alg.acp)
            F_final = Array{Float64, 1}(undef, 2)
            F_Check_inner = Array{Any, 2}(undef, 3, $alg.period)
            for i = 1:$alg.acp
                $alg.fstore(F,F_Check,t,i)
                for j= (i-1)*$alg.period: (i)*$alg.period-1
                    $(loop.args[2])
                end
            end
            F_final .= F
            L .= [0, 1]
            t = 1.0-h
            L_H .= L
            for i = $alg.acp:-1:1
                F,t = $alg.frestore(F_Check,i)
                for j= 1:$alg.period
                    $alg.fstore(F,F_Check_inner,t,j)
                    $(loop.args[2])
                end
                for j= $alg.period:-1:1
                    F,t = $alg.frestore(F_Check_inner,j)
                    L_H .= L
                    F_H .= F
                    res = Checkpointing.jacobian(tobedifferentiated, F_H, $adtool)
                    L =  transpose(res)*L
                    t = t - h
                end
            end
            F .= F_final
        end
    end
    esc(ex)
end


text:
#
# benchmarks.jl --
#
# Some speed tests for local filters.  Among others:
#
# * Naive (but otherwise fast) versions of filters which does not use the
#   `localfilter!` driver nor the smart algorithms implemented in LocalFilters;

isdefined(Main, :LocalFilters) || include("../src/LocalFilters.jl")
isdefined(Main, :NaiveLocalFilters) || include("NaiveLocalFilters.jl")

module LocalFiltersBenchmarks

const AUTORUN = true

using Compat
using Compat.Printf
using LocalFilters
using LocalFilters: Kernel, limits, cartesianregion, axes

import Base: eltype, ndims, size, length, first, last, tail,
    getindex, setindex!, convert

@static if isdefined(Base, :CartesianIndices)
    import Base: CartesianIndices
else
    import Base: CartesianRange
    import Compat: CartesianIndices
end

replicate(a, n::Integer) = ntuple(i->a, n)
compare(a, b) = maximum(abs(a - b))
samevalues(a, b) = maximum(a == b)
function similarvalues(A::AbstractArray{T,N}, B::AbstractArray{T,N};
                       atol=0.0, gtol=0.0) where {T,N}
    @assert axes(A) == axes(B)
    local sd2::Float64 = 0.0
    local sa2::Float64 = 0.0
    local sb2::Float64 = 0.0
    @inbounds for i in eachindex(A, B)
        a = Float64(A[i])
        b = Float64(B[i])
        sa2 += a*a
        sb2 += b*b
        sd2 += (a - b)^2
    end
    return sqrt(sd2) ≤ atol + gtol*sqrt(max(sa2, sb2))
end

#------------------------------------------------------------------------------

function checkresult(txt, tst::Bool)
    print(txt)
    checkresult(tst)
end

function checkresult(tst::Bool)
    if tst
        printstyled("ok"; color=:green)
    else
        printstyled("no"; color=:red)
    end
end

if AUTORUN
    n = 1000
    a = rand(62,81)
    box = RectangularBox(3,5)
    rngs = (-1:1, -2:2)
    mask = Kernel(box)
    kern = Kernel(eltype(a), ones(size(box)))
    a0 = similar(a)
    a1 = similar(a)
    a2 = similar(a)
    a3 = similar(a)
    a4 = similar(a)
    a5 = similar(a)

    tests = (:Base, :NTuple, :NTupleVar, :Map)
    for (name, B) in (("RectangularBox", box),
                      ("boolean kernel", mask),
                      ("non-boolean kernel", kern))
        println("\nErosion on a $name (timings on $n iterations):")
        erode!(Val(:Base), a0, a, B)
        for v in (B === box ? (tests..., :Naive) : tests)
            erode!(Val(v), a1, a, B)
            @printf "   Variant %-10s (" v
            checkresult(samevalues(a1, a0))
            print("): ")
            @time for i in 1:n; erode!(Val(v), a0, a, B); end
        end
        if B === box
            erode!(a1, a, :, rngs)
            @printf "   Variant %-10s (" "vHGW"
            checkresult(samevalues(a1, a0))
            print("): ")
            @time for i in 1:n; erode!(a1, a, :, rngs); end
        end

        println("\nDilation on a $name (timings on $n iterations):")
        dilate!(Val(:Base), a0, a, B)
        for v in (B === box ? (tests..., :Naive) : tests)
            dilate!(Val(v), a1, a, B)
            @printf "   Variant %-10s (" v
            checkresult(samevalues(a1, a0))
            print("): ")
            @time for i in 1:n; dilate!(Val(v), a1, a, B); end
        end
        if B === box
            dilate!(a1, a, :, rngs)
            @printf "   Variant %-10s (" "vHGW"
            checkresult(samevalues(a1, a0))
            print("): ")
            @time for i in 1:n; dilate!(a1, a, :, rngs); end
        end

        println("\nErosion and dilation on a $name (timings on $n iterations):")
        erode!(Val(:Base), a0, a, B)
        dilate!(Val(:Base), a1, a, B)
        for v in tests
            localextrema!(Val(v), a2, a3, a, B)
            @printf "   Variant %-10s (" v
            checkresult(samevalues(a2, a0) && samevalues(a3, a1))
            print("): ")
            @time for i in 1:n; localextrema!(Val(v), a2, a3, a, B); end
        end

        println("\nLocal mean on a $name (timings on $n iterations):")
        localmean!(Val(:Base), a0, a, B)
        for v in tests
            localmean!(Val(v), a1, a, B)
            @printf "   Variant %-10s (" v
            checkresult(similarvalues(a1, a0; gtol=4*eps(Float64)))
            print("): ")
            @time for i in 1:n; localmean!(Val(v), a1, a, B); end
        end

        if isa(B, Kernel) && eltype(B) != Bool
            println("\nConvolution by a $name (timings on $n iterations):")
            convolve!(Val(:Base), a0, a, B)
            for v in tests
                convolve!(Val(v), a1, a, B)
                @printf "   Variant %-10s (" v
                checkresult(similarvalues(a1, a0; gtol=4*eps(Float64)))
                print("): ")
                @time for i in 1:n; convolve!(Val(v), a1, a, B); end
            end
        end
        println()
    end

end

end # module


text:
module LifeValFunc

using JuliaDB, DataFrames

using LifeValStructures

export Table_to_Policies, Table_Length

function unitPFunction(initVal, incr, rows)
    unitP = [initVal] .* (1 .+ incr) .^ (1 / 12) #unitP[1] is at end of first month
    for i in 2:rows
        append!(unitP, unitP[i-1] .* (1 .+ incr) .^ (1 / 12))
    end
    return(unitP)
end

function Table_to_Policies(policyTable::IndexedTable, productIndex, columnsIndex, PolicyType)
    #global PolicyType
    n = length(policyTable)
    # convert to policy and append to vector
    # change column order to correspond to fields                                                         of Policy
    orderedInput = JuliaDB.select(policyTable, columnsIndex)
    # create product identifier in vector
    product = JuliaDB.select(policyTable, productIndex)
    PolicyVector = Vector{LifeValStructures.Policy}(undef, n)
    # eventually create struct called policyVector
    for i in 1:n
        type = PolicyType[product[i]]
        PolicyVector[i] = type(orderedInput[i]...)
    end

    return PolicyVector
end

function Table_Length(policyTable::Array{IndexedTable}, runsettings)
    n = length(policyTable)
    maxlength = 0
    for i in 1:n
        if length(policyTable[i]) > maxlength
            maxlength = length(policyTable[i])
        end
    end
    reserveList = Array{Float64}(undef, maxlength, nrow(runsettings))
    return reserveList
end

end


text:
# load code
include("param.jl")
include("mesh.jl")
include("buffer.jl")
include("test.jl")
include("timers.jl")


text:
using LiveServer
serve(dir="build")


text:
module Bigram

function ngram(t,n)
    gram = Dict{String,Int64}()
    T = collect(t)
    N = length(T)
    for i = 1:N-n+1
        s = String(T[i:i+n-1])
        if haskey(gram,s)
            gram[s] += 1
        else
            gram[s] = 1
        end
    end

    return gram
end

function removeChar(t,c)
    t = filter(e->e!=c,t)
    return t
end

function removeChars(t,c)
    t = filter(e->!(e in c),t)
    return t
end

function removeNumbers(t)
    c = ['0','1','2','3','4','5','6','7','8','9']
    t = removeChars(t,c)
    return t
end

function keepChars(t,c)
    return filter(e -> (e in c),t)
end

function removePunctuation(t)
    c = ['.',',','\'','?','!','(',')','{','}','[',']','&', ':', ';', '\"', '/','>','<','|']
    t = removeChars(t,c)
    return t
end

C = ['\u0009','\u000A','\u000B','\u000C','\u000D','\u0085','\u00A0','\u1680',
         '\u2000','\u2001','\u2002','\u2003','\u2004','\u2005','\u2006','\u2007',
         '\u2008','\u2009','\u200A','\u2028','\u2029','\u202F','\u205F','\u3000']

function replaceWhitespace(t)
    T = collect(t)
    for i = 1:length(T)
        if T[i] in C
            T[i] = ' '
        end
    end
    return String(T)
end

function condenseWhitespace(t)
    T = collect(t)
    newT = ""
    newT = newT*T[1]
    for i = 2:length(T)
        if (T[i] == ' ' && T[i-1] != ' ') || T[i] != ' '
            newT = newT*T[i]
        end
    end

    T = collect(newT)
    s=1
    e=length(T)
    if T[1] == ' '
        s = 2
    end
    if T[e] == ' '
        e -= 1
    end

    return newT[s:e]
end

function absoluteDiscount(mu,delta)
    k = length(mu)
    n = Int(sum(mu))
    D = sum(mu .> 0.0)

    for i = 1:k
        if mu[i] == 0.0
            mu[i] = (D*delta)/(n*(k-D))
        else
            mu[i] = (mu[i]-delta)/n
        end
    end

    return mu
end

function ngramTransMatrix(text,alphabet,N; maxdelta = 0.9)
    k = length(alphabet)
    Ngram = ngram(text,N)
    Nm1gram = ngram(text,N-1)

    println("Grams created")

    ind2gram = [key for key in keys(Nm1gram)]

    n = length(ind2gram)

    M = zeros(n, k)
    println("Creating M")
    for i = 1:n
        prefix = ind2gram[i]
        for j = 1:k
            nextLetter = alphabet[j]
            key = prefix*nextLetter
            if haskey(Ngram,key)
                M[i,j] = Ngram[key]
            end
        end
        phi = sum(M[i,:] .== 1.0)
        D = sum(M[i,:] .> 0.0)

        if D == 0
            M[i,:] = ones(k)/k
        else
            delta = min(max(phi,1)/D, maxdelta)
            M[i,:] = absoluteDiscount(M[i,:],delta)
        end
    end

    return M,Nm1gram,ind2gram
end

function gramToInd(ind2gram)
    gram2ind = Dict{String, Integer}()
    for i = 1:length(ind2gram)
        gram2ind[ind2gram[i]] = i
    end

    return gram2ind
end

end


text:
# to save the name
macro getName(arg)
  string(arg)
end


text:
function f() if false y=1 end; println(y); y = 1 end
f()

max_stars_repo_name: gabriel-doriath-dohler/pjulia

max_issues_repo_name: gabriel-doriath-dohler/pjulia

max_forks_repo_name: gabriel-doriath-dohler/pjulia


text:
using CSV, Interpolations, DataFrames, JuMP, Ipopt

"""
    awa(twa, v_s, v_t)

Calculate the apparent wind angle given true wind angle, boat speed and wind speed.

# Example
#
# ```jldoctest
# using sail_route
# c_awa = sail_route.awa(60, 3.086, 5.144)
# isapprox(0.6669807044553968, c_awa, rtol=3)
#
# # output
#
# true
# ```
# """
awa(twa, v_s, v_t) = atan(sind(twa)/(cosd(twa) + v_s/v_t))

"""
    Performance(polar, uncertainty, acceptable_failure, wave_resistance)

Type to hold sailing craft performance information.

Arguments:

- twa: Array of true wind angles for each point in polar plot.
- tws: Array of true wind speeds for each point in polar plot.
- boat_perf: Interpolations instance.

"""
struct Performance
    polar
    uncertainty::Float64
    acceptable_failure::Float64
    wave_resistance
end

"""
    load_file(path)

Load the file specified by path.
"""
function load_file(path)
    df = CSV.read(path, delim=';', datarow=1)
    perf = convert(Matrix, df[2:end, 2:end])
    tws = [df[1, col] for col in 2:ncol(df)]
    twa = map(x->parse(Float64, x), df[2:end, 1])
    return convert(Array{Float64}, twa), convert(Array{Float64},tws), perf
end

"""
    setup_perf_interpolation(tws, twa, perf)

Return interpolation object.
"""
function setup_perf_interpolation(tws, twa, perf)
    knots = (twa, tws)
    itp = interpolate(knots, perf, Gridded(Linear()))
    etp0 = extrapolate(itp, Flat())
    return etp0
end

"""
functionterp(itp, twa, tws)

Return interpolated performance. Convert from ms to knots here.
"""
@fastmath function perf_interp(performance::Performance, twa, tws)
    if twa < performance.polar.itp.knots[1][1]
        return 0.0
    else
        v = performance.polar(twa, tws)*performance.uncertainty
        if v > 0.0
            return v
        else
            return 0
        end
    end
end

"""Calculate the minimum distance between two angles."""
@inline @fastmath function min_angle(a, b)
    return abs(atand(sind(a-b), cosd(a-b)))
end

"""Generic Aerrtsen typical speed loss values. Needs to be made more specific."""
function typical_aerrtsen()
    itp = interpolate(([0.2, 0.6, 1.5, 2.3, 4.2, 8.2],), [1.0, 0.99, 0.97, 0.94, 0.83, 0.60], Gridded(Linear()))
    etp = extrapolate(itp, Line())
    return etp
end

@inline @fastmath wwd_to_md(x)=mod2pi(deg2rad(270.0-x))
@inline @fastmath md_to_wwd(x)=mod(rad2deg(x)-270.0, 360.0)

"""Resolve the wind and current vectors."""
@fastmath function w_c(twa, tws, ca, cs)
    twa = wwd_to_md(twa)
    ca = wwd_to_md(ca)
    x = tws*cos(twa) + cs*cos(ca)
    y = tws*sin(twa) + cs*sin(ca)
    w_c_s = sqrt(x^2+y^2)
    w_c_a = md_to_wwd(atan(y, x))
    return w_c_s, w_c_a
end

"""Return the speed of a sailing craft"""
@fastmath function cost_func(ϕ, tws, twa, cs, ca, wahi, perf)
    w_c_s, w_c_a = w_c(twa, tws, ca, cs)
    awa = min_angle(w_c_a, ϕ)
    return perf_interp(perf, awa, w_c_s)*perf.wave_resistance(wahi)
end

"""Calculate the speed of the sailing craft given the current."""
function solve_speed_given_current(tws, twa, cs, ca, wahi, bearing, perf)
    p(ϕ) = cost_func(ϕ, tws, twa, cs, ca, wahi, perf)
    ca = wwd_to_md(ca)
    h_comp(ϕ) = p(ϕ)*sind(bearing-ϕ)-cs*sind(ca-bearing)
    v_comp(ϕ) = p(ϕ)*cosd(bearing-ϕ)
    model = Model(with_optimizer(Ipopt.Optimizer,print_level=0, warm_start_init_point="yes",max_iter=30, acceptable_tol=0.2))
    # variables
    @variable(model, 0.0 <= ϕ <= 360.0, start=bearing)
    # register functions
    register(model, :p, 1, p, autodiff=true)
    register(model, :h_comp, 1, h_comp, autodiff=true)
    register(model, :v_comp, 1, v_comp, autodiff=true)
    # constraints
    @NLconstraint(model, con1, h_comp(ϕ)==0.0)
    @NLconstraint(model, con2, v_comp(ϕ)>=0.0)
    # objective function
    @NLobjective(model, Max, v_comp(ϕ))
    JuMP.optimize!(model)
    return v_comp(value.(ϕ))
end

"""
Cost function to use within routing simulation.
"""
function cost_function(performance, cudi, cusp, widi, wisp, wadi, wahi, bearing)
    return solve_speed_given_current(wisp, widi, cusp, cudi, wahi, bearing, performance)
end

"""Generate range of modified polars for performance uncertainty simulation."""
function generate_performance_uncertainty_samples(polar, params, wave_m)
    unc_perf = [Performance(polar, i, 1.0, wave_m) for i in params]
end


text:
using FixedSizeArrays
using PlotlyJS

import Base: *, isless

include("utils.jl");
include("algorithms.jl");

p = [Point(randn(), randn()) for i=1:250];
ep = _akltoussaint(p)

# a = Point(0.0, 0.0)
# b = Point(1.0, 0.1)
# c = Point(0.5, 0.4)
# d = Point(1.0, 1.0)
# e = Point(0.1, 1.0)

# wrappoints([a, b, c, d, e, a])

ep_g = _grahamscan(p)
ep_m = _monotonechain(p)

# Plot all points
t1 = scatter(;x=[i[1] for i in p], y=[i[2] for i in p], mode="markers")

# Plot Convex hull from graham scan
t2 = scatter(;x=[i[1] for i in ep_g], y=[i[2] for i in ep_g], mode="lines")

# Plot upper hull
t3 = scatter(;x=[i[1] for i in ep_m], y=[i[2] for i in ep_m], mode="lines")

show(Plot([t1, t2, t3]))


text:
using CounterfactualExplanations
using Test
using Random
Random.seed!(0)

@testset "CounterfactualExplanations.jl" begin

    @testset "Data" begin
        include("data.jl")
    end

    @testset "Data preprocessing" begin
        include("data_preprocessing.jl")
    end

    @testset "Counterfactuals" begin
        include("counterfactuals.jl")
    end

    @testset "Generators" begin
        include("generators.jl")
    end

    @testset "Model" begin
        include("models.jl")
    end

end


text:
########################################################################################################################
# init_batch_model
function init_batch_model(id_isolate, id_monomer, assimilation, enzymes, maintenance, protein_synthesis, turnover)
    #
    n_polymers = 0
    n_monomers = 1
    n_microbes = 1
    n_enzymes  = 1
    n_minerals = 0
    p_set      = Setup(n_polymers, n_monomers, n_microbes, n_enzymes, n_minerals)
    #
    k_E        = protein_synthesis["kE"][id_isolate]
    y_EV       = protein_synthesis["yEV"][id_isolate]
    k_M        = maintenance["kM"][id_isolate]
    y_EM       = assimilation["yEM"][id_isolate]
    α_X        = enzymes["alpha"][id_isolate]
    y_EX       = y_EV
    f_αX       = ones(n_enzymes)
    min_gt     = protein_synthesis["mingt"][id_isolate]
    p_met      = MetabolismC([k_E], [y_EV], [k_M], [y_EM], [α_X], [y_EX], min_gt)
    #
    N_SB       = assimilation["NSB"][id_monomer,id_isolate]
    K_D        = assimilation["KD"][id_monomer,id_isolate]
    y_DE       = assimilation["yDE"][id_monomer]
    N_C        = assimilation["NC"][id_monomer]
    N_X        = 1
    p_ass      = AssimilationC(N_SB*ones(1,1),K_D*ones(1,1),[y_DE],[N_C],N_X)
    #
    γ_V0       = turnover["gV0"][id_isolate]
    γ_V1       = turnover["gV1"]
    γ_X        = 1/(7*24)*ones(n_enzymes)
    #
    γ_D_ads    = zeros(n_monomers)
    γ_X_ads    = zeros(n_enzymes)
    f_ED       = ones(n_monomers)
    f_V        = ones(n_microbes)    # all structural biomass recycling to monomers
    f_VD       = ones(n_microbes)
    f_VP       = ones(n_microbes)
    f_X        = zeros(n_enzymes)    # all enzymes recycling to monomers
    f_XD       = ones(n_enzymes)
    f_XP       = ones(n_enzymes)
    p_turn     = Turnover([γ_V0],[γ_V1],γ_X,γ_D_ads,γ_X_ads,f_ED,f_VD,f_VP,f_V,f_XD,f_XP,f_X)
    #
    p = Params(p_set,p_met,p_ass,nothing,p_turn)
end
########################################################################################################################

########################################################################################################################
# batch model
function batch_model!(du, u, p, t)
    D, E, V, X, CO2 = DEBmicroTrait.split_state_batch(u, p)
    # setup
    n_polymers                = p.setup_pars.n_polymers
    n_monomers                = p.setup_pars.n_monomers
    n_microbes                = p.setup_pars.n_microbes
    n_enzymes                 = p.setup_pars.n_enzymes
    # metabolism
    r                         = growth!(0.0*ones(n_microbes), p.metabolism_pars, E, V)
    x, rG_CO2, rM_CO2, rX_CO2 = growth_production!(r, p.metabolism_pars, E, V)
    J_EX                      = enzyme_production!(x, p.metabolism_pars, V)
    # assimilation
    J_DE         = assimilation!(zeros(n_microbes), p.assimilation_pars, D, V)
    J_DE_CO2     = assimilation_production!(zeros(n_microbes), p.assimilation_pars, D, V)
    J_D          = uptake!(zeros(n_monomers), p.assimilation_pars, D, V)
    # turnover
    J_ED         = reserve_recycling!(zeros(n_monomers), p.turnover_pars, E)
    J_X          = enzyme_decay!(zeros(n_enzymes), p.turnover_pars, X)
    J_XD, J_XP   = enzyme_recycling!(zeros(n_monomers), p.turnover_pars, X)
    J_V          = biomass_turnover!(zeros(n_microbes), p.turnover_pars, V)
    J_VD, J_VP   = biomass_recycling!(zeros(n_monomers), p.turnover_pars, V)
    J_E          = biomass_turnover!(zeros(n_microbes), p.turnover_pars, E)
    # system
    @. du[1+n_polymers:n_polymers+n_monomers] = - J_D + J_ED + J_VD + J_XD
    @. du[1+n_polymers+n_monomers:n_polymers+n_monomers+n_microbes] =  J_DE - (p.metabolism_pars.k_E - r)*E - J_E
    @. du[1+n_polymers+n_monomers+n_microbes:n_polymers+n_monomers+2*n_microbes] = r*V - J_V
    @. du[1+n_polymers+n_monomers+2*n_microbes:n_polymers+n_monomers+2*n_microbes+n_enzymes] = J_EX - J_X
    @. du[1+n_polymers+n_monomers+2*n_microbes+n_enzymes:n_polymers+n_monomers+2*n_microbes+n_enzymes+n_microbes] = rG_CO2 + rX_CO2 + rM_CO2 + J_DE_CO2
    return du
end
########################################################################################################################

max_stars_repo_name: giannamars/DEBMicroTrait

max_issues_repo_name: giannamars/DEBMicroTrait

max_forks_repo_name: giannamars/DEBMicroTrait


text:
function ueberpruefeAbsorptionskoeffizientena(Zeile1,Zeile2,Zeile3,Spalte1,Spalte2,Spalte3,Diagonale,f1,f2,f3,f4,f5,f6,f7,f8,f9)

    Zeile1 = 20-Zeile1;
    Zeile2 = 20-Zeile2;
    Zeile3 = 20-Zeile3;
    Spalte1 = 20-Spalte1;
    Spalte2 = 20-Spalte2;
    Spalte3 = 20-Spalte3;
    Diagonale = 20-Diagonale;

    if (Zeile1 == f1+f4+f7) && (Zeile2 == f2+f5+f8) && (Zeile3 == f3+f6+f9) && (Spalte1 == f1+f2+f3) && (Spalte2 == f4+f5+f6) && (Spalte3 == f7+f8+f9) && (round(Diagonale;digits =2) == round(f3*sqrt(2)+f5*sqrt(2)+f7*sqrt(2);digits=2))
        println("Ihr habt eine mögliche Verteilung der Absorptionskoeffizienten gefunden!")
    else
        println("Überprüft noch einmal, ob wirklich alle Zeilen- und Spaltensummen erfüllt sind.")
    end

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"""DownwardAPIVolumeSource represents a volume containing downward API info. Downward API volumes support ownership management and SELinux relabeling.

    IoK8sApiCoreV1DownwardAPIVolumeSource(;
        defaultMode=nothing,
        items=nothing,
    )

    - defaultMode::Int32 : Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
    - items::Vector{IoK8sApiCoreV1DownwardAPIVolumeFile} : Items is a list of downward API volume file
"""
mutable struct IoK8sApiCoreV1DownwardAPIVolumeSource <: SwaggerModel
    defaultMode::Any # spec type: Union{ Nothing, Int32 } # spec name: defaultMode
    items::Any # spec type: Union{ Nothing, Vector{IoK8sApiCoreV1DownwardAPIVolumeFile} } # spec name: items

    function IoK8sApiCoreV1DownwardAPIVolumeSource(;defaultMode=nothing, items=nothing)
        o = new()
        validate_property(IoK8sApiCoreV1DownwardAPIVolumeSource, Symbol("defaultMode"), defaultMode)
        setfield!(o, Symbol("defaultMode"), defaultMode)
        validate_property(IoK8sApiCoreV1DownwardAPIVolumeSource, Symbol("items"), items)
        setfield!(o, Symbol("items"), items)
        o
    end
end # type IoK8sApiCoreV1DownwardAPIVolumeSource

const _property_map_IoK8sApiCoreV1DownwardAPIVolumeSource = Dict{Symbol,Symbol}(Symbol("defaultMode")=>Symbol("defaultMode"), Symbol("items")=>Symbol("items"))
const _property_types_IoK8sApiCoreV1DownwardAPIVolumeSource = Dict{Symbol,String}(Symbol("defaultMode")=>"Int32", Symbol("items")=>"Vector{IoK8sApiCoreV1DownwardAPIVolumeFile}")
Base.propertynames(::Type{ IoK8sApiCoreV1DownwardAPIVolumeSource }) = collect(keys(_property_map_IoK8sApiCoreV1DownwardAPIVolumeSource))
Swagger.property_type(::Type{ IoK8sApiCoreV1DownwardAPIVolumeSource }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiCoreV1DownwardAPIVolumeSource[name]))}
Swagger.field_name(::Type{ IoK8sApiCoreV1DownwardAPIVolumeSource }, property_name::Symbol) =  _property_map_IoK8sApiCoreV1DownwardAPIVolumeSource[property_name]

function check_required(o::IoK8sApiCoreV1DownwardAPIVolumeSource)
    true
end

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


text:
"""
$(SIGNATURES)

Helper function for `convert_inter_html` that processes an extracted block given a latex context
`lxc` and returns the processed html that needs to be plugged in the final html.
"""
function convert_block(β::AbstractBlock, lxcontext::LxContext)::AS
    # case for special characters / html entities
    β isa HTML_SPCH     && return ifelse(isempty(β.r), β.ss, β.r)
    # Return relevant interpolated string based on case
    βn = β.name
    βn ∈  MD_HEADER        && return convert_header(β)
    βn == :CODE_INLINE     && return html_code_inline(content(β) |> htmlesc)
    βn == :CODE_BLOCK_LANG && return convert_code_block(β.ss)
    βn == :CODE_BLOCK_IND  && return convert_indented_code_block(β.ss)
    βn == :CODE_BLOCK      && return html_code(strip(content(β)), "{{fill lang}}")
    βn == :ESCAPE          && return chop(β.ss, head=3, tail=3)
    βn == :FOOTNOTE_REF    && return convert_footnote_ref(β)
    βn == :FOOTNOTE_DEF    && return convert_footnote_def(β, lxcontext)
    βn == :LINK_DEF        && return ""

    # Math block --> needs to call further processing to resolve possible latex
    βn ∈ MATH_BLOCKS_NAMES && return convert_math_block(β, lxcontext.lxdefs)

    # Div block --> need to process the block as a sub-element
    if βn == :DIV
        ct, _ = convert_md(content(β) * EOS, lxcontext.lxdefs;
                           isrecursive=true, has_mddefs=false)
        name = chop(otok(β).ss, head=2, tail=0)
        return html_div(name, ct)
    end

    # default case, ignore block (should not happen)
    return ""
end
convert_block(β::LxCom, λ::LxContext) = resolve_lxcom(β, λ.lxdefs)

"""
MATH_BLOCKS_PARENS

Dictionary to keep track of how math blocks are fenced in standard LaTeX and how these fences need
to be adapted for compatibility with KaTeX. Each tuple contains the number of characters to chop
off the front and the back of the maths expression (fences) as well as the KaTeX-compatible
replacement.
For instance, `\$ ... \$` will become `\\( ... \\)` chopping off 1 character at the front and the
back (`\$` sign).
"""
const MATH_BLOCKS_PARENS = Dict{Symbol, Tuple{Int,Int,String,String}}(
    :MATH_A     => ( 1,  1, "\\(", "\\)"),
    :MATH_B     => ( 2,  2, "\\[", "\\]"),
    :MATH_C     => ( 2,  2, "\\[", "\\]"),
    :MATH_ALIGN => (13, 11, "\\[\\begin{aligned}", "\\end{aligned}\\]"),
    :MATH_EQA   => (16, 14, "\\[\\begin{array}{c}", "\\end{array}\\]"),
    :MATH_I     => ( 4,  4, "", "")
    )

"""
$(SIGNATURES)

Helper function for the math block case of `convert_block` taking the inside of a math block,
resolving any latex command in it and returning the correct syntax that KaTeX can render.
"""
function convert_math_block(β::OCBlock, lxdefs::Vector{LxDef})::String
    # try to find the block out of `MATH_BLOCKS_PARENS`, if not found, error
    pm = get(MATH_BLOCKS_PARENS, β.name) do
        throw(MathBlockError("Unrecognised math block name."))
    end

    # convert the inside, decorate with KaTex and return, also act if
    # if the math block is a "display" one (with a number)
    inner = chop(β.ss, head=pm[1], tail=pm[2])
    htmls = IOBuffer()
    if β.name ∉ [:MATH_A, :MATH_I]
        # NOTE: in the future if allow equation tags, then will need an `if`
        # here and only increment if there's no tag. For now just use numbers.

        # increment equation counter
        PAGE_EQREFS[PAGE_EQREFS_COUNTER] += 1

        # check if there's a label, if there is, add that to the dictionary
        matched = match(r"\\label{(.*?)}", inner)

        if !isnothing(matched)
            name   = refstring(matched.captures[1])
            write(htmls, "")
            inner  = replace(inner, r"\\label{.*?}" => "")
            # store the label name and associated number
            PAGE_EQREFS[name] = PAGE_EQREFS[PAGE_EQREFS_COUNTER]
        end
    end
    # assemble the katex decorators, the resolved content etc
    write(htmls, pm[3], convert_md_math(inner * EOS, lxdefs, from(β)), pm[4])
    return String(take!(htmls))
end

"""
$(SIGNATURES)

Helper function for the case of a header block (H1, ..., H6).
"""
function convert_header(β::OCBlock)::String
    hk       = lowercase(string(β.name))
    title, _ = convert_md(content(β) * EOS; isrecursive=true, has_mddefs=false)
    # check if the header has appeared before
    rstitle  = refstring(title)
    level    = parse(Int, hk[2])
    occur    = (hv[3] for hv ∈ values(PAGE_HEADERS) if hv[2] == rstitle)
    occur    = isempty(occur) ? 0 : maximum(occur)
    rstitle  = ifelse(occur==0, rstitle, "$(rstitle)_$(occur+1)")
    # save in list of headers
    PAGE_HEADERS[length(PAGE_HEADERS)+1] = (title, rstitle, occur+1, level)
    # return the title
    return html_hk(hk, html_ahref_key(rstitle, title); id=rstitle)
end

"""
$(SIGNATURES)

Helper function for the code block case of `convert_block`.
"""
function convert_code_block(ss::SubString)::String
    fencer = ifelse(startswith(ss, "`````"), "`````", "```")
    reg    = Regex("$fencer([a-z-]*)(\\:[a-zA-Z\\\\\\/-_\\.]+)?\\s*\\n?((?:.|\\n)*)$fencer")
    m      = match(reg, ss)
    lang  = m.captures[1]
    rpath = m.captures[2]
    code  = m.captures[3]

    if isnothing(rpath)
        return html_code(code, lang)
    end
    if lang!="julia"
        @warn "Eval of non-julia code blocks is not yet supported."
        return html_code(code, lang)
    end
    # path currently has an indicative `:` we don't care about
    rpath = rpath[2:end]

    # Here we have a julia code block that was provided with a script path
    # It will consequently be
    #   1. written to script file unless it's already there
    #   2. evaled (unless a file was there and output file is present), redirect out
    #   3. inserted after scrapping out lines (see resolve_lx_input)
    path = resolve_assets_rpath(rpath; canonical=true)

    endswith(path, ".jl") || (path *= ".jl")

    out_path, fname = splitdir(path)
    out_path = mkpath(joinpath(out_path, "output"))
    out_name = splitext(fname)[1] * ".out"
    out_path = joinpath(out_path, out_name)

    # > 1.b check whether the file already exists and if so compare content
    do_eval = !isfile(path) || read(path, String) != code || !isfile(out_path)

    if do_eval
        write(path, "# This file was generated by JuDoc, do not modify it. # hide\n", code)
        # step 2: execute the code while redirecting the output to file (note that
        # everything is ran in one big sequence of scripts so in particular if there
        # are 3 code blocks on the same page then the second and third one can use
        # whatever is defined or loaded in the first (it also has access to scope of
        # other pages but it's really not recommended to exploit that)
        open(out_path, "w") do outf
            redirect_stdout(outf)  do
                try
                    Main.include(path)
                catch e
                    print("There was an error running the code: $(e.error).")
                end
            end
        end
    end

    # step 3, insertion of code stripping of "hide" lines.
    return resolve_lx_input_hlcode(rpath, "julia")
end

"""
$(SIGNATURES)

Helper function for the indented code block case of `convert_block`.
"""
function convert_indented_code_block(ss::SubString)::String
    # 1. decrease indentation of all lines (either frontal \n\t or \n⎵⎵⎵⎵)
    code = replace(ss, r"\n(?:\t| {4})" => "\n")
    # 2. return; lang is a LOCAL_PAGE_VARS that is julia by default and can be set
    sc = strip(code)
    isempty(sc) && return ""
    return html_code(sc, "{{fill lang}}")
end

"""
$(SIGNATURES)

Helper function to convert a `[^1]` into a html sup object with appropriate ref and backref.
"""
function convert_footnote_ref(β::Token)::String
    # β.ss is [^id]; extract id
    id = string(match(r"\[\^(.*?)\]", β.ss).captures[1])
    # add it to the list of refs unless it's been seen before
    pos = 0
    for (i, pri) in enumerate(PAGE_FNREFS)
        if pri == id
            pos = i
            break
        end
    end
    if pos == 0
        push!(PAGE_FNREFS, id)
        pos = length(PAGE_FNREFS)
    end
    return html_sup("fnref:$id", html_ahref(url_curpage() * "#fndef:$id", "[$pos]"; class="fnref"))
end

"""
$(SIGNATURES)

Helper function to convert a `[^1]: ...` into a html table for the def.
"""
function convert_footnote_def(β::OCBlock, lxcontext::LxContext)::String
    # otok(β) is [^id]:
    id = match(r"\[\^(.*?)\]:", otok(β).ss).captures[1]
    pos = 0
    for (i, pri) in enumerate(PAGE_FNREFS)
        if pri == id
            pos = i
            break
        end
    end
    if pos == 0
        # this was never referenced before, so probably best not to show it
        return ""
    end
    # need to process the content which could contain stuff
    ct, _ = convert_md(content(β) * EOS, lxcontext.lxdefs;
                       isrecursive=true, has_mddefs=false)
    """

            $(html_ahref(url_curpage() * "#fnref:$id", "[$pos]"))
            $(ct)

    """
end


text:
function Resistor(; name, R = 1.0)
    # 2 pin component
    @named oneport = OnePort()
    @unpack v, i = oneport
    ps = @parameters R=R
    eqs = [
        v ~ i * R
    ]
    extend(ODESystem(eqs, t, [], ps; name), oneport)
end

function Capacitor(; name, C = 1.0)
    @named oneport = OnePort()
    @unpack v, i = oneport
    ps = @parameters C=C
    D = Differential(t)
    eqs = [
        D(v) ~ i / C
    ]
    extend(ODESystem(eqs, t, [], ps; name), oneport)
end

function Inductor(; name, L = 1.0)
    @named oneport = OnePort()
    @unpack v, i = oneport
    ps = @parameters L=L
    D = Differential(t)
    eqs = [
        D(i) ~ v / L
    ]
    extend(ODESystem(eqs, t, [], ps; name), oneport)
end