text:
module JSServe

import AssetRegistry, Sockets
using UUIDs, Hyperscript, Hyperscript, JSON3, Observables
import Sockets: send, TCPServer
using Hyperscript: Node, children, tag
using HTTP, Markdown
using HTTP: Response, Request
using HTTP.Streams: Stream
using WebSockets
using Base64
using MsgPack
# Needed, since we offer some extended testing functions to make it
# easier for downstream packages to test their web stuff
using Test

if VERSION < v"1.3-"
    include("compat.jl")
end

include("types.jl")
include("js_source.jl")
include("session.jl")
include("observables.jl")
include("dependencies.jl")
include("http.jl")
include("util.jl")
include("widgets.jl")
include("hyperscript_integration.jl")
include("display.jl")
include("jscall.jl")
include("markdown_integration.jl")
include("serialization.jl")
include("diffing.jl")

const active_sessions = nothing

function __init__()
    url = if haskey(ENV, "JULIA_WEBIO_BASEURL")
        ENV["JULIA_WEBIO_BASEURL"]
    else
        ""
    end
    if endswith(url, "/")
        url = url[1:end-1]
    end
    server_proxy_url[] = url
    atexit() do
        # remove session folder, in which we store data dependencies temporary
        # TODO remove whenever a session is closed to not accumulate waste until julia
        # gets closed
        rm(dependency_path("session_temp_data"), recursive=true, force=true)
    end
end

end # module


text:
#
# test FundamentalSolutions submodule
#
using ApproxFun, SingularIntegralEquations, Base.Test

x = collect(-10:0.5:10)
y = collect(-9.75:0.5:10.25)
E = collect(-10:10.0:10)

# These values were computed using the C-library of Barnett, Nelson, and Mahoney.

Φ = [(Complex{Float64}[0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,-2.7177786073940434e-15 + 7.088144176763204e-17im,1.915032314214556e-15 + 1.062472191604418e-15im,8.348561393138206e-14 - 2.0725829383749506e-15im,1.2906220044659275e-12 + 1.1233425015281e-15im,2.004352396756511e-11 + 4.050862755550819e-17im,2.99641288632409e-10 - 5.107640496654681e-15im,4.313365405406057e-9 - 1.6586670631087627e-18im,5.987650506478715e-8 + 2.678087274943622e-15im,8.036491088527181e-7 - 4.1566770191093646e-20im,1.0481911109243105e-5 - 1.3887627004584244e-15im,0.000134221034800493 + 3.479717996635153e-19im,0.0017274882801318313 - 1.6239902604124774e-18im,0.023860414153611623 - 1.1997678739439142e-18im,0.09199129960693156 + 7.044571562116214e-18im,0.007009655477148429 - 5.361158534508201e-19im,0.000656801067989086 + 1.41968589313552e-19im,7.097449259287094e-5 + 8.034735626738917e-19im,8.52124827834661e-6 + 1.39243737663054e-18im,1.1212652664570484e-6 + 1.1780007703932245e-17im,1.6088397622748281e-7 + 4.024624122391895e-17im,2.5146349735561583e-8 + 1.2738766636439244e-16im,4.287690609422299e-9 + 3.7525072451203737e-16im,8.002532610106711e-10 + 1.0189815858427598e-15im,1.6436828335746545e-10 + 2.5490151050909247e-15im,3.745131741348526e-11 + 5.826972594305736e-15im,9.583230364482935e-12 + 1.2106172621587705e-14im,2.808387401836333e-12 + 2.267473868228771e-14im,9.6822670788384e-13 + 3.790445542445573e-14im,3.9785460274139317e-13 + 5.57652511966692e-14im,1.841347268213127e-13 + 7.079656408295009e-14im,7.947869393575377e-14 + 7.51983684006048e-14im,1.6655950429201335e-14 + 6.31820949902256e-14im,-1.7603978963813583e-14 + 3.6705040150194534e-14im,-2.494775976802604e-14 + 7.321968406482739e-15im],Complex{Float64}[0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,4.058651603261031e-15 - 3.3115802072659474e-15im,-1.0204890401494459e-14 - 3.535604706904387e-15im,-2.0786904538586839e-13 + 4.453290687265494e-15im,-3.321378591264416e-12 - 4.479990671239373e-16im,-5.1417816151645136e-11 - 6.706175264740401e-17im,-7.669645098189046e-10 + 5.2622262439675785e-15im,-1.1033685491708622e-8 - 1.0497429531081222e-18im,-1.534482428409001e-7 - 7.474079515942788e-16im,-2.071950099402365e-6 + 8.578315985755632e-21im,-2.7392371905744022e-5 + 4.132840353574865e-16im,-0.0003610526514322561 - 8.767505001275645e-18im,-0.00497231308538903 + 7.721186803585204e-19im,-0.08514735493339759 - 1.515102199623331e-19im,0.0 + 0.0im,0.014064943892512593 + 2.606364950488978e-19im,0.0013769451909061016 + 2.4849783614898278e-20im,0.00014881197291795472 + 9.442328091684242e-20im,1.7697298954357147e-5 - 3.646614467754496e-18im,2.2972789015955277e-6 + 2.4623781602501203e-18im,3.2433230865361906e-7 + 1.1930262393096905e-17im,4.9769709355538425e-8 + 3.86984448505805e-17im,8.312880619793969e-9 + 1.322097402883273e-16im,1.5159473879140603e-9 + 4.0832136128495536e-16im,3.032683645624505e-10 + 1.171027295598021e-15im,6.70133397896639e-11 + 3.0164105919380474e-15im,1.6522756878836112e-11 + 7.022614976997634e-15im,4.6183165779036835e-12 + 1.468111037963438e-14im,1.4997920455131623e-12 + 2.7371179592677948e-14im,5.806163359979423e-13 + 4.4947462285522736e-14im,2.6413095263062726e-13 + 6.399048791805897e-14im,1.25284448006157e-13 + 7.706564900367722e-14im,4.466872610961881e-14 + 7.53109640844585e-14im,-5.9475507194407915e-15 + 5.472101684004291e-14im,-2.783133412396072e-14 + 2.232963705453047e-14im],Complex{Float64}[0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,0.0 + 0.0im,1.9202327473178666e-15 - 4.516794137340351e-15im,-1.0108563008573199e-14 - 4.43560261250676e-15im,-1.4930320520609354e-13 + 5.272099526023163e-15im,-2.5025455733347145e-12 + 1.1198934143539465e-15im,-3.935066826540064e-11 - 1.3333894014595015e-16im,-5.955985816601308e-10 + 6.0000339465122565e-15im,-8.677587171352468e-9 - 9.709198850408539e-18im,-1.2183935729024614e-7 + 2.371004385869295e-15im,-1.6523402690568737e-6 - 6.044302273255796e-20im,-2.1731701644251383e-5 - 4.6108614993603776e-17im,-0.00027920267779759506 - 7.340832077953816e-18im,-0.003541616266213967 - 1.409174634311243e-18im,-0.04125833513327128 + 5.027709985393252e-18im,0.445865880291157 + 2.5880367303763978e-17im,0.02169213202596337 - 5.556239971139944e-19im,0.0018156335452467099 + 6.633197947751877e-19im,0.00018815356766272066 + 2.5737836302712535e-18im,2.2193878188067997e-5 + 4.4632499309702165e-17im,2.9012378056546723e-6 + 3.761693814194309e-17im,4.160743340280872e-7 + 1.300219364398536e-16im,6.524461703332531e-8 + 4.0505404735836866e-16im,1.1189600646082624e-8 + 1.1938557058714125e-15im,2.104611664842445e-9 + 3.2343148006130445e-15im,4.3632530352087725e-10 + 8.074687438094622e-15im,1.0050167783571491e-10 + 1.8415960870073928e-14im,2.6043197623182808e-11 + 3.8139528966007313e-14im,7.746441972238439e-12 + 7.115672238749773e-14im,2.71696868073637e-12 + 1.1838471244276802e-13im,1.1348960689021464e-12 + 1.7312220159377177e-13im,5.293033772809371e-13 + 2.1806184108338944e-13im,2.2508141971530844e-13 + 2.29095305283336e-13im,4.0180539600264057e-14 + 1.8921489422173267e-13im,-5.884240745550609e-14 + 1.0611079589828134e-13im,-7.612611029342802e-14 + 1.6778751961906487e-14im]);
     (Complex{Float64}[-4.2207742054609445e-14 + 2.5582099967016215e-14im,-3.0640864285993137e-13 + 2.5582120932105505e-13im,-2.0381096673341605e-12 + 2.2873123165164373e-12im,-1.2291262971952923e-11 + 1.859168887769827e-11im,-6.593469034490949e-11 + 1.385823619623002e-10im,-3.0249880612095654e-10 + 9.518445208552073e-10im,-1.0682751675260649e-9 + 6.03929577130901e-9im,-1.639612588945498e-9 + 3.543551586947374e-8im,1.5177439798448966e-8 + 1.9228966824880425e-7im,1.9538821451619523e-7 + 9.64344580406234e-7im,1.4651459010156878e-6 + 4.463484556294712e-6im,8.740421991126924e-6 + 1.9029111396794245e-5im,4.469428878355194e-5 + 7.452957964701884e-5im,0.00020156564053186403 + 0.00026728008545472056im,0.0008121563495976686 + 0.0008740618464729511im,0.002942033678125101 + 0.002593159678899259im,0.009615189026887246 + 0.0069347922948135065im,0.028462894387744752 + 0.016579814378646977im,0.07718687796772232 + 0.035055532644951364im,0.20138079548989188 + 0.0645772090888822im,0.34449771280311725 + 0.10139785495345906im,0.14052000757498556 + 0.13097106387740856im,0.02416066593685897 + 0.1300068557958706im,-0.05658235113805852 + 0.08266935708982236im,-0.07931085671583328 + 0.00462601860978848im,-0.03663533617594418 - 0.05321036831038424im,0.026760299092560575 - 0.046114440363527194im,0.04370336518387192 + 0.007858483754800048im,0.003070419610705451 + 0.03706378262151246im,-0.030193447002630103 + 0.00807798138843038im,-0.009344484325229154 - 0.02460244627777213im,0.020502139451006922 - 0.008458004805011528im,0.006403003997704943 + 0.017561065479597644im,-0.015291241578608568 + 0.003758477628861037im,-0.0009006814895022193 - 0.013222608261887687im,0.010986335856433216 + 0.0018526653198289058im,-0.0041698682550289495 + 0.008371569174473147im,-0.005374203921470931 - 0.005705566107920749im,0.006168626185334842 - 0.0022233665542553426im,-0.0006469760319096293 + 0.00543662347493285im,-0.00366973959806075 - 0.0027106956531463824im],Complex{Float64}[4.1501911810981205e-14 - 5.486825532069073e-14im,2.598015692762275e-13 - 4.781987909335566e-13im,1.4047271789562447e-12 - 3.83242748715863e-12im,6.00534428544889e-12 - 2.8360162116211566e-11im,1.3563725949235504e-11 - 1.9419039405781347e-10im,-8.06580310046677e-11 - 1.2313465437952206e-9im,-1.4406602374465107e-9 - 7.229463827730596e-9im,-1.3189939420484509e-8 - 3.926581726828507e-8im,-9.45379851033821e-8 - 1.96979117233407e-7im,-5.796509661138316e-7 - 9.106358457976207e-7im,-3.1419226543336096e-6 - 3.8680581450532525e-6im,-1.5282310255001012e-5 - 1.503818516968255e-5im,-6.719529848171383e-5 - 5.324851620953596e-5im,-0.0002680454396954023 - 0.00017062325723433142im,-0.0009717798716489432 - 0.0004905135740319524im,-0.0032067896279610445 - 0.0012499929398858088im,-0.009668292882845425 - 0.0027728301899642743im,-0.026977367524609042 - 0.005193188288550748im,-0.07308799203104946 - 0.0077188747645003065im,-0.24216642239493244 - 0.00759564827245433im,0.0 + 0.0im,0.10482641731156107 + 0.018876882010997017im,0.06322656141965662 + 0.04490914283998468im,0.01797329476820751 + 0.06112064534364743im,-0.028891627647689933 + 0.046628824932477365im,-0.048075504374452245 + 0.0017685884582004105im,-0.020787097889397758 - 0.03706195723683278im,0.02389309422704863 - 0.029050563777788568im,0.030524348608791513 + 0.013269799039853643im,-0.006349334744224723 + 0.028710735611595234im,-0.025772539794501236 - 0.0027219301378680434im,0.0015512037853623508 - 0.022724926296232694im,0.019854350669049014 + 0.0020433994451300383im,-0.003551339961524409 + 0.017068561901514782im,-0.014135156767161062 - 0.005531901366146632im,0.007478384063701854 - 0.010843738387818137im,0.0071263958215239094 + 0.008889638031851362im,-0.009305585810744019 + 0.0031442615413370596im,0.000681702950876991 - 0.008412845320355107im,0.006190598197107229 + 0.003733713493470452im,-0.005379105649981245 + 0.003026950791353769im],Complex{Float64}[-4.8387735622072593e-14 - 4.071998081485528e-14im,-4.230839565694019e-13 - 2.6189596650869957e-13im,-3.3973007152248344e-12 - 1.4897618787691359e-12im,-2.5173916780737902e-11 - 7.149229885146233e-12im,-1.7259447220387145e-10 - 2.5175674018024192e-11im,-1.0962990057119443e-9 - 1.9673683456074828e-11im,-6.454309347468289e-9 + 6.715003988687346e-10im,-3.521487276373733e-8 + 7.859326678373458e-9im,-1.779610914993488e-7 + 6.081881080408569e-8im,-8.323736415592234e-7 + 3.8397456587549035e-7im,-3.6005161914359747e-6 + 2.0973915769076318e-6im,-1.4395240646545717e-5 + 1.0147063634294516e-5im,-5.319704847892867e-5 + 4.393362944036802e-5im,-0.00018191174704171068 + 0.0001709442450787586im,-0.0005773603176132271 + 0.000598035217970257im,-0.0017109546437779643 + 0.0018770891140273934im,-0.004783597470394279 + 0.005262467652486228im,-0.01283724437769671 + 0.01308623491396291im,-0.034015377605162496 + 0.028572925162380053im,-0.08660626968740466 + 0.053973986903251434im,0.6691598104203897 + 0.08623908572848926im,0.1452794264517145 + 0.11223212655111685im,0.020577959188579596 + 0.11036745559154632im,-0.05250009218264828 + 0.0661239165966846im,-0.0684520437673922 - 0.004536172566952253im,-0.02448767077258869 - 0.052310829226474974im,0.032741982094043186 - 0.037140996764535444im,0.039468169230482936 + 0.01666969859246884im,-0.005905706146079599 + 0.036777752221404426im,-0.03244856494262742 + 9.833178887472701e-5im,-0.0025659690983082816 - 0.028159041525335306im,0.02447798042990512 - 0.0026441340481144467im,0.0012010508904148605 + 0.021372174757058337im,-0.018540280327483467 - 0.0011309139190583135im,0.0038419093766019364 - 0.0156156499998411im,0.012301076216195472 + 0.006446272746877235im,-0.00844099975225217 + 0.008475314823997162im,-0.004276450979867765 - 0.009341997975022508im,0.008798991637435276 - 0.00013478458014303505im,-0.003289447005871243 + 0.00675761448215497im,-0.00359525205938016 - 0.0052950644285032im]);
     (Complex{Float64}[-0.006010560931105717 - 8.099206058228727e-5im,-0.013051842663096367 + 0.005072997552494464im,-0.020767358890538802 + 0.019682077819744254im,-0.020350238867813317 + 0.04582032165708542im,-0.000840462988510415 + 0.07261675027853165im,0.0332227865523085 + 0.0738741967602914im,0.0470596175620651 + 0.03318306101683247im,0.005088105121148251 - 0.017353169428847258im,-0.060140832621221406 - 0.01670211006014415im,-0.055685193586157665 + 0.02554150180991539im,0.023804475095123116 + 0.013091631772648592im,0.0453157515552314 - 0.05506075457887237im,-0.020338926278687768 - 0.03052938026745089im,-0.012328935826891372 + 0.06821949245308044im,0.04492219448720636 + 0.023343960299165443im,-0.03191179764206049 - 0.0689871518398665im,-0.05471667415446181 + 0.02280234814239691im,0.09181914286137305 + 0.03476355833284616im,-0.004636062285236399 - 0.08272409269029607im,-0.1341517019976866 + 0.09574737472886005im,0.018429462976150356 + 0.1949711893094354im,-0.08481800073867386 - 0.059695974371485376im,0.08448649365704856 - 0.009209773344884764im,-0.05217040384400483 + 0.061484496500109835im,-0.006608463758114336 - 0.07761527344078166im,0.05553541227538794 + 0.046969102534750236im,-0.06416627406970883 + 0.0029610063048838096im,0.03954094751201312 - 0.03518867518285888im,-0.011072200221512295 + 0.038811329542635824im,-0.002355330370127763 - 0.02929563602440653im,0.004161400259820308 + 0.02452031452178002im,-0.0074709247440437315 - 0.027954687340761748im,0.018987787629378226 + 0.03116034013192417im,-0.034589143849163034 - 0.025672160148372945im,0.04556074306767523 + 0.010724912328657797im,-0.046421786079989896 + 0.007571537903612689im,0.038012190635015576 - 0.021706878988059335im,-0.025573449862868452 + 0.02742230841587303im,0.014938022253327127 - 0.024982887262599555im,-0.009718974909464856 + 0.017681455346822823im,0.010542373181428552 - 0.00946559277680657im],Complex{Float64}[0.003400245486727625 - 0.007511015669592902im,-0.00014577102890233216 - 0.01880254929969861im,-0.016519694225866143 - 0.03381228588555419im,-0.051602445318170785 - 0.03906333615373821im,-0.0916754662562709 - 0.013110037809624893im,-0.09439428997876526 + 0.04462264490477062im,-0.02741888522036609 + 0.0804700768960561im,0.05735924933792379 + 0.025325077733909435im,0.04453304748017203 - 0.08003530300305259im,-0.05835900729439083 - 0.07499331179497443im,-0.05888898288726756 + 0.058113453537780906im,0.0779887919076034 + 0.07409759335885852im,0.06478071717257719 - 0.07632830237178781im,-0.10862722399706422 - 0.04671836917057687im,-0.02586258316536636 + 0.12043093492051966im,0.13954005316683837 - 0.0273164392331431im,-0.0838831737033017 - 0.1348238545962945im,-0.09902194325164608 + 0.1678178866560469im,0.2527365985045 + 0.011646944258297045im,-0.1758171289691821 - 0.40852753667861696im,0.0 + 0.0im,-0.1327707583536467 + 0.1665524988271359im,-0.03608446949387168 - 0.17523694940330375im,0.13043142758152051 + 0.08702717247010915im,-0.14090497939678473 + 0.018737477733484557im,0.0908647152090503 - 0.09458457046104024im,-0.01679594283094598 + 0.12045974026331244im,-0.047594203355206435 - 0.10199693258325562im,0.08472407872290133 + 0.06026939256557984im,-0.09529122017179062 - 0.016049263002305574im,0.08925099541629826 - 0.020236146476579484im,-0.0753159312460544 + 0.04772498177693122im,0.05699320160953973 - 0.0685714288063339im,-0.03494710178588556 + 0.08321095784105365im,0.010630204364646864 - 0.09027425863546125im,0.012568218449376629 + 0.08900847412571977im,-0.03074588779217126 - 0.08100679270024726im,0.04149616041771441 + 0.06991784952489172im,-0.044828289530455145 - 0.05982778583522361im,0.042675933856008486 + 0.05366676772796644im,-0.03765589528315129 - 0.052487346671997455im],Complex{Float64}[-0.0009186353611679662 - 0.01770123238482186im,-0.016959020530409118 - 0.03740406789764434im,-0.0599505640786381 - 0.05805622216894309im,-0.1344893692372033 - 0.05525210111959452im,-0.2093027749008774 - 0.0005548348565847305im,-0.2131251042086431 + 0.09077348355257847im,-0.10355718051202827 + 0.12407161468960597im,0.03349124509992406 + 0.008093498213504576im,0.04045219804815411 - 0.16644607779415307im,-0.05720602125457568 - 0.1563190338979058im,-0.020643433022335473 + 0.052284756866292185im,0.14536733702065063 + 0.1221366754550719im,0.07605698181778453 - 0.030986213874861324im,-0.17441057514137137 - 0.02649239519446253im,-0.07209046943730052 + 0.0922502093114227im,0.1651050033694482 - 0.08149244616313518im,-0.024692674600178544 - 0.12369120995514969im,-0.086003952508595 + 0.20809993506041094im,0.14411938865170457 + 0.019337232739630537im,-0.10404575751754877 - 0.265376728428818im,0.8313649528991015 + 0.2770652647011028im,-0.18399347965235652 + 0.29797382316815707im,-0.09804705507448168 - 0.20493430452018024im,0.14743962622809376 + 0.03984933681806125im,-0.09257061273868299 + 0.037065164855240675im,0.057633260793869684 - 0.048161929257768216im,-0.047393247774767396 + 0.06982353459682639im,0.008540015465826228 - 0.1059435599075758im,0.06511898173485135 + 0.10558035432931263im,-0.1235757095904637 - 0.04643660639079983im,0.12364532859213535 - 0.03638696209117433im,-0.07172191233460602 + 0.09031730512656982im,0.009803463673061952 - 0.09265513508105916im,0.024426457601701524 + 0.06032841727155126im,-0.022125330315602373 - 0.026919724024059406im,-0.00022570298498006497 + 0.015882610317076305im,0.019284989672185286 - 0.02972983257190519im,-0.02060144412329091 + 0.055709862696594364im,0.0034502925455790583 - 0.07784906497310044im,0.02333062134240389 + 0.08602932400641243im,-0.04850398311454398 - 0.0786803078946175im])]

for i in eachindex(E)
    ϕ = lhelmfs(complex(x,y),0.0,E[i];derivs=true)
    for j in 1:3
        @test norm(ϕ[j]-Φ[i][j],Inf) < 100eps()
    end
end

x = collect(-2:1.0:2)
y = collect(-2:1.0:2)
E = collect(-10:10.0:10)
z = x.+im*y'

𝕽 = Array{Matrix{Complex{Float64}}}(size(E))
#=
xBF = collect(-2:BigFloat(1.0):2)
yBF = collect(-2:BigFloat(1.0):2)
EBF = collect(-10:BigFloat(10.0):10)
zBF = xBF.+im*yBF'
[𝕽[i] = convert(Matrix{Complex{Float64}},lhelm_riemann(zBF,0zBF,EBF[i])) for i in eachindex(E)]
=#

𝕽[1] = Complex{Float64}[1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 1.559527688081715042215407854014417808812149076921151555306529585730657664096213e+03im 1.272006459007845559941221987327284931812837881102053926735813512404190170845331e+02 + 1.682675278677127413254962649769713242417117174802738568981084683205586894460463e+02im 9.036436716008059715046661857663038256082130349900884351522974053732106636088462e+01 - 6.908934844075555700309081490240319656892800291549025108018962776134873442529942e-77im 9.176017961670177477264995768865600275565644353378550340037085254575791729298424e+01 - 1.210135728222690330301999435848746703408752580450473378671611367276772230573123e+02im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 6.694220661350562768705955293791082897961252328946944830822527565529059646157028e+02im
                  -1.469797198354392957674307303368354243224969726253943319448322854626834039706531e+02 + 1.973062931139190610232409737824472324299959635005257759264430472835778719608694e+02im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 1.779549957127476842553971431330336947114533379129140713304465139221826076496712e+01im 5.571230536887944565938012219540339054165948043656580809163982321476259622717075 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 1.44387270429883337378563234716649680554593134300381556054938062365753083788965e+01im -7.54902295815984987507699797274028219584300038313104311343694574292079612857124e+01 - 1.019869727754646650010266396365370959445733384417472415124926099056106150476154e+02im
                  -1.180278957488324212994966225306292525543123583615742679698057861627287320792801e+02 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im -3.941448339192336808620796267390290024317406908924433550372292127439443513482247 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im -3.217748338718791625938231255779184786419545953889291497853425094213522810467873 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im -6.514136573623292627177857640703331299885272625312977908570241225088221548994035e+01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im
                  -1.469797198354392957674307303368354243224969726253943319448322854626834039706531e+02 - 1.973062931139190610232409737824472324299959635005257759264430472835778719608694e+02im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 1.779549957127476842553971431330336947114533379129140713304465139221826076496712e+01im 5.571230536887944565938012219540339054165948043656580809163982321476259622717075 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 1.44387270429883337378563234716649680554593134300381556054938062365753083788965e+01im -7.54902295815984987507699797274028219584300038313104311343694574292079612857124e+01 + 1.019869727754646650010266396365370959445733384417472415124926099056106150476154e+02im
                  1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 1.559527688081715042215407854014417808812149076921151555306529585730657664096213e+03im 1.272006459007845559941221987327284931812837881102053926735813512404190170845331e+02 - 1.682675278677127413254962649769713242417117174802738568981084683205586894460463e+02im 9.036436716008059715046661857663038256082130349900884351522974053732106636088462e+01 + 6.908934844075555700309081490240319656892800291549025108018962776134873442529942e-77im 9.176017961670177477264995768865600275565644353378550340037085254575791729298424e+01 + 1.210135728222690330301999435848746703408752580450473378671611367276772230573123e+02im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 6.694220661350562768705955293791082897961252328946944830822527565529059646157028e+02im]

𝕽[2] = Complex{Float64}[1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 3.073654314444833662867964848381522401755999147405737616093502014377717524232445im 1.418854048232790568746896929046516198920607600727090496402599277712711679157509 + 5.584720643103874249958625720620215985608101343027873285367990369502822388766784e-01im 9.86115933376187458582138300031294561693601179244344917413538404541762709179762e-01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 6.658034104345442152153485269277412323895019441304504162145078911208223274348069e-01 + 4.455954527539410463795352974296783568139974078260661117139894785055702300869126e-01im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 1.261833533873199247338473214568452448691622630393699188159856807676191643984414im
                  2.429202859589911244935746817936526572228570754385794002264369738432396854452519e-03 + 1.330094396187213451673419004242751297903695238994152274663647507015423470860724im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 2.642185870934118886976721327803798567540028959270961614088944223360039094659795e-01im 9.997829872884857964621492312570073605746725318551060411234728989496103839209607e-01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 2.364325202385329331629421718228186720109686567927908446539003997915883387187256e-01im 1.557530911624388325050314290856466126631569682759095020603294323450132760986883 + 7.433745488325177667337523878086215021754262436787933608043924312668436813158496e-01im
                  -2.618625282633160276679611137420980507166095431137950475419951349739603957834599e-01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 8.712629502825992863524248855440375903487349752444898365486026161935750230979242e-01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.12135789696223673945980223744967686852199385851859231455050502993940831780726 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.786850316788085522466271467711976505960963653738283316835888165034510428350373 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im
                  2.429202859589911244935746817936526572228570754385794002264369738432396854452519e-03 - 1.330094396187213451673419004242751297903695238994152274663647507015423470860724im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 2.642185870934118886976721327803798567540028959270961614088944223360039094659795e-01im 9.997829872884857964621492312570073605746725318551060411234728989496103839209607e-01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 2.364325202385329331629421718228186720109686567927908446539003997915883387187256e-01im 1.557530911624388325050314290856466126631569682759095020603294323450132760986883 - 7.433745488325177667337523878086215021754262436787933608043924312668436813158496e-01im
                  1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 3.073654314444833662867964848381522401755999147405737616093502014377717524232445im 1.418854048232790568746896929046516198920607600727090496402599277712711679157509 - 5.584720643103874249958625720620215985608101343027873285367990369502822388766784e-01im 9.86115933376187458582138300031294561693601179244344917413538404541762709179762e-01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 6.658034104345442152153485269277412323895019441304504162145078911208223274348069e-01 - 4.455954527539410463795352974296783568139974078260661117139894785055702300869126e-01im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 1.261833533873199247338473214568452448691622630393699188159856807676191643984414im]

𝕽[3] = Complex{Float64}[9.999999999999999999999999999999999999999999999999999999999999999999999999980655e-01 - 9.517238569709800023874567389955156162674768308768388424203108533002058545384214e-01im 5.790284158160320220961853532056169599327554024881639356372427239870912934499176e-01 - 5.612954455786239705384195290591773867563261300157814191503430346838782754008468e-01im 2.288009162095741154905408387174082632213159811870103137593180613801942273846618e-01 - 6.908934844075555700309081490240319656892800291549025108018962776134873442529942e-77im 5.758238875031047816496313742425357945880684197453251688931294557790261197062539e-01 + 5.655681499958602911338248343432856072159087736728997748091607256279651737247645e-01im 1.000000000000000000000000000000000000000000000000000000000000000000000000002211 + 1.17264010864624459379346662801933260330527746869623999206548531289553809041883im
                  1.428252665025167288262470244662553434974457923630899075608144834861194381696167 - 5.710035533668897176832936595500712466326105648411987674775264464815925089277165e-01im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 1.350772297697414442907732644136038422100599886949192391697172847498034382760828im -3.101557626802583102305642592816542637714672944999185491761153865128874251783409e-01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 1.300933735900403336184611180589715479538621945086370831744859018006213526172839im 1.433455011883104556255954047231397588180361364352305890029660629253820826059144 + 5.77940015844139408341272062975196784240481819136407853372880839005094434745663e-01im
                  1.849707795343286952161135478581626753609490258919800706080985086980418367503952 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 2.286763645275007880682499244638978373195219760814932051170388229980619041872889 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 2.330517058931000757981322437829390876495583273960066083365299569340764070239034 - 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.721795016851737660005610577941552186204948415952999743212144627194238498555157 - 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im
                  1.428252665025167288262470244662553434974457923630899075608144834861194381696167 + 5.710035533668897176832936595500712466326105648411987674775264464815925089277165e-01im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + 1.350772297697414442907732644136038422100599886949192391697172847498034382760828im -3.101557626802583102305642592816542637714672944999185491761153865128874251783409e-01 + 0.000000000000000000000000000000000000000000000000000000000000000000000000000000im 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 1.300933735900403336184611180589715479538621945086370831744859018006213526172839im 1.433455011883104556255954047231397588180361364352305890029660629253820826059144 - 5.77940015844139408341272062975196784240481819136407853372880839005094434745663e-01im
                  9.999999999999999999999999999999999999999999999999999999999999999999999999980655e-01 + 9.517238569709800023874567389955156162674768308768388424203108533002058545384214e-01im 5.790284158160320220961853532056169599327554024881639356372427239870912934499176e-01 + 5.612954455786239705384195290591773867563261300157814191503430346838782754008468e-01im 2.288009162095741154905408387174082632213159811870103137593180613801942273846618e-01 + 6.908934844075555700309081490240319656892800291549025108018962776134873442529942e-77im 5.758238875031047816496313742425357945880684197453251688931294557790261197062539e-01 - 5.655681499958602911338248343432856072159087736728997748091607256279651737247645e-01im 1.000000000000000000000000000000000000000000000000000000000000000000000000002211 - 1.17264010864624459379346662801933260330527746869623999206548531289553809041883im]

for i in eachindex(E)
    ℜ = lhelm_riemann(z,0z,E[i])
    @test norm(ℜ-𝕽[i],Inf) < 2500eps()
end

ext: jl


text:
using JetPackWaveFD, Jets, Test

tmax = 9.0
dtdom,dtrng = 0.004,0.0005
n1dom,n1rng,n2 = round(Int,tmax/dtdom)+1,round(Int,tmax/dtrng)+1,10

@testset "JopSincRegular linearity test, T=$(T)" for T in (Float32,Float64)
    A = JopSincRegular(JetSpace(T,n1dom,n2), JetSpace(T,n1rng,n2), dtdom, dtrng)
    lhs, rhs = linearity_test(A)
    @test lhs ≈ rhs
    lhs, rhs = linearity_test(A')
    @test lhs ≈ rhs
end

@testset "JotOpFilter dot product test, T=$(T)" for T in (Float32,Float64)
    A = JopSincRegular(JetSpace(T,n1dom,n2), JetSpace(T,n1rng,n2), dtdom, dtrng)
    lhs,rhs = dot_product_test(A, -1 .+ 2 .* rand(domain(A)), -1 .+ 2 .* rand(range(A)))
    @test lhs ≈ rhs
end

max_stars_repo_name: ChevronETC/JetPackWaveFD

max_issues_repo_name: ChevronETC/JetPackWaveFD

max_forks_repo_name: ChevronETC/JetPackWaveFD


text:
# Importing packages

struct SudokuState
    puzzle::Array
    energy::Number
    T::Number
end

struct Indices
    blocks::Array
    columns::Array
    rows::Array
    free_cells_pr_block::Dict
    fixed_numbers_pr_block::Dict
end

function  get_indices(puzzle)
    blocks = []
    columns = []
    rows = []
    free_cells_pr_block = Dict()
    fixed_numbers_pr_block = Dict()
    counter = 0
    for i in 1:3:7
        for j in 1:3:7
            counter += 1
            push!(rows, (counter, 1:9))
            push!(columns, (1:9, counter))
            push!(blocks, (i:i+2, j:j+2))

            free_block = []
            fixed_numbers = []
            for k in i:i+2
                for l in j:j+2
                    if puzzle[k, l]==0
                        push!(free_block, (k, l))
                    else
                        push!(fixed_numbers, puzzle[k, l])
                    end
                end
            end
            free_cells_pr_block[(i:i+2, j:j+2)] = free_block
            fixed_numbers_pr_block[(i:i+2, j:j+2)] = fixed_numbers
        end
    end

    return Indices(blocks, columns, rows, free_cells_pr_block, fixed_numbers_pr_block)
end

function initialize_board(puzzle, indices)
    puzzle = copy(puzzle)
    for (b_i, b_j) in indices.blocks

        possible_values = [v for v in 1:9 if v ∉ indices.fixed_numbers_pr_block[(b_i,b_j)]]

        for (c_i, c_j) in indices.free_cells_pr_block[(b_i, b_j)]
            i = rand(1:length(possible_values))
            puzzle[c_i, c_j] = possible_values[i]
            deleteat!(possible_values, i)
        end
    end

    return get_state(puzzle, indices)
end

function get_energy(puzzle, indices)
    energy = sum([sum(unique(puzzle[i, j])) for (i, j) in indices.columns])
    energy += sum([sum(unique(puzzle[i, j])) for (i, j) in indices.rows])

    return abs(2*405 - energy)

end

function get_state(puzzle, indices, T=-1.0)
    energy = get_energy(puzzle, indices)

    return SudokuState(puzzle, energy, T)

end

function random_block_swap(puzzle, indices)
    puzzle = copy(puzzle)
    (b_i, b_j) = indices.blocks[rand(1:length(indices.blocks))]
    (c_i, c_j) = rand(1:length(indices.free_cells_pr_block[(b_i, b_j)]), 2)
    (s1_i, s1_j) = indices.free_cells_pr_block[(b_i, b_j)][c_i]
    (s2_i, s2_j) = indices.free_cells_pr_block[(b_i, b_j)][c_j]
    puzzle[s1_i, s1_j], puzzle[s2_i, s2_j] = puzzle[s2_i, s2_j], puzzle[s1_i, s1_j]

    return puzzle
end

function run_mc(state, indices, temp::Real, nsteps::Int)
    count = 0
    missed_moves = 0
    for i in 1:nsteps

        puzzle = random_block_swap(state.puzzle, indices)
        new_state = get_state(puzzle, indices, temp)

        energy_diff = new_state.energy - state.energy

        if MathConstants.e^(-energy_diff/temp) > rand() || energy_diff <= 0
            state = new_state
        end
        if state.energy==0
            break
        end

    end
    return state
end


text:
# browse.jl
## https://developer.spotify.com/documentation/web-api/reference/browse/

## https://developer.spotify.com/documentation/web-api/reference/browse/get-category/
@doc """"
Get a single category used to tag items in Spotify (on, for example, the Spotify player’s “Browse” tab).\n

country: (Optional) A country: ISO 3166-1 alpha-2 country code. Provide this parameter to ensure that the category exists for a particular country.\n
locale: (Optional) The desired language, consisting of an ISO 639-1 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. For example: es_MX, meaning "Spanish (Mexico)". Provide this parameter if you want the category strings returned in a particular language. Note that, if locale is not supplied, or if the specified language is not available, the category strings returned will be in the Spotify default language (American English).\n
""" ->
function category_get(category_id, country="US", locale="en")
    return spotify_request("browse/categories/$category_id?country=$country&locale=$locale")
end

## https://developer.spotify.com/documentation/web-api/reference/browse/get-categorys-playlists/
@doc """
Get a list of Spotify playlists tagged with a particular category.\n

country: (Optional) A country: an ISO 3166-1 alpha-2 country code.\n
limit: (Optional) The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.\n
offset: (Optional) The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items.\n
""" ->
function category_get_playlist(category_id, country="US", limit = 20, offset = 0)
    return spotify_request("browse/categories/$category_id/playlists?country=$country&limit=$limit&offset=$offset")
end

## https://developer.spotify.com/documentation/web-api/reference/browse/get-list-categories/
@doc """
Get a list of categories used to tag items in Spotify (on, for example, the Spotify player’s “Browse” tab).\n

country: (Optional) A country: an ISO 3166-1 alpha-2 country code.\n
limit: (Optional) The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.\n
offset: (Optional) The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items.\n
""" ->
function category_get_several(country="US", locale="en", limit=20, offset=0)
    return spotify_request("browse/categories?country=$country&locale=$locale&limit=$limit&offset=$offset")
end

## https://developer.spotify.com/documentation/web-api/reference/browse/get-list-new-releases/
@doc """
Get a list of new album releases featured in Spotify (shown, for example, on a Spotify player’s “Browse” tab).\n

country: (Optional) A country: an ISO 3166-1 alpha-2 country code. Provide this parameter if you want the list of returned items to be relevant to a particular country. If omitted, the returned items will be relevant to all countries.\n
locale: (Optional) The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.\n
offset: (Optional) Optional. The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items.\n
""" ->
function category_get_new_releases(country="US", locale="en", limit=20, offset=0)
    return spotify_request("browse/new-releases?country=$country&locale=$locale&limit=$limit&offset=$offset")
end

## https://developer.spotify.com/documentation/web-api/reference/browse/get-list-featured-playlists/
@doc """
Get a list of Spotify featured playlists (shown, for example, on a Spotify player’s ‘Browse’ tab).\n

country: (Optional) A country: an ISO 3166-1 alpha-2 country code. Provide this parameter if you want the list of returned items to be relevant to a particular country. If omitted, the returned items will be relevant to all countries.\n
locale: (Optional) The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.\n
offset: (Optional) The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items.\n
timestamp: (Optional) A timestamp in ISO 8601 format: yyyy-MM-ddTHH:mm:ss.
Use this parameter to specify the user’s local time to get results tailored for that specific date and time in the day.
If not provided, the response defaults to the current UTC time.
Example: “2014-10-23T09:00:00” for a user whose local time is 9AM.
If there were no featured playlists (or there is no data) at the specified time, the response will revert to the current UTC time.
""" ->
function category_get_featured_playlist(country="US",locale="en", limit=50, offset=0, timestamp=string(now())[1:19])
    return spotify_request("browse/featured-playlists?country=$country&locale=$locale&limit=$limit&offset=$offset&timestamp=$timestamp")
end

## https://developer.spotify.com/documentation/web-api/reference/browse/get-recommendations/
@doc """
Get Recommendations Based on Seeds

seeds: (Required) A dictionary containing keys(seed_genres, seed_artists, seed_tracks) and values for each key being seeds delimeted by a comma up to 5 seeds for each category\n
Example\n
Dict("seed_artists" => "s33dart1st,s33edart!st2", "seed_genres" => "g3nre1,genr32", "seed_tracks" => "trackid1,trackid2")\n

track_attributes: (Optional) a dictionary containing key values for different tunable track track_attributes\n
See https://developer.spotify.com/documentation/web-api/reference/browse/get-recommendations/
""" ->
function recommendations_get(
    seeds,
    track_attributes,
    limit = 50,
    market = "US"
)
    track_attributes = recommendations_dict_parser(track_attributes)
    seeds = recommendations_dict_parser(seeds)
    return spotify_request("recommendations?$seeds&$track_attributes&limit=$limit&market=$market")

end

## Recommendations Helper Func
function recommendations_dict_parser(track_attributes::Dict)
    query = ""
    for (key,value) in track_attributes
        query = query * key * "=" * value * "&"
    end
    return query
end

"""
For each tunable track attribute, a hard floor on the selected track attribute’s value can be provided. See tunable track attributes below for the list of available options. For example, min_tempo=140 would restrict results to only those tracks with a tempo of greater than 140 beats per minute.
"""
min_acousticness, min_danceability, min_duration_ms, min_energy, min_min_instrumentalness , min_key,
min_liveness, min_loudness, min_mode, min_popularity, min_speechiness, min_tempo, min_time_signature, min_valence

"""
For each tunable track attribute, a hard ceiling on the selected track attribute’s value can be provided. See tunable track attributes below for the list of available options. For example, max_instrumentalness=0.35 would filter out most tracks that are likely to be instrumental.
"""
max_acousticness, max_danceability, max_duration_ms, max_energy, max_instrumentalness, max_key, max_liveness, max_loudness, max_mode,
max_popularity, max_speechiness, max_tempo, max_time_signature, max_valence

"""
For each of the tunable track attributes (below) a target value may be provided. Tracks with the attribute values nearest to the target values will be preferred. For example, you might request target_energy=0.6 and target_danceability=0.8. All target values will be weighed equally in ranking results.
"""
target_acousticness, target_danceability, target_duration_ms, target_energy, target_instrumentalness, target_key, target_liveness, target_loudness, target_mode, target_popularity, target_speechiness, target_tempo, target_time_signature, target_valence

max_acousticness(x::Float64) = x
max_danceability(x::Float64) = x
max_duration_ms(x::Integer) = x
max_energy(x::Float64) = x
max_instrumentalness(x::Float64) = x
max_key(x::Integer) = x
max_liveness(x::Float64) = x
max_loudness(x::Float64) = x
max_mode(x::Float64) = x
max_popularity(x::Integer) = x
max_speechiness(x::Float64) = x
max_tempo(x::Float64) = x
max_time_signature(x::Integer) = x
max_valence(x::Float64) = x
min_acousticness(x::Float64) = x
min_danceability(x::Float64) = x
min_duration_ms(x::Integer) = x
min_energy(x::Float64) = x
min_instrumentalness(x::Float64) = x
min_key(x::Integer) = x
min_liveness(x::Float64) = x
min_loudness(x::Float64) = x
min_mode(x::Float64) = x
min_popularity(x::Integer) = x
min_speechiness(x::Float64) = x
min_tempo(x::Float64) = x
min_time_signature(x::Integer) = x
min_valence(x::Float64) = x
target_acousticness(x::Float64) = x
target_danceability(x::Float64) = x
target_duration_ms(x::Integer) = x
target_energy(x::Float64) = x
target_instrumentalness(x::Float64) = x
target_key(x::Integer) = x
target_liveness(x::Float64) = x
target_loudness(x::Float64) = x
target_mode(x::Integer) = x
target_popularity(x::Integer) = x
target_speechiness(x::Float64) = x
target_tempo(x::Float64) = x
target_time_signature(x::Integer) = x
target_valence(x::Float64) = x


text:
function foo()
    file = open("data/2.txt", "r")
    threes = 0
    twos = 0
    for line in readlines(file)
        x = Dict{Char, Int}()
        for char in line
            if !(char in keys(x))
                x[char] = 0
            end
            x[char] += 1
        end
        threes += 3 in values(x)
        twos += 2 in values(x)
    end
    return twos * threes
end

println(foo())


text:
"""
Tableau for the 1-stage SRKw1 method due to Wang, Hong & Xu
  Method cited in
  Wang, Hong, Xu, "Construction of Symplectic Runge-Kutta Methods for Stochastic Hamiltonian Systems",
  Commun. Comput. Phys. 21(1), 2017
  According to the paper, the method has weak order 1.0.
"""
function getTableauSRKw1(x::Number=0.0)

    A0 = 0.5*ones(typeof(x),1,1)

    A1 = (1. - x)*ones(typeof(x),1,1)

    B0 = x*ones(typeof(x),1,1)

    B1 = 0.5*ones(typeof(x),1,1)

    B3 = 0.5*ones(typeof(x),1,1)

    α  =  [1.0]
    β1 =  [1.0]

    c0 =  [0.5]
    c1 =  [1. - x]

    TableauWIRK(:SRKw1, A0, A1, B0, B1, B3, α, β1, c0, c1)
end

"""
Tableau for the 4-stage SRKw2 method due to Wang, Hong & Xu
  Method cited in
  Wang, Hong, Xu, "Construction of Symplectic Runge-Kutta Methods for Stochastic Hamiltonian Systems",
  Commun. Comput. Phys. 21(1), 2017
  According to the paper, the method has weak order 2.0 when applied to systems
  driven by one-dimensional noise.
"""
function getTableauSRKw2(x1::Number=0.0, x2::Number=0.0, x3::Number=0.0)

    A0 = [[1. / 8.   0.0        0.0       0.0]
          [1. / 4.   1. / 8.    0.0       0.0]
          [1. / 4.   1. / 4.    1. / 8.   0.0]
          [1. / 4.   1. / 4.    1. / 4.   1. / 8.]]

    A1 = [[-1. / 6. + sqrt(3)/6.   1. / 3. - sqrt(3)/6.   0.0   1. / 3.]
          [ 1. / 2.                0.0                    0.0   0.0]
          [0.0                     0.0                    0.0   0.0]
          [0.0                     0.0                    0.0   0.0]]

    B0 = [[ 5. / 6. - sqrt(3)/3.     -1. / 2.    0.0   0.0]
          [-1. / 6. + sqrt(3)/3.      1. / 2.    0.0   0.0]
          [ 1. / 2.                   1. / 2.    0.0   0.0]
          [-1. / 6.                   1. / 2.    0.0   0.0]]

    B1 = [[1. / 4.                1. / 4. - sqrt(3)/6.   0.0   0.0]
          [1. / 4. + sqrt(3)/6.   1. / 4.                0.0   0.0]
          [x1                     x2                     0.0   x3]
          [0.0                    -1. / 2.               0.0   0.0]]

    B3 = zeros(typeof(x1),4,4)

    α  =  [0.25, 0.25, 0.25, 0.25]
    β1 =  [0.5,  0.5,  0.0,  0.0]

    c0 =  [1. / 8., 3. / 8., 5. / 8., 7. / 8.]
    c1 =  [0.5, 0.5, 0.0, 0.0]

    TableauWIRK(:SRKw2, A0, A1, B0, B1, B3, α, β1, c0, c1)
end


text:
using Roots

function detach_indexer(repo::Repository, id::AbstractString)::Tuple{Indexer,Repository}
    # Get requested indexer
    i = findfirst(x -> x.id == id, repo.indexers)
    if isnothing(i)
        throw(UnknownIndexerError())
    end
    indexer = repo.indexers[i]

    # Remove indexer from repository
    indexers = filter(x -> x.id != id, repo.indexers)
    frepo = Repository(indexers, repo.subgraphs)
    return indexer, frepo
end

function stakes(r::Repository)
    # Loop over subgraphs, getting their names
    subgraphs = ipfshash.(r.subgraphs)

    # Match name to indexer allocations
    ω = reduce(vcat, allocation.(r.indexers))
    Ω = []
    for subgraph in subgraphs
        subgraph_allocations = filter(x -> x.ipfshash == subgraph, ω)
        subgraph_amounts = allocated_stake.(subgraph_allocations)

        # If no match, then set to 0
        if isempty(subgraph_amounts)
            subgraph_amounts = [0.0]
        end
        stake_on_subgraph = sum(subgraph_amounts)
        append!(Ω, stake_on_subgraph)
    end
    return Ω
end

function solve_dual(Ω, ψ, σ)
    lower_bound = eps(Float64)
    upper_bound = (sum(.√(ψ .* Ω)))^2 / σ
    sol = find_zero(
        x -> sum(max.(0.0, .√(ψ .* Ω / x) .- Ω)) - σ,
        (lower_bound, upper_bound),
        Roots.Brent(),
    )
    return sol
end

solve_primal(Ω, ψ, v) = max.(0.0, .√(ψ .* Ω / v) - Ω)

function optimize(indexer::Indexer, repo::Repository)
    ψ = signal.(repo.subgraphs)
    Ω = stakes(repo)
    σ = indexer.stake

    # Solve the dual and use that value to solve the primal
    v = solve_dual(Ω, ψ, σ)
    ω = solve_primal(Ω, ψ, v)

    return ω
end


text:
module Crypto
using Compat
##############################################################################
##
## TODO
##
##############################################################################

# - Investigate why shared library libcryptojl isn't getting picked up without
#   @timholy's hack.

##############################################################################
##
## Exports
##
##############################################################################

export init, cleanup, digest, random, ec_pub_key, ec_sign, ec_verify,
       hex2oct, oct2hex, int2oct, oct2int

export COMPRESSED,
       UNCOMPRESSED,
       COMPRESSED_LENGTH,
       UNCOMPRESSED_LENGTH,

       # TODO: Assume maximum signature size is 144 bytes (way overkill)
       SIGNATURE_SIZE,

       NID_secp256k1

##############################################################################
##
## Load files
##
##############################################################################

include("util.jl")
include("digest.jl")
include("ecdsa.jl")
include("random.jl")

##############################################################################
##
## Get libcryptojl path (borrowed from @timholy's Cpp package)
##
##############################################################################

# Get possible library extensions
fnames = ["libcryptojl.so", "libcryptojl.dylib", "libcryptojl.dll"]

# Search for libraries
path = joinpath(Pkg.dir(), "Crypto", "deps")
global libname

found = false

for fname in fnames
    libname = Base.find_in_path(joinpath(path, fname))
    if isfile(libname)
        break
    end
end

if !isfile(libname)
    error("Library cannot be found; it may not have been built correctly.\n Try include(\"build.jl\") from within the deps directory.")
end

const libcryptojl = libname

end # module Crypto


max_stars_repo_path: test/1 Algebraic functions/1.1 Binomial products/1.1.1 Linear/1.1.1.5 P(x) (a+b x)^m (c+d x)^n.jl


text:
using JuliaFEM
using JuliaFEM.Preprocess
using JuliaFEM.Postprocess
using JuliaFEM.Abaqus: create_surface_elements

Logging.configure(level=Logging.DEBUG)

function create_body(mesh, name, E, nu, rho)
    body = Problem(mesh, Elasticity, name, 3)
    update!(body, "youngs modulus", E)
    update!(body, "poissons ratio", nu)
    update!(body, "density", rho)
    return body
end

""" Create boundary condition from surface set. """
function create_bc_from_surface_set(mesh, name, u1, u2, u3)
    bc = Problem(Dirichlet, string(name), 3, "displacement")
    bc.elements = create_surface_elements(mesh, name)
    update!(bc, "displacement 1", u1)
    update!(bc, "displacement 2", u2)
    update!(bc, "displacement 3", u3)
    return bc
end

""" Create boundary condition from node set. """
function create_bc_from_node_set(mesh, name, u1, u2, u3)
    bc = Problem(Dirichlet, string(name), 3, "displacement")
    bc.elements = [Element(Poi1, [nid]) for nid in mesh.node_sets[name]]
    update!(bc, "geometry", mesh.nodes)
    update!(bc, "displacement 1", u1)
    update!(bc, "displacement 2", u2)
    update!(bc, "displacement 3", u3)
    return bc
end

function create_bc(mesh, name, u1=0.0, u2=0.0, u3=0.0)
    name = Symbol(name)
    if haskey(mesh.surface_sets, name)
        return create_bc_from_surface_set(mesh, name, u1, u2, u3)
    elseif haskey(mesh.node_sets, name)
        return create_bc_from_node_set(mesh, name, u1, u2, u3)
    else
        error("Mesh does not contain node or surface set $name")
    end
end

function create_interface(mesh, slave_surface::String, master_surface::String;
dual_basis=true)
    interface = Problem(Mortar, "interface between $slave_surface and $master_surface", 3, "displacement")
    interface.properties.dual_basis = dual_basis
    slave_elements = create_surface_elements(mesh, Symbol(slave_surface))
    master_elements = create_surface_elements(mesh, Symbol(master_surface))
    nslaves = length(slave_elements)
    nmasters = length(master_elements)
    info("$nslaves slaves, $nmasters masters")
    update!(slave_elements, "master elements", master_elements)
    interface.elements = [slave_elements; master_elements]
    return interface
end

function create_interface(mesh, slave::Problem, master::Problem)
    slave_surface = slave.name * "_TO_" * master.name
    master_surface = master.name * "_TO_" * slave.name
    return create_interface(mesh, slave_surface, master_surface)
end

""" Convert Mesh object from quadratic to linear. """
function to_linear!(mesh)
    mapping = Dict(:Tet10 => :Tet4, :Tri6 => :Tri3)
    nnodes = Dict(:Tet4 => 4, :Tri3 => 3)
    for elid in keys(mesh.elements)
        eltype = mesh.element_types[elid]
        if haskey(mapping, eltype)
            mesh.element_types[elid] = mapping[eltype]
            nnodes_new = nnodes[mapping[eltype]]
            mesh.elements[elid] = mesh.elements[elid][1:nnodes_new]
        end
    end
end

# start of simulation
mesh = abaqus_read_mesh("splitted_wedge.inp")
#to_linear!(mesh)
info("element sets = ", collect(keys(mesh.element_sets)))
info("surface sets = ", collect(keys(mesh.surface_sets)))

# parts
lower = create_body(mesh, "LOWER", 210.0e3, 0.3, 7.85e-9)
upper = create_body(mesh, "UPPER", 210.0e3, 0.3, 7.85e-9)

# boundary conditions
bc1 = create_bc(mesh, "LOWER_FIXED")
bc2 = create_bc(mesh, "UPPER_FIXED")

# load
load = Problem(Elasticity, "pressure load", 3)
load.elements = create_surface_elements(mesh, :UPPER_FIXED)
update!(load, "surface pressure", -100.0)

contact = create_interface(mesh, "UPPER_TO_LOWER", "LOWER_TO_UPPER")
contact.properties.linear_surface_elements = true
contact.properties.split_quadratic_slave_elements = false

# solution
solver = Solver(Linear, lower, upper, bc1, load, contact)
solver.xdmf = Xdmf("tie_contact"; overwrite=true)
solver()


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

module TestLQ

using Test, LinearAlgebra, Random
using LinearAlgebra: BlasComplex, BlasFloat, BlasReal, rmul!, lmul!

m = 10

Random.seed!(1234321)

asquare = randn(ComplexF64, m, m) / 2
awide = randn(ComplexF64, m, m+3) / 2
bcomplex = randn(ComplexF64, m, 2) / 2

# helper functions to unambiguously recover explicit forms of an LQPackedQ
squareQ(Q::LinearAlgebra.LQPackedQ) = (n = size(Q.factors, 2); lmul!(Q, Matrix{eltype(Q)}(I, n, n)))
rectangularQ(Q::LinearAlgebra.LQPackedQ) = convert(Array, Q)

@testset for eltya in (Float32, Float64, ComplexF32, ComplexF64), n in (m, size(awide, 2))
    adata = m == n ? asquare : awide
    a = convert(Matrix{eltya}, eltya <: Complex ? adata : real(adata))
    ε = εa = eps(abs(float(one(eltya))))
    n1 = n ÷ 2

    α = rand(eltya)
    aα = fill(α,1,1)
    @test lq(α).L*lq(α).Q ≈ lq(aα).L*lq(aα).Q
    @test abs(lq(α).Q[1,1]) ≈ one(eltya)

    @testset for eltyb in (Float32, Float64, ComplexF32, ComplexF64, Int)
        b = eltyb == Int ? rand(1:5, m, 2) : convert(Matrix{eltyb}, eltyb <: Complex ? bcomplex : real(bcomplex))
        εb = eps(abs(float(one(eltyb))))
        ε = max(εa,εb)

        tab = promote_type(eltya,eltyb)

        @testset for isview in (false,true)
            let a = isview ? view(a, 1:m - 1, 1:n - 1) : a, b = isview ? view(b, 1:m - 1) : b, m = m - isview, n = n - isview
                lqa   = lq(a)
                x = lqa\b
                l,q   = lqa.L, lqa.Q
                qra   = qr(a, Val(true))
                @testset "Basic ops" begin
                    @test size(lqa,1) == size(a,1)
                    @test size(lqa,3) == 1
                    @test size(lqa.Q,3) == 1
                    @test Base.propertynames(lqa) == (:L, :Q)
                    ref_obs = (l, q)
                    for (ii, lq_obj) in enumerate(lqa)
                        @test ref_obs[ii] == lq_obj
                    end
                    @test_throws ErrorException lqa.Z
                    @test Array(copy(adjoint(lqa))) ≈ a'
                    @test q*squareQ(q)' ≈ Matrix(I, n, n)
                    @test l*q ≈ a
                    @test Array(lqa) ≈ a
                    @test Array(copy(lqa)) ≈ a
                    lstring = sprint(show, l, context = :compact=>true)
                    qstring = sprint(show, q, context = :compact=>true)
                    @test sprint(show,MIME"text/plain"(),lqa) == "$(typeof(lqa)) with factors L and Q:\n$lstring\n$qstring"
                    @test LinearAlgebra.Factorization{eltya}(lqa) === lqa
                    @test Matrix{eltya}(q) isa Matrix{eltya}
                end
                @testset "Binary ops" begin
                    @test a*x ≈ b rtol=3000ε
                    @test x ≈ qra \ b rtol=3000ε
                    @test lqa*x ≈ a*x rtol=3000ε
                    @test (sq = size(q.factors, 2); *(Matrix{eltyb}(I, sq, sq), adjoint(q))*squareQ(q)) ≈ Matrix(I, n, n) rtol=5000ε
                    if eltya != Int
                        @test Matrix{eltyb}(I, n, n)*q ≈ convert(AbstractMatrix{tab},q)
                    end
                    @test q*x ≈ squareQ(q)*x rtol=100ε
                    @test transpose(q)*x ≈ transpose(squareQ(q))*x rtol=100ε
                    @test q'*x ≈ squareQ(q)'*x rtol=100ε
                    @test a*q ≈ a*squareQ(q) rtol=100ε
                    @test a*transpose(q) ≈ a*transpose(squareQ(q)) rtol=100ε
                    @test a*q' ≈ a*squareQ(q)' rtol=100ε
                    @test q*a'≈ squareQ(q)*a' rtol=100ε
                    @test q'*a' ≈ squareQ(q)'*a' rtol=100ε
                    @test_throws DimensionMismatch q*x[1:n1 + 1]
                    @test_throws DimensionMismatch adjoint(q) * Matrix{eltya}(undef,m+2,m+2)
                    @test_throws DimensionMismatch Matrix{eltyb}(undef,m+2,m+2)*q
                    if isa(a, DenseArray) && isa(b, DenseArray)
                        # use this to test 2nd branch in mult code
                        pad_a = vcat(I, a)
                        pad_x = hcat(I, x)
                        @test pad_a*q ≈ pad_a*squareQ(q) rtol=100ε
                        @test transpose(q)*pad_x ≈ transpose(squareQ(q))*pad_x rtol=100ε
                        @test q'*pad_x ≈ squareQ(q)'*pad_x rtol=100ε
                    end
                end
            end
        end

        @testset "Matmul with LQ factorizations" begin
            lqa = lq(a[:,1:n1])
            l,q = lqa.L, lqa.Q
            @test rectangularQ(q)*rectangularQ(q)' ≈ Matrix(I, n1, n1)
            @test squareQ(q)'*squareQ(q) ≈ Matrix(I, n1, n1)
            @test_throws DimensionMismatch rmul!(Matrix{eltya}(I, n+1, n+1),q)
            @test lmul!(adjoint(q), rectangularQ(q)) ≈ Matrix(I, n1, n1)
            @test_throws DimensionMismatch rmul!(Matrix{eltya}(I, n+1, n+1), adjoint(q))
            @test_throws BoundsError size(q,-1)
        end
    end
end

@testset "getindex on LQPackedQ (#23733)" begin
    local m, n
    function getqs(F::LinearAlgebra.LQ)
        implicitQ = F.Q
        sq = size(implicitQ.factors, 2)
        explicitQ = lmul!(implicitQ, Matrix{eltype(implicitQ)}(I, sq, sq))
        return implicitQ, explicitQ
    end

    m, n = 3, 3 # reduced Q 3-by-3, full Q 3-by-3
    implicitQ, explicitQ = getqs(lq(randn(m, n)))
    @test implicitQ[1, 1] == explicitQ[1, 1]
    @test implicitQ[m, 1] == explicitQ[m, 1]
    @test implicitQ[1, n] == explicitQ[1, n]
    @test implicitQ[m, n] == explicitQ[m, n]

    m, n = 3, 4 # reduced Q 3-by-4, full Q 4-by-4
    implicitQ, explicitQ = getqs(lq(randn(m, n)))
    @test implicitQ[1, 1] == explicitQ[1, 1]
    @test implicitQ[m, 1] == explicitQ[m, 1]
    @test implicitQ[1, n] == explicitQ[1, n]
    @test implicitQ[m, n] == explicitQ[m, n]
    @test implicitQ[m+1, 1] == explicitQ[m+1, 1]
    @test implicitQ[m+1, n] == explicitQ[m+1, n]

    m, n = 4, 3 # reduced Q 3-by-3, full Q 3-by-3
    implicitQ, explicitQ = getqs(lq(randn(m, n)))
    @test implicitQ[1, 1] == explicitQ[1, 1]
    @test implicitQ[n, 1] == explicitQ[n, 1]
    @test implicitQ[1, n] == explicitQ[1, n]
    @test implicitQ[n, n] == explicitQ[n, n]
end

@testset "size on LQPackedQ (#23780)" begin
    # size(Q::LQPackedQ) yields the shape of Q's full/square form
    for ((mA, nA), nQ) in (
        ((3, 3), 3), # A 3-by-3 => full/square Q 3-by-3
        ((3, 4), 4), # A 3-by-4 => full/square Q 4-by-4
        ((4, 3), 3) )# A 4-by-3 => full/square Q 3-by-3
        @test size(lq(randn(mA, nA)).Q) == (nQ, nQ)
    end
end

@testset "postmultiplication with / right-application of LQPackedQ (#23779)" begin
    function getqs(F::LinearAlgebra.LQ)
        implicitQ = F.Q
        explicitQ = lmul!(implicitQ, Matrix{eltype(implicitQ)}(I, size(implicitQ)...))
        return implicitQ, explicitQ
    end
    # for any shape m-by-n of LQ-factored matrix, where Q is an LQPackedQ
    # A_mul_B*(C, Q) (Ac_mul_B*(C, Q)) operations should work for
    # *-by-n (n-by-*) C, which we test below via n-by-n C
    for (mA, nA) in ((3, 3), (3, 4), (4, 3))
        implicitQ, explicitQ = getqs(lq(randn(mA, nA)))
        C = randn(nA, nA)
        @test *(C, implicitQ) ≈ *(C, explicitQ)
        @test *(C, adjoint(implicitQ)) ≈ *(C, adjoint(explicitQ))
        @test *(adjoint(C), implicitQ) ≈ *(adjoint(C), explicitQ)
        @test *(adjoint(C), adjoint(implicitQ)) ≈ *(adjoint(C), adjoint(explicitQ))
    end
    # where the LQ-factored matrix has at least as many rows m as columns n,
    # Q's full/square and reduced/rectangular forms have the same shape (n-by-n). hence we expect
    # _only_ *-by-n (n-by-*) C to work in A_mul_B*(C, Q) (Ac_mul_B*(C, Q)) ops.
    # and hence the n-by-n C tests above suffice.
    #
    # where the LQ-factored matrix has more columns n than rows m,
    # Q's full/square form is n-by-n whereas its reduced/rectangular form is m-by-n.
    # hence we need also test *-by-m C with
    # A*_mul_B(C, Q) ops, as below via m-by-m C.
    mA, nA = 3, 4
    implicitQ, explicitQ = getqs(lq(randn(mA, nA)))
    C = randn(mA, mA)
    zeroextCright = hcat(C, zeros(eltype(C), mA))
    zeroextCdown = vcat(C, zeros(eltype(C), (1, mA)))
    @test *(C, implicitQ) ≈ *(zeroextCright, explicitQ)
    @test *(adjoint(C), implicitQ) ≈ *(adjoint(zeroextCdown), explicitQ)
    @test_throws DimensionMismatch C * adjoint(implicitQ)
    @test_throws DimensionMismatch adjoint(C) * adjoint(implicitQ)
end

@testset "det(Q::LQPackedQ)" begin
    @testset for n in 1:3, m in 1:3
        @testset "real" begin
            _, Q = lq(randn(n, m))
            @test det(Q) ≈ det(collect(Q))
            @test abs(det(Q)) ≈ 1
        end
        @testset "complex" begin
            _, Q = lq(randn(ComplexF64, n, m))
            @test det(Q) ≈ det(collect(Q))
            @test abs(det(Q)) ≈ 1
        end
    end
end

end # module TestLQ

max_stars_repo_name: Dictino/julia

max_issues_repo_name: Dictino/julia

max_forks_repo_name: Dictino/julia


text:
"""
This module provides some neural-network-based estimators of the following form:

Input: Vectors y[1,:], ..., y[nTrain,:]

A summary statistic z is calculated from the inputs and this is the input to the NN.
The output of the NN is an "element-wise" filter w, which is then applied to each input y[t,:]

Input filter estimator: vector z[:] = sum_t |y[t,:]|.^2
Output filter: vector w[:]

Output: Vectors y[1,:] .* w[:], ..., y[nTrain,:] .* w[:]

Note: For uplink channel estimation, the input data y[t,:] (of length #antennas)
should be the DFT of what is observed at the antennas. The output of the NN are then
the DFTs of the estimated spatial channels.
"""
module CondNormalTF

using TensorFlow; const tf = TensorFlow
using Distributions
using Interpolations

square = import_op("Square")
"""
    circ_conv(x,w)

Calculate circular convolution of each vector `x[b,:]` with filter `w[:]`
of same length for each `b=1,...,nBatches`.

Note that nn.conv2d calculates the linear convolution with the time-reversed
filter (=correlation). Thus, the filter w needs to be reversed and repeated.
"""
function circ_conv(x,w)
    # x,y dims: nBatches, nFilterLength
    const nBatches = -1 # special value in TF
    s     = get_shape(w).dims
    nFilterLength = get(s[1])

    xx = reshape(x,[nBatches,nFilterLength,1,1]) # arrange as 4D array for conv2d
    ww = reshape(tile(w[nFilterLength:-1:1],[2]), [2*nFilterLength,1,1,1]) # reverse, repeat, and arrange as 4D-array for conv2d

    z = squeeze(nn.conv2d(xx,ww, strides=[1,1,1,1], padding="SAME"),[3,4]) # dims: nBatches, nFilterLength
end

# TF routines need format: batch-coherence-antennas
# and CNN operates on DFT of observations
cnn_perm = x -> permutedims(x,[3,2,1])

include("ConvNN.jl")

end

max_stars_repo_name: tum-msv/learning-mmse-est


text:
@defcomp impacttropicalstorms begin
    regions = Index()

    hurrdam = Variable(index=[time,regions])
    hurrdead = Variable(index=[time,regions])

    hurrbasedam = Parameter(index=[regions])
    hurrdamel = Parameter(default = -0.514)
    hurrnl = Parameter(default = 3)
    hurrpar = Parameter(default = 0.04)
    hurrbasedead = Parameter(index=[regions])
    hurrdeadel = Parameter(default = -0.501)

    gdp90 = Parameter(index=[regions])
    pop90 = Parameter(index=[regions])

    population = Parameter(index=[time,regions])
    income = Parameter(index=[time,regions])

    regstmp = Parameter(index=[time,regions])

    function run_timestep(p, v, d, t)

        for r in d.regions
            ypc = p.income[t, r] / p.population[t, r] * 1000.0
            ypc90 = p.gdp90[r] / p.pop90[r] * 1000.0

            # This is hurrican damage
            v.hurrdam[t, r] = 0.001 * p.hurrbasedam[r] * p.income[t, r] * (ypc / ypc90)^p.hurrdamel * ((1.0 + p.hurrpar * p.regstmp[t, r])^p.hurrnl - 1.0)

            v.hurrdead[t, r] = 1000.0 * p.hurrbasedead[r] * p.population[t, r] * (ypc / ypc90)^p.hurrdeadel * ((1.0 + p.hurrpar * p.regstmp[t, r])^p.hurrnl - 1.0)
        end
    end
end


text:
# Many datasets have tree-like indices.  Examples:
#
#        Index        Data
#
# * OS:  directories           files
# * Git: trees                 blobs
# * S3:  prefixes              blobs
# * HDF5 group                 typed data
# * Zip  flattend directory(?) blobs
#

import AbstractTrees: AbstractTrees, children

#-------------------------------------------------------------------------------
abstract type AbstractBlobTree; end

# The tree API

# TODO: Should we have `istree` separate from `isdir`?
Base.isdir(x::AbstractBlobTree) = true
Base.isfile(tree::AbstractBlobTree) = false
Base.ispath(x::AbstractBlobTree) = true

# Number of children is not known without a (potentially high-latency) call to
# an external resource
Base.IteratorSize(tree::AbstractBlobTree) = Base.SizeUnknown()

function Base.iterate(tree::AbstractBlobTree, state=nothing)
    if state == nothing
        # By default, call `children(tree)` to eagerly get a list of children
        # for iteration.
        cs = children(tree)
        itr = iterate(cs)
    else
        (cs, cstate) = state
        itr = iterate(cs, cstate)
    end
    if itr == nothing
        return nothing
    else
        (c, cstate) = itr
        (c, (cs, cstate))
    end
end

"""
    children(tree::AbstractBlobTree)

Return an array of the children of `tree`. A child `x` may abstractly either be
another tree (`children(x)` returns a collection) or a file, where `children(x)`
returns `()`.

Note that this is subtly different from `readdir(path)` which returns relative
paths, or `readdir(path, join=true)` which returns absolute paths.
"""
function children(tree::AbstractBlobTree)
    # TODO: Is dispatch to the root a correct default?
    children(tree.root, tree.path)
end

"""
    showtree([io,], tree)

Pretty printing of file trees, in the spirit of the unix `tree` utility.
"""
function showtree(io::IO, tree::AbstractBlobTree; maxdepth=5)
    println(io, "📂 ", tree)
    _showtree(io, tree, "", maxdepth)
end

struct ShownTree
    tree
end
# Use a wrapper rather than defaulting to stdout so that this works in more
# functional environments such as Pluto.jl
showtree(tree::AbstractBlobTree) = ShownTree(tree)

Base.show(io::IO, s::ShownTree) = showtree(io, s.tree)

function _showtree(io::IO, tree::AbstractBlobTree, prefix, depth)
    cs = children(tree)
    for (i,x) in enumerate(cs)
        islast = i == lastindex(cs) # TODO: won't work if children() is lazy
        first_prefix = prefix * (islast ? "└──" : "├──")
        other_prefix = prefix * (islast ? "   " : "│  ")
        if isdir(x)
            print(io, first_prefix, "📂 ")
            printstyled(io, basename(x), "\n", color=:light_blue, bold=true)
            if depth > 1
                _showtree(io, x, other_prefix, depth-1)
            else
                print(io, other_prefix, '⋮')
            end
        else
            println(io, first_prefix, " ", basename(x))
        end
    end
end

function Base.copy!(dst::AbstractBlobTree, src::AbstractBlobTree)
    for x in src
        newpath = joinpath(dst, basename(x))
        if isdir(x)
            newdir = mkdir(newpath)
            copy!(newdir, x)
        else
            open(x) do io_src
                open(newpath, write=true) do io_dst
                    write(io_dst, io_src)
                end
            end
        end
    end
end

#-------------------------------------------------------------------------------
"""
    Blob(root)
    Blob(root, relpath)

`Blob` represents the location of a collection of unstructured binary data. The
location is a path `relpath` relative to some `root` data resource.

A `Blob` can naturally be `open()`ed as a `Vector{UInt8}`, but can also be
mapped into the program as an `IO` byte stream, or interpreted as a `String`.

Blobs can be arranged into hierarchies "directories" via the `BlobTree` type.
"""
mutable struct Blob{Root}
    root::Root
    path::RelPath
end

Blob(root) = Blob(root, RelPath())

Base.basename(file::Blob) = basename(file.path)
Base.abspath(file::Blob) = AbsPath(file.root, file.path)
Base.isdir(file::Blob) = false
Base.isfile(file::Blob) = true
Base.ispath(file::Blob) = true

function Base.show(io::IO, ::MIME"text/plain", file::Blob)
    print(io, "📄 ", file.path, " @ ", summary(file.root))
end

function AbstractTrees.printnode(io::IO, file::Blob)
    print(io, "📄 ",  basename(file))
end

# Opening as Vector{UInt8} or as String defers to IO interface
function Base.open(f::Function, ::Type{Vector{UInt8}}, file::Blob)
    open(IO, file.root, file.path) do io
        f(read(io)) # TODO: use Mmap?
    end
end

function Base.open(f::Function, ::Type{String}, file::Blob)
    open(IO, file.root, file.path) do io
        f(read(io, String))
    end
end

# Default open-type for Blob is IO
Base.open(f::Function, file::Blob; kws...) = open(f, IO, file.root, file.path; kws...)

# Opening Blob as itself is trivial
function Base.open(f::Function, ::Type{Blob}, file::Blob)
    f(file)
end

# open with other types T defers to the underlying storage system
function Base.open(f::Function, ::Type{T}, file::Blob; kws...) where {T}
    open(f, T, file.root, file.path; kws...)
end

# ResourceContexts.jl - based versions of the above.

@! function Base.open(::Type{Vector{UInt8}}, file::Blob)
    @context begin
        # TODO: use Mmap?
        read(@! open(IO, file.root, file.path))
    end
end

@! function Base.open(::Type{String}, file::Blob)
    @context begin
        read(@!(open(IO, file.root, file.path)), String)
    end
end

# Default open-type for Blob is IO
@! function Base.open(file::Blob; kws...)
    @! open(IO, file.root, file.path; kws...)
end

# Opening Blob as itself is trivial
@! function Base.open(::Type{Blob}, file::Blob)
    file
end

# open with other types T defers to the underlying storage system
@! function Base.open(::Type{T}, file::Blob; kws...) where {T}
    @! open(T, file.root, file.path; kws...)
end

# Fallback implementation of `@! open(T, root, path)` based on enter_do.
#
# TODO: Update other backends to avoid calling this; using enter_do is pretty
# inefficient.
@! function Base.open(::Type{T}, root, path; kws...) where {T}
    (res,) = @! enter_do(open, T, root, path; kws...)
    res
end

# Unscoped form of open for Blob
function Base.open(::Type{T}, blob::Blob; kws...) where {T}
    @context begin
        result = @! open(T, blob; kws...)
        @! ResourceContexts.detach_context_cleanup(result)
    end
end

# read() is also supported for `Blob`s
Base.read(file::Blob) = read(file.root, file.path)
Base.read(file::Blob, ::Type{T}) where {T} = read(file.root, file.path, T)

# Support for opening AbsPath
#
# TODO: Put this elsewhere?
function Base.open(f::Function, ::Type{T}, path::AbsPath; kws...) where {T}
    open(f, T, path.root, path.path; kws...)
end

Base.open(f::Function, path::AbsPath; kws...) = open(f, IO, path.root, path.path; kws...)

#-------------------------------------------------------------------------------
"""
    BlobTree(root)

`BlobTree` is a "directory tree" like hierarchy which may have `Blob`s and
`BlobTree`s as children.

The tree implements the `AbstracTrees.children()` interface and may be indexed
with paths to traverse the hierarchy down to the leaves ("files") which are of
type `Blob`. Individual leaves may be `open()`ed as various Julia types.

# Example

Normally you'd construct these via the [`dataset`](@ref) function which takes
care of constructing the correct `root` object. However, here's a direct
demonstration:

```
julia> tree = BlobTree(DataSets.FileSystemRoot(dirname(pathof(DataSets))), path"../test/data")
📂 Tree ../test/data @ /home/chris/.julia/dev/DataSets/src
 📁 csvset
 📄 file.txt
 📄 foo.txt
 📄 people.csv.gz

julia> tree["csvset"]
📂 Tree ../test/data/csvset @ /home/chris/.julia/dev/DataSets/src
 📄 1.csv
 📄 2.csv

julia> tree[path"csvset"]
📂 Tree ../test/data/csvset @ /home/chris/.julia/dev/DataSets/src
 📄 1.csv
 📄 2.csv
```
"""
mutable struct BlobTree{Root} <: AbstractBlobTree
    root::Root
    path::RelPath
end

BlobTree(root) = BlobTree(root, RelPath())

function AbstractTrees.printnode(io::IO, tree::BlobTree)
    print(io, "📂 ",  basename(tree))
end

function Base.show(io::IO, ::MIME"text/plain", tree::AbstractBlobTree)
    # TODO: Ideally we'd use
    # AbstractTrees.print_tree(io, tree, 1)
    # However, this is hard to use efficiently; we'd need to implement a lazy
    # `children()` for all our trees. It'd be much easier if
    # `AbstractTrees.has_children()` was used consistently upstream.
    cs = children(tree)
    println(io, "📂 Tree ", tree.path, " @ ", summary(tree.root))
    for (i, c) in enumerate(cs)
        print(io, " ", isdir(c) ? '📁' : '📄', " ", basename(c))
        if i != length(cs)
            print(io, '\n')
        end
    end
end

Base.basename(tree::BlobTree) = basename(tree.path)
Base.abspath(tree::BlobTree) = AbsPath(tree.root, tree.path)

# getindex vs joinpath:
#  - getindex about indexing the datastrcutre; therefore it looks in the
#    filesystem to only return things which exist.
#  - joinpath just makes paths, not knowing whether they exist.
function Base.getindex(tree::BlobTree, path::RelPath)
    relpath = joinpath(tree.path, path)
    root = tree.root
    # TODO: Make this more efficient by moving this work to the storage backend?
    # Sort of like an equivalent of `stat`?
    if isdir(root, relpath)
        BlobTree(root, relpath)
    elseif isfile(root, relpath)
        Blob(root, relpath)
    elseif ispath(root, relpath)
        AbsPath(root, relpath) # Not great?
    else
        error("Path $relpath @ $root doesn't exist")
    end
end

function Base.getindex(tree::BlobTree, name::AbstractString)
    getindex(tree, joinpath(RelPath(), name))
end

# We've got a weird mishmash of path vs tree handling here.
# TODO: Can we refactor this to cleanly separate the filesystem-like commands
# (which take abstract paths?) from BlobTree and Blob which act as an
# abstraction over the filesystem or other storage mechanisms?
function Base.joinpath(tree::BlobTree, r::RelPath)
    AbsPath(tree.root, joinpath(tree.path, r))
end

function Base.joinpath(tree::BlobTree, s::AbstractString)
    AbsPath(tree.root, joinpath(tree.path, s))
end

function Base.haskey(tree::BlobTree, name::AbstractString)
    ispath(tree.root, joinpath(tree.path, name))
end

function Base.readdir(tree::BlobTree)
    readdir(tree.root, tree.path)
end

function Base.keys(tree::BlobTree)
    readdir(tree.root, tree.path)
end

function Base.rm(tree::BlobTree; kws...)
    rm(tree.root, tree.path; kws...)
end

function children(tree::BlobTree)
    child_names = readdir(tree)
    [tree[c] for c in child_names]
end

function Base.open(f::Function, ::Type{BlobTree}, tree::BlobTree)
    f(tree)
end

@! function Base.open(::Type{BlobTree}, tree::BlobTree)
    tree
end

# Base.open(::Type{T}, file::Blob; kws...) where {T} = open(identity, T, file.root, file.path; kws...)


text:
using Documenter, JetPackDSP

makedocs(sitename="JetPackDSP", modules=[JetPackDSP])

deploydocs(
    repo = "github.com/ChevronETC/JetPackDSP.jl.git",
)


text:
"""
Read file line by line.
"""
function get_directories(filepath::String)
	return readlines(filepath)
end

"""
	boxmodelfromjson(volume::String)

Read volume model from a file JSON.
"""
function boxmodel_from_json(volume::String)
	V,EV,FV = json2LARvolume(volume)
	return V,EV,FV
end

"""
Return LAR model (V,EV,FV) of a box, aligned or not to axes.
"""
# overload method of Common
function Common.getmodel(bbin::String)
	# path of voume json
	return boxmodel_from_json(bbin)
end

function Common.getmodel(bbin::Array{Float64,1})
	# in questo formato gli viene passato -> bbin = [x_min y_min z_min x_max y_max z_max ]
	bb = AABB(bbin[4], bbin[1], bbin[5], bbin[2], bbin[6], bbin[3])
	return Common.boxmodel_from_aabb(bb)
end

"""
In recursive mode, search all files with key in filename.
"""
function searchfile(path::String,key::String)
	files = String[]
	for (root, _, _) in walkdir(path)
		thisfiles = filter(x->occursin(key,x), readdir(root,join=true))
		union!(files,thisfiles)
	end
	return files
end

"""
create folder of project
"""
function mkdir_project(folder::String, project_name::String)
	@assert isdir(folder) "$folder not an existing folder"
	proj_folder = joinpath(folder,project_name)

	mkdir_if(proj_folder)

	return proj_folder
end

"""
folder
"""
function mkdir_if(folder::String)
	if !isdir(folder)
		mkdir(folder)
	end
end

"""
	clearfolder(folder::String)

Clear the given `folder`.
"""
function clearfolder(folder::String)
	root, dirs, files = first(walkdir(folder))
	for dir in dirs
		rm(joinpath(root,dir),recursive=true)
	end
	for file in files
		rm(joinpath(root,file))
	end
	return 1
end

"""
generate input point cloud
"""
function source2pc(source::String, lod::Union{Nothing,Int64})

	if isdir(source) # se source è un potree
		flushprintln("Potree struct")
		cloud_metadata = CloudMetadata(source)

		if lod == -1
			trie = potree2trie(source)
			max_level = Potree.max_depth(trie)
			all_files = Potree.get_all_values(trie)
			PC = Potree.las2pointcloud(all_files...)
			return PC
		else
			all_files = Potree.get_files_in_potree_folder(source,lod)
			PC = Potree.las2pointcloud(all_files...)
			return PC
		end

	elseif isfile(source) # se source è un file
		PC = Potree.las2pointcloud(source)
		return PC
	end

end


text:
"""

This example demonstrates the usage of stochastic gradient descent(sgd) based
optimization methods. We train LeNet model on MNIST dataset similar to `lenet.jl`.

You can run the demo using `julia optimizers.jl`.  Use `julia optimizers.jl
--help` for a list of options. By default the [LeNet](http://yann.lecun.com/exdb/lenet)
convolutional neural network model will be trained using sgd for 10 epochs.
At the end of the training accuracy for the training and test sets for each epoch will be printed
and optimized parameters will be returned.

"""
module Optimizers
using Knet,CUDA,MLDatasets,ArgParse,Random

function main(args=ARGS)
    s = ArgParseSettings()
    s.description="optimizers.jl (c) Ozan Arkan Can and Deniz Yuret, 2016. Demonstration of different sgd based optimization methods using LeNet."
    s.exc_handler=ArgParse.debug_handler
    @add_arg_table s begin
        ("--seed"; arg_type=Int; default=-1; help="random number seed: use a nonnegative int for repeatable results")
        ("--batchsize"; arg_type=Int; default=100; help="minibatch size")
        ("--lr"; arg_type=Float64; default=0.1; help="learning rate")
	("--eps"; arg_type=Float64; default=1e-6; help="epsilon parameter used in adam, adagrad, adadelta")
	("--gamma"; arg_type=Float64; default=0.95; help="gamma parameter used in momentum and nesterov")
	("--rho"; arg_type=Float64; default=0.9; help="rho parameter used in adadelta and rmsprop")
	("--beta1"; arg_type=Float64; default=0.9; help="beta1 parameter used in adam")
	("--beta2"; arg_type=Float64; default=0.95; help="beta2 parameter used in adam")
        ("--epochs"; arg_type=Int; default=10; help="number of epochs for training")
        ("--iters"; arg_type=Int; default=6000; help="number of updates for training")
	("--optim"; default="SGD"; help="optimization method (SGD, Momentum, Nesterov, Adagrad, Adadelta, Rmsprop, Adam)")
        ("--atype"; default="$(Knet.array_type[])"; help="array and float type to use")
    end
    isa(args, AbstractString) && (args=split(args))
    if in("--help", args) || in("-h", args)
        ArgParse.show_help(s; exit_when_done=false)
        return
    end
    println(s.description)
    o = parse_args(args, s; as_symbols=true)
    println("opts=",[(k,v) for (k,v) in o]...)
    o[:seed] > 0 && Knet.seed!(o[:seed])
    atype = eval(Meta.parse(o[:atype]))
    if atype <: Array; @warn("CPU conv4 support is experimental and very slow."); end

    xtrn,ytrn = MNIST.traindata(Float32); ytrn[ytrn .== 0] .= 10
    xtst,ytst = MNIST.testdata(Float32);  ytst[ytst .== 0] .= 10
    xsize = (size(xtrn,1),size(xtrn,2),1,o[:batchsize])
    dtrn = minibatch(xtrn, ytrn, o[:batchsize], xtype=atype, xsize=xsize)
    dtst = minibatch(xtst, ytst, o[:batchsize], xtype=atype, xsize=xsize)
    w = weights(atype=atype)
    prms = params(w, o)

    # log = Any[]
    # report(epoch)=push!(log, (:epoch,epoch,:trn,accuracy(w,dtrn,predict),:tst,accuracy(w,dtst,predict)))
    report(epoch)=println((:epoch,epoch,:trn,accuracy(w,dtrn,predict),:tst,accuracy(w,dtst,predict)))
    report(0)
    iters = o[:iters]
    @time for epoch=1:o[:epochs]
	train(w, prms, dtrn; epochs=1, iters=iters)
	report(epoch)
        (iters -= length(dtrn)) <= 0 && break
    end

    # for t in log; println(t); end
    return w
end

function train(w, prms, data; epochs=10, iters=6000)
    for epoch=1:epochs
        for (x,y) in data
            g = lossgradient(w, x, y)
            update!(w, g, prms)
            if (iters -= 1) <= 0
                return w
            end
        end
    end
    return w
end

function predict(w,x)
    n=length(w)-4
    for i=1:2:n
        x = pool(relu.(conv4(w[i],x; padding=0) .+ w[i+1]))
    end
    x = mat(x)
    for i=n+1:2:length(w)-2
        x = relu.(w[i]*x .+ w[i+1])
    end
    return w[end-1]*x .+ w[end]
end

loss(w,x,ygold) = nll(predict(w,x), ygold)

lossgradient = grad(loss)

function weights(;atype=KnetArray{Float32})
    w = Array{Any}(undef, 8)
    w[1] = xavier(Float32,5,5,1,20)
    w[2] = zeros(Float32,1,1,20,1)
    w[3] = xavier(Float32,5,5,20,50)
    w[4] = zeros(Float32,1,1,50,1)
    w[5] = xavier(Float32,500,800)
    w[6] = zeros(Float32,500,1)
    w[7] = xavier(Float32,10,500)
    w[8] = zeros(Float32,10,1)
    return map(a->convert(atype,a), w)
end

#Creates necessary parameters for each weight to use in the optimization
function params(ws, o)
	prms = Any[]

	for i=1:length(ws)
		w = ws[i]
		if o[:optim] == "SGD"
			prm = SGD(;lr=o[:lr])
		elseif o[:optim] == "Momentum"
			prm = Momentum(lr=o[:lr], gamma=o[:gamma])
		elseif o[:optim] == "Nesterov"
			prm = Nesterov(lr=o[:lr], gamma=o[:gamma])
		elseif o[:optim] == "Adagrad"
			prm = Adagrad(lr=o[:lr], eps=o[:eps])
		elseif o[:optim] == "Adadelta"
			prm = Adadelta(lr=o[:lr], rho=o[:rho], eps=o[:eps])
		elseif o[:optim] == "Rmsprop"
			prm = Rmsprop(lr=o[:lr], rho=o[:rho], eps=o[:eps])
		elseif o[:optim] == "Adam"
			prm = Adam(lr=o[:lr], beta1=o[:beta1], beta2=o[:beta2], eps=o[:eps])
		else
			error("Unknown optimization method!")
		end
		push!(prms, prm)
	end

	return prms
end

# This allows both non-interactive (shell command) and interactive calls like:
# $ julia optimizers.jl --epochs 10
# julia> Optim.main("--epochs 10")
PROGRAM_FILE == "optimizers.jl" && main(ARGS)

end # module

#=
Example Runs
julia optimizers.jl --epochs 10 --lr 0.1
(:epoch,0,:trn,(0.116283335f0,2.2941937f0),:tst,(0.1145f0,2.2946365f0))
(:epoch,1,:trn,(0.9543667f0,0.13499537f0),:tst,(0.958f0,0.12281874f0))
(:epoch,2,:trn,(0.9761f0,0.07270251f0),:tst,(0.9777f0,0.068315394f0))
(:epoch,3,:trn,(0.9838667f0,0.050217737f0),:tst,(0.9827f0,0.051610798f0))
(:epoch,4,:trn,(0.98865f0,0.035738606f0),:tst,(0.9861f0,0.041292988f0))
(:epoch,5,:trn,(0.99125f0,0.027983023f0),:tst,(0.9878f0,0.03583622f0))
(:epoch,6,:trn,(0.99266666f0,0.022933502f0),:tst,(0.9887f0,0.03300085f0))
(:epoch,7,:trn,(0.994f0,0.019440753f0),:tst,(0.9892f0,0.031878017f0))
(:epoch,8,:trn,(0.99455f0,0.017081417f0),:tst,(0.9896f0,0.032124583f0))
(:epoch,9,:trn,(0.9952f0,0.015017059f0),:tst,(0.9895f0,0.032097496f0))
(:epoch,10,:trn,(0.9956333f0,0.013202912f0),:tst,(0.99f0,0.032265987f0))

julia optimizers.jl --epochs 10 --optim Momentum --lr 0.005 --gamma 0.99
(:epoch,0,:trn,(0.1113f0,2.3082018f0),:tst,(0.109f0,2.3084798f0))
(:epoch,1,:trn,(0.9766167f0,0.0770328f0),:tst,(0.9771f0,0.07414803f0))
(:epoch,2,:trn,(0.9861f0,0.043933548f0),:tst,(0.9827f0,0.053114332f0))
(:epoch,3,:trn,(0.98613334f0,0.04348948f0),:tst,(0.984f0,0.057768427f0))
(:epoch,4,:trn,(0.9903167f0,0.030606346f0),:tst,(0.9874f0,0.049403645f0))
(:epoch,5,:trn,(0.99516666f0,0.015177544f0),:tst,(0.9896f0,0.037613332f0))
(:epoch,6,:trn,(0.9928667f0,0.022532726f0),:tst,(0.9874f0,0.04748415f0))
(:epoch,7,:trn,(0.99306667f0,0.020087594f0),:tst,(0.9865f0,0.046911795f0))
(:epoch,8,:trn,(0.9956333f0,0.013521209f0),:tst,(0.9897f0,0.04430927f0))
(:epoch,9,:trn,(0.99703336f0,0.009070589f0),:tst,(0.9896f0,0.04142135f0))
(:epoch,10,:trn,(0.99545f0,0.013547439f0),:tst,(0.9889f0,0.050601155f0))

julia optimizers.jl --epochs 10 --optim Adam --lr 0.001 --beta1 0.9 --beta2 0.95 --eps 1e-8
(:epoch,0,:trn,(0.09903333f0,2.3000493f0),:tst,(0.1008f0,2.2998705f0))
(:epoch,1,:trn,(0.9783667f0,0.068403654f0),:tst,(0.9778f0,0.06494001f0))
(:epoch,2,:trn,(0.99105f0,0.029772233f0),:tst,(0.9881f0,0.035110194f0))
(:epoch,3,:trn,(0.9928667f0,0.022084517f0),:tst,(0.9888f0,0.03618613f0))
(:epoch,4,:trn,(0.9949833f0,0.016130717f0),:tst,(0.99f0,0.035175573f0))
(:epoch,5,:trn,(0.9946f0,0.016869426f0),:tst,(0.9911f0,0.037593916f0))
(:epoch,6,:trn,(0.99328333f0,0.020982243f0),:tst,(0.9896f0,0.04647621f0))
(:epoch,7,:trn,(0.99435f0,0.018795041f0),:tst,(0.9883f0,0.056620233f0))
(:epoch,8,:trn,(0.99576664f0,0.014459096f0),:tst,(0.9896f0,0.053490806f0))
(:epoch,9,:trn,(0.99726665f0,0.0086101545f0),:tst,(0.9902f0,0.053602222f0))
(:epoch,10,:trn,(0.99805f0,0.0059931586f0),:tst,(0.9907f0,0.04834718f0))

julia optimizers.jl --epochs 10 --optim Adagrad --lr 0.01 --eps 1e-6
(:epoch,0,:trn,(0.09983333f0,2.3135705f0),:tst,(0.102f0,2.3134475f0))
(:epoch,1,:trn,(0.98385f0,0.052541837f0),:tst,(0.9822f0,0.051062915f0))
(:epoch,2,:trn,(0.98948336f0,0.03411366f0),:tst,(0.9874f0,0.03760465f0))
(:epoch,3,:trn,(0.99258333f0,0.024431698f0),:tst,(0.9883f0,0.031564854f0))
(:epoch,4,:trn,(0.9945667f0,0.018760378f0),:tst,(0.9895f0,0.028625559f0))
(:epoch,5,:trn,(0.99558336f0,0.015392832f0),:tst,(0.9905f0,0.027373016f0))
(:epoch,6,:trn,(0.99635f0,0.013078845f0),:tst,(0.9907f0,0.026836984f0))
(:epoch,7,:trn,(0.9967f0,0.011378325f0),:tst,(0.991f0,0.026760537f0))
(:epoch,8,:trn,(0.9972f0,0.009899871f0),:tst,(0.9916f0,0.026756253f0))
(:epoch,9,:trn,(0.9975833f0,0.008612509f0),:tst,(0.9917f0,0.026813095f0))
(:epoch,10,:trn,(0.9981167f0,0.0075078686f0),:tst,(0.9914f0,0.026876792f0))

julia optimizers.jl --epochs 10 --optim Adadelta --lr 0.35 --rho 0.9 --eps 1e-6
(:epoch,0,:trn,(0.10545f0,2.3033164f0),:tst,(0.1044f0,2.3031325f0))
(:epoch,1,:trn,(0.96865f0,0.094790496f0),:tst,(0.9704f0,0.08684527f0))
(:epoch,2,:trn,(0.98265f0,0.052093666f0),:tst,(0.982f0,0.05110204f0))
(:epoch,3,:trn,(0.98755f0,0.03808583f0),:tst,(0.9854f0,0.041785713f0))
(:epoch,4,:trn,(0.99105f0,0.027597718f0),:tst,(0.9884f0,0.034749445f0))
(:epoch,5,:trn,(0.9936f0,0.020410579f0),:tst,(0.9903f0,0.030838303f0))
(:epoch,6,:trn,(0.99505f0,0.015846655f0),:tst,(0.9916f0,0.029965784f0))
(:epoch,7,:trn,(0.9963167f0,0.011981298f0),:tst,(0.9915f0,0.028378064f0))
(:epoch,8,:trn,(0.99655f0,0.010981782f0),:tst,(0.9906f0,0.029865112f0))
(:epoch,9,:trn,(0.9967667f0,0.009754072f0),:tst,(0.991f0,0.030760523f0))
(:epoch,10,:trn,(0.9967167f0,0.009537837f0),:tst,(0.9907f0,0.033669963f0))

julia optimizers.jl --epochs 10 --optim Rmsprop --lr 0.001 --rho 0.9 --eps 1e-6
(:epoch,0,:trn,(0.0939f0,2.3106394f0),:tst,(0.0982f0,2.3105752f0))
(:epoch,1,:trn,(0.97908336f0,0.064061135f0),:tst,(0.9799f0,0.058447704f0))
(:epoch,2,:trn,(0.9867833f0,0.03991856f0),:tst,(0.9853f0,0.041050147f0))
(:epoch,3,:trn,(0.99165f0,0.026376523f0),:tst,(0.9898f0,0.03340754f0))
(:epoch,4,:trn,(0.9941667f0,0.017389463f0),:tst,(0.9906f0,0.027854504f0))
(:epoch,5,:trn,(0.9946167f0,0.015640112f0),:tst,(0.9901f0,0.031023417f0))
(:epoch,6,:trn,(0.9949333f0,0.014334091f0),:tst,(0.9904f0,0.033757735f0))
(:epoch,7,:trn,(0.99625f0,0.011019098f0),:tst,(0.9907f0,0.034442622f0))
(:epoch,8,:trn,(0.99691665f0,0.008667187f0),:tst,(0.9912f0,0.030480979f0))
(:epoch,9,:trn,(0.9974f0,0.00787889f0),:tst,(0.9906f0,0.03693716f0))
(:epoch,10,:trn,(0.9979f0,0.0062678233f0),:tst,(0.9911f0,0.034750625f0))
=#


text:
using Graphons

# sample a graph with 10 nodes from a graphon with equal size groups
println("sample a graph with 10 nodes from a graphon with equal size groups")
k = 5
g = SBM(fill(1/k,k))
A = sample(g, 10)
println(A)

# create an erdos renyi graph with p=.3
# and find a histogram of its degree distribution
println("create an erdos renyi graph with p=.3 and find a histogram of its degree distribution")
erdos = erdosrenyi(.3)
edge_density(erdos,100)
h = hist(degree_distribution(erdos,100))
println(h)


text:
module TestPrecompile

using Test, DataFrames

@testset "precompile" begin
    @test DataFrames.precompile() === nothing
    @test DataFrames.precompile(true) === nothing
end

end


text:
import JSON
using MultiAgentPathFinding

function main(infile::String, start_x::Int64, start_y::Int64, goal_x::Int64, goal_y::Int64, weight::Float64)

    config = JSON.parsefile(infile)

    dim = convert(Vector{Int64}, config["map"]["dimensions"])

    obstacles = Set{Grid2DLocation}()
    for obs in config["map"]["obstacles"]
        obs_arr = convert(Vector{Int64}, obs)
        push!(obstacles, Grid2DLocation((x=obs_arr[1], y=obs_arr[2])))
    end

    start = Grid2DLocation((x=start_x, y=start_y))
    goal = Grid2DLocation((x=goal_x, y=goal_y))

    env = AStarGrid2DEnvironment(dimx=dim[1], dimy=dim[2], goal=goal, obstacles=obstacles)

    @time solution, cost = low_level_search!(env, start, weight)

    if solution == nothing
        println("Plannign not successful!")
    else
        println("Solution: ")
        for s in solution
            println(s)
        end

        println("Cost: ",cost)
    end
end