text:
module LightBSON

using DataStructures
using Dates
using DecFP
using FNVHash
using Sockets
using StructTypes
using Transducers
using UnsafeArrays
using UUIDs
using WeakRefStrings

export BSONConversionError
export AbstractBSONReader, BSONReader, BSONWriter, BSONWriteBuffer
export BSONValidator, StrictBSONValidator, LightBSONValidator, UncheckedBSONValidator
export BSONIndex, IndexedBSONReader
export BSONObjectId, BSONObjectIdGenerator
export BSONTimestamp
export BSONCode, BSONCodeWithScope, BSONSymbol
export BSONBinary, UnsafeBSONBinary
export BSONRegex, UnsafeBSONString
export BSONMinKey, BSONMaxKey
export BSONUndefined
export BSONUUIDOld
export BSONDBPointer

export BSON_TYPE_DOUBLE,
    BSON_TYPE_STRING,
    BSON_TYPE_DOCUMENT,
    BSON_TYPE_ARRAY,
    BSON_TYPE_BINARY,
    BSON_TYPE_UNDEFINED,
    BSON_TYPE_OBJECTID,
    BSON_TYPE_BOOL,
    BSON_TYPE_DATETIME,
    BSON_TYPE_NULL,
    BSON_TYPE_REGEX,
    BSON_TYPE_DB_POINTER,
    BSON_TYPE_CODE,
    BSON_TYPE_SYMBOL,
    BSON_TYPE_CODE_WITH_SCOPE,
    BSON_TYPE_INT32,
    BSON_TYPE_TIMESTAMP,
    BSON_TYPE_INT64,
    BSON_TYPE_DECIMAL128

export BSON_SUBTYPE_GENERIC_BINARY,
    BSON_SUBTYPE_FUNCTION,
    BSON_SUBTYPE_BINARY_OLD,
    BSON_SUBTYPE_UUID_OLD,
    BSON_SUBTYPE_UUID,
    BSON_SUBTYPE_MD5,
    BSON_SUBTYPE_ENCRYPTED

export bson_simple
export bson_read, bson_read_simple, bson_read_structtype, bson_read_unversioned, bson_read_versioned
export bson_write, bson_write_simple, bson_write_structtype
export bson_schema_version, bson_schema_version_field
export bson_object_id_range

bson_schema_version(::Type{T}) where T = nothing

bson_schema_version_field(::Type{T}) where T = "_v"

bson_simple(::Type{T}) where T = StructTypes.StructType(T) == StructTypes.NoStructType()

include("object_id.jl")
include("types.jl")
include("representations.jl")
include("exceptions.jl")
include("validator.jl")
include("reader.jl")
include("index.jl")
include("indexed_reader.jl")
include("writer.jl")
include("write_buffer.jl")
include("convenience.jl")
include("fileio.jl")

end


text:
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function IDACreate()
    ccall((:IDACreate,libsundials_ida),IDAMemPtr,())
end

function __IDASetErrHandlerFn(ida_mem::IDAMemPtr,ehfun::IDAErrHandlerFn,eh_data::Ptr{Void})
    ccall((:IDASetErrHandlerFn,libsundials_ida),Cint,(IDAMemPtr,IDAErrHandlerFn,Ptr{Void}),ida_mem,ehfun,eh_data)
end

function IDASetErrHandlerFn(ida_mem,ehfun,eh_data)
    __IDASetErrHandlerFn(convert(IDAMemPtr,ida_mem),ehfun,pointer(eh_data))
end

function __IDASetErrFile(ida_mem::IDAMemPtr,errfp::Ptr{FILE})
    ccall((:IDASetErrFile,libsundials_ida),Cint,(IDAMemPtr,Ptr{FILE}),ida_mem,errfp)
end

function IDASetErrFile(ida_mem,errfp)
    __IDASetErrFile(convert(IDAMemPtr,ida_mem),errfp)
end

function __IDASetUserData(ida_mem::IDAMemPtr,user_data::Any)
    ccall((:IDASetUserData,libsundials_ida),Cint,(IDAMemPtr,Any),ida_mem,user_data)
end

function IDASetUserData(ida_mem,user_data)
    __IDASetUserData(convert(IDAMemPtr,ida_mem),user_data)
end

function __IDASetMaxOrd(ida_mem::IDAMemPtr,maxord::Cint)
    ccall((:IDASetMaxOrd,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxord)
end

function IDASetMaxOrd(ida_mem,maxord)
    __IDASetMaxOrd(convert(IDAMemPtr,ida_mem),convert(Cint,maxord))
end

function __IDASetMaxNumSteps(ida_mem::IDAMemPtr,mxsteps::Clong)
    ccall((:IDASetMaxNumSteps,libsundials_ida),Cint,(IDAMemPtr,Clong),ida_mem,mxsteps)
end

function IDASetMaxNumSteps(ida_mem,mxsteps)
    __IDASetMaxNumSteps(convert(IDAMemPtr,ida_mem),convert(Clong,mxsteps))
end

function __IDASetInitStep(ida_mem::IDAMemPtr,hin::realtype)
    ccall((:IDASetInitStep,libsundials_ida),Cint,(IDAMemPtr,realtype),ida_mem,hin)
end

function IDASetInitStep(ida_mem,hin)
    __IDASetInitStep(convert(IDAMemPtr,ida_mem),hin)
end

function __IDASetMaxStep(ida_mem::IDAMemPtr,hmax::realtype)
    ccall((:IDASetMaxStep,libsundials_ida),Cint,(IDAMemPtr,realtype),ida_mem,hmax)
end

function IDASetMaxStep(ida_mem,hmax)
    __IDASetMaxStep(convert(IDAMemPtr,ida_mem),hmax)
end

function __IDASetStopTime(ida_mem::IDAMemPtr,tstop::realtype)
    ccall((:IDASetStopTime,libsundials_ida),Cint,(IDAMemPtr,realtype),ida_mem,tstop)
end

function IDASetStopTime(ida_mem,tstop)
    __IDASetStopTime(convert(IDAMemPtr,ida_mem),tstop)
end

function __IDASetNonlinConvCoef(ida_mem::IDAMemPtr,epcon::realtype)
    ccall((:IDASetNonlinConvCoef,libsundials_ida),Cint,(IDAMemPtr,realtype),ida_mem,epcon)
end

function IDASetNonlinConvCoef(ida_mem,epcon)
    __IDASetNonlinConvCoef(convert(IDAMemPtr,ida_mem),epcon)
end

function __IDASetMaxErrTestFails(ida_mem::IDAMemPtr,maxnef::Cint)
    ccall((:IDASetMaxErrTestFails,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxnef)
end

function IDASetMaxErrTestFails(ida_mem,maxnef)
    __IDASetMaxErrTestFails(convert(IDAMemPtr,ida_mem),convert(Cint,maxnef))
end

function __IDASetMaxNonlinIters(ida_mem::IDAMemPtr,maxcor::Cint)
    ccall((:IDASetMaxNonlinIters,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxcor)
end

function IDASetMaxNonlinIters(ida_mem,maxcor)
    __IDASetMaxNonlinIters(convert(IDAMemPtr,ida_mem),convert(Cint,maxcor))
end

function __IDASetMaxConvFails(ida_mem::IDAMemPtr,maxncf::Cint)
    ccall((:IDASetMaxConvFails,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxncf)
end

function IDASetMaxConvFails(ida_mem,maxncf)
    __IDASetMaxConvFails(convert(IDAMemPtr,ida_mem),convert(Cint,maxncf))
end

function __IDASetSuppressAlg(ida_mem::IDAMemPtr,suppressalg::Cint)
    ccall((:IDASetSuppressAlg,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,suppressalg)
end

function IDASetSuppressAlg(ida_mem,suppressalg)
    __IDASetSuppressAlg(convert(IDAMemPtr,ida_mem),convert(Cint,suppressalg))
end

function __IDASetId(ida_mem::IDAMemPtr,id::N_Vector)
    ccall((:IDASetId,libsundials_ida),Cint,(IDAMemPtr,N_Vector),ida_mem,id)
end

function IDASetId(ida_mem,id)
    __id = convert(NVector,id)
    __IDASetId(convert(IDAMemPtr,ida_mem),convert(N_Vector,__id))
end

function __IDASetConstraints(ida_mem::IDAMemPtr,constraints::N_Vector)
    ccall((:IDASetConstraints,libsundials_ida),Cint,(IDAMemPtr,N_Vector),ida_mem,constraints)
end

function IDASetConstraints(ida_mem,constraints)
    __constraints = convert(NVector,constraints)
    __IDASetConstraints(convert(IDAMemPtr,ida_mem),convert(N_Vector,__constraints))
end

function __IDASetRootDirection(ida_mem::IDAMemPtr,rootdir::Ptr{Cint})
    ccall((:IDASetRootDirection,libsundials_ida),Cint,(IDAMemPtr,Ptr{Cint}),ida_mem,rootdir)
end

function IDASetRootDirection(ida_mem,rootdir)
    __IDASetRootDirection(convert(IDAMemPtr,ida_mem),pointer(rootdir))
end

function __IDASetNoInactiveRootWarn(ida_mem::IDAMemPtr)
    ccall((:IDASetNoInactiveRootWarn,libsundials_ida),Cint,(IDAMemPtr,),ida_mem)
end

function IDASetNoInactiveRootWarn(ida_mem)
    __IDASetNoInactiveRootWarn(convert(IDAMemPtr,ida_mem))
end

function __IDAInit(ida_mem::IDAMemPtr,res::IDAResFn,t0::realtype,yy0::N_Vector,yp0::N_Vector)
    ccall((:IDAInit,libsundials_ida),Cint,(IDAMemPtr,IDAResFn,realtype,N_Vector,N_Vector),ida_mem,res,t0,yy0,yp0)
end

function IDAInit(ida_mem,res,t0,yy0,yp0)
    __yy0 = convert(NVector,yy0)
    __yp0 = convert(NVector,yp0)
    __IDAInit(convert(IDAMemPtr,ida_mem),IDAResFn_wrapper(res),t0,convert(N_Vector,__yy0),convert(N_Vector,__yp0))
end

function __IDAReInit(ida_mem::IDAMemPtr,t0::realtype,yy0::N_Vector,yp0::N_Vector)
    ccall((:IDAReInit,libsundials_ida),Cint,(IDAMemPtr,realtype,N_Vector,N_Vector),ida_mem,t0,yy0,yp0)
end

function IDAReInit(ida_mem,t0,yy0,yp0)
    __yy0 = convert(NVector,yy0)
    __yp0 = convert(NVector,yp0)
    __IDAReInit(convert(IDAMemPtr,ida_mem),t0,convert(N_Vector,__yy0),convert(N_Vector,__yp0))
end

function __IDASStolerances(ida_mem::IDAMemPtr,reltol::realtype,abstol::realtype)
    ccall((:IDASStolerances,libsundials_ida),Cint,(IDAMemPtr,realtype,realtype),ida_mem,reltol,abstol)
end

function IDASStolerances(ida_mem,reltol,abstol)
    __IDASStolerances(convert(IDAMemPtr,ida_mem),reltol,abstol)
end

function __IDASVtolerances(ida_mem::IDAMemPtr,reltol::realtype,abstol::N_Vector)
    ccall((:IDASVtolerances,libsundials_ida),Cint,(IDAMemPtr,realtype,N_Vector),ida_mem,reltol,abstol)
end

function IDASVtolerances(ida_mem,reltol,abstol)
    __abstol = convert(NVector,abstol)
    __IDASVtolerances(convert(IDAMemPtr,ida_mem),reltol,convert(N_Vector,__abstol))
end

function __IDAWFtolerances(ida_mem::IDAMemPtr,efun::IDAEwtFn)
    ccall((:IDAWFtolerances,libsundials_ida),Cint,(IDAMemPtr,IDAEwtFn),ida_mem,efun)
end

function IDAWFtolerances(ida_mem,efun)
    __IDAWFtolerances(convert(IDAMemPtr,ida_mem),efun)
end

function __IDASetNonlinConvCoefIC(ida_mem::IDAMemPtr,epiccon::realtype)
    ccall((:IDASetNonlinConvCoefIC,libsundials_ida),Cint,(IDAMemPtr,realtype),ida_mem,epiccon)
end

function IDASetNonlinConvCoefIC(ida_mem,epiccon)
    __IDASetNonlinConvCoefIC(convert(IDAMemPtr,ida_mem),epiccon)
end

function __IDASetMaxNumStepsIC(ida_mem::IDAMemPtr,maxnh::Cint)
    ccall((:IDASetMaxNumStepsIC,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxnh)
end

function IDASetMaxNumStepsIC(ida_mem,maxnh)
    __IDASetMaxNumStepsIC(convert(IDAMemPtr,ida_mem),convert(Cint,maxnh))
end

function __IDASetMaxNumJacsIC(ida_mem::IDAMemPtr,maxnj::Cint)
    ccall((:IDASetMaxNumJacsIC,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxnj)
end

function IDASetMaxNumJacsIC(ida_mem,maxnj)
    __IDASetMaxNumJacsIC(convert(IDAMemPtr,ida_mem),convert(Cint,maxnj))
end

function __IDASetMaxNumItersIC(ida_mem::IDAMemPtr,maxnit::Cint)
    ccall((:IDASetMaxNumItersIC,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxnit)
end

function IDASetMaxNumItersIC(ida_mem,maxnit)
    __IDASetMaxNumItersIC(convert(IDAMemPtr,ida_mem),convert(Cint,maxnit))
end

function __IDASetLineSearchOffIC(ida_mem::IDAMemPtr,lsoff::Cint)
    ccall((:IDASetLineSearchOffIC,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,lsoff)
end

function IDASetLineSearchOffIC(ida_mem,lsoff)
    __IDASetLineSearchOffIC(convert(IDAMemPtr,ida_mem),convert(Cint,lsoff))
end

function __IDASetStepToleranceIC(ida_mem::IDAMemPtr,steptol::realtype)
    ccall((:IDASetStepToleranceIC,libsundials_ida),Cint,(IDAMemPtr,realtype),ida_mem,steptol)
end

function IDASetStepToleranceIC(ida_mem,steptol)
    __IDASetStepToleranceIC(convert(IDAMemPtr,ida_mem),steptol)
end

function __IDARootInit(ida_mem::IDAMemPtr,nrtfn::Cint,g::IDARootFn)
    ccall((:IDARootInit,libsundials_ida),Cint,(IDAMemPtr,Cint,IDARootFn),ida_mem,nrtfn,g)
end

function IDARootInit(ida_mem,nrtfn,g)
    __IDARootInit(convert(IDAMemPtr,ida_mem),convert(Cint,nrtfn),IDARootFn_wrapper(g))
end

function __IDACalcIC(ida_mem::IDAMemPtr,icopt::Cint,tout1::realtype)
    ccall((:IDACalcIC,libsundials_ida),Cint,(IDAMemPtr,Cint,realtype),ida_mem,icopt,tout1)
end

function IDACalcIC(ida_mem,icopt,tout1)
    __IDACalcIC(convert(IDAMemPtr,ida_mem),convert(Cint,icopt),tout1)
end

function __IDASolve(ida_mem::IDAMemPtr,tout::realtype,tret::Ptr{realtype},yret::N_Vector,ypret::N_Vector,itask::Cint)
    ccall((:IDASolve,libsundials_ida),Cint,(IDAMemPtr,realtype,Ptr{realtype},N_Vector,N_Vector,Cint),ida_mem,tout,tret,yret,ypret,itask)
end

function IDASolve(ida_mem,tout,tret,yret,ypret,itask)
    __yret = convert(NVector,yret)
    __ypret = convert(NVector,ypret)
    __IDASolve(convert(IDAMemPtr,ida_mem),tout,pointer(tret),convert(N_Vector,__yret),convert(N_Vector,__ypret),convert(Cint,itask))
end

function __IDAGetDky(ida_mem::IDAMemPtr,t::realtype,k::Cint,dky::N_Vector)
    ccall((:IDAGetDky,libsundials_ida),Cint,(IDAMemPtr,realtype,Cint,N_Vector),ida_mem,t,k,dky)
end

function IDAGetDky(ida_mem,t,k,dky)
    __dky = convert(NVector,dky)
    __IDAGetDky(convert(IDAMemPtr,ida_mem),t,convert(Cint,k),convert(N_Vector,__dky))
end

function __IDAGetWorkSpace(ida_mem::IDAMemPtr,lenrw::Ptr{Clong},leniw::Ptr{Clong})
    ccall((:IDAGetWorkSpace,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong},Ptr{Clong}),ida_mem,lenrw,leniw)
end

function IDAGetWorkSpace(ida_mem,lenrw,leniw)
    __IDAGetWorkSpace(convert(IDAMemPtr,ida_mem),pointer(lenrw),pointer(leniw))
end

function __IDAGetNumSteps(ida_mem::IDAMemPtr,nsteps::Ptr{Clong})
    ccall((:IDAGetNumSteps,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nsteps)
end

function IDAGetNumSteps(ida_mem,nsteps)
    __IDAGetNumSteps(convert(IDAMemPtr,ida_mem),pointer(nsteps))
end

function __IDAGetNumResEvals(ida_mem::IDAMemPtr,nrevals::Ptr{Clong})
    ccall((:IDAGetNumResEvals,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nrevals)
end

function IDAGetNumResEvals(ida_mem,nrevals)
    __IDAGetNumResEvals(convert(IDAMemPtr,ida_mem),pointer(nrevals))
end

function __IDAGetNumLinSolvSetups(ida_mem::IDAMemPtr,nlinsetups::Ptr{Clong})
    ccall((:IDAGetNumLinSolvSetups,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nlinsetups)
end

function IDAGetNumLinSolvSetups(ida_mem,nlinsetups)
    __IDAGetNumLinSolvSetups(convert(IDAMemPtr,ida_mem),pointer(nlinsetups))
end

function __IDAGetNumErrTestFails(ida_mem::IDAMemPtr,netfails::Ptr{Clong})
    ccall((:IDAGetNumErrTestFails,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,netfails)
end

function IDAGetNumErrTestFails(ida_mem,netfails)
    __IDAGetNumErrTestFails(convert(IDAMemPtr,ida_mem),pointer(netfails))
end

function __IDAGetNumBacktrackOps(ida_mem::IDAMemPtr,nbacktr::Ptr{Clong})
    ccall((:IDAGetNumBacktrackOps,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nbacktr)
end

function IDAGetNumBacktrackOps(ida_mem,nbacktr)
    __IDAGetNumBacktrackOps(convert(IDAMemPtr,ida_mem),pointer(nbacktr))
end

function __IDAGetConsistentIC(ida_mem::IDAMemPtr,yy0_mod::N_Vector,yp0_mod::N_Vector)
    ccall((:IDAGetConsistentIC,libsundials_ida),Cint,(IDAMemPtr,N_Vector,N_Vector),ida_mem,yy0_mod,yp0_mod)
end

function IDAGetConsistentIC(ida_mem,yy0_mod,yp0_mod)
    __yy0_mod = convert(NVector,yy0_mod)
    __yp0_mod = convert(NVector,yp0_mod)
    __IDAGetConsistentIC(convert(IDAMemPtr,ida_mem),convert(N_Vector,__yy0_mod),convert(N_Vector,__yp0_mod))
end

function __IDAGetLastOrder(ida_mem::IDAMemPtr,klast::Ptr{Cint})
    ccall((:IDAGetLastOrder,libsundials_ida),Cint,(IDAMemPtr,Ptr{Cint}),ida_mem,klast)
end

function IDAGetLastOrder(ida_mem,klast)
    __IDAGetLastOrder(convert(IDAMemPtr,ida_mem),pointer(klast))
end

function __IDAGetCurrentOrder(ida_mem::IDAMemPtr,kcur::Ptr{Cint})
    ccall((:IDAGetCurrentOrder,libsundials_ida),Cint,(IDAMemPtr,Ptr{Cint}),ida_mem,kcur)
end

function IDAGetCurrentOrder(ida_mem,kcur)
    __IDAGetCurrentOrder(convert(IDAMemPtr,ida_mem),pointer(kcur))
end

function __IDAGetActualInitStep(ida_mem::IDAMemPtr,hinused::Ptr{realtype})
    ccall((:IDAGetActualInitStep,libsundials_ida),Cint,(IDAMemPtr,Ptr{realtype}),ida_mem,hinused)
end

function IDAGetActualInitStep(ida_mem,hinused)
    __IDAGetActualInitStep(convert(IDAMemPtr,ida_mem),pointer(hinused))
end

function __IDAGetLastStep(ida_mem::IDAMemPtr,hlast::Ptr{realtype})
    ccall((:IDAGetLastStep,libsundials_ida),Cint,(IDAMemPtr,Ptr{realtype}),ida_mem,hlast)
end

function IDAGetLastStep(ida_mem,hlast)
    __IDAGetLastStep(convert(IDAMemPtr,ida_mem),pointer(hlast))
end

function __IDAGetCurrentStep(ida_mem::IDAMemPtr,hcur::Ptr{realtype})
    ccall((:IDAGetCurrentStep,libsundials_ida),Cint,(IDAMemPtr,Ptr{realtype}),ida_mem,hcur)
end

function IDAGetCurrentStep(ida_mem,hcur)
    __IDAGetCurrentStep(convert(IDAMemPtr,ida_mem),pointer(hcur))
end

function __IDAGetCurrentTime(ida_mem::IDAMemPtr,tcur::Ptr{realtype})
    ccall((:IDAGetCurrentTime,libsundials_ida),Cint,(IDAMemPtr,Ptr{realtype}),ida_mem,tcur)
end

function IDAGetCurrentTime(ida_mem,tcur)
    __IDAGetCurrentTime(convert(IDAMemPtr,ida_mem),pointer(tcur))
end

function __IDAGetTolScaleFactor(ida_mem::IDAMemPtr,tolsfact::Ptr{realtype})
    ccall((:IDAGetTolScaleFactor,libsundials_ida),Cint,(IDAMemPtr,Ptr{realtype}),ida_mem,tolsfact)
end

function IDAGetTolScaleFactor(ida_mem,tolsfact)
    __IDAGetTolScaleFactor(convert(IDAMemPtr,ida_mem),pointer(tolsfact))
end

function __IDAGetErrWeights(ida_mem::IDAMemPtr,eweight::N_Vector)
    ccall((:IDAGetErrWeights,libsundials_ida),Cint,(IDAMemPtr,N_Vector),ida_mem,eweight)
end

function IDAGetErrWeights(ida_mem,eweight)
    __eweight = convert(NVector,eweight)
    __IDAGetErrWeights(convert(IDAMemPtr,ida_mem),convert(N_Vector,__eweight))
end

function __IDAGetEstLocalErrors(ida_mem::IDAMemPtr,ele::N_Vector)
    ccall((:IDAGetEstLocalErrors,libsundials_ida),Cint,(IDAMemPtr,N_Vector),ida_mem,ele)
end

function IDAGetEstLocalErrors(ida_mem,ele)
    __ele = convert(NVector,ele)
    __IDAGetEstLocalErrors(convert(IDAMemPtr,ida_mem),convert(N_Vector,__ele))
end

function __IDAGetNumGEvals(ida_mem::IDAMemPtr,ngevals::Ptr{Clong})
    ccall((:IDAGetNumGEvals,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,ngevals)
end

function IDAGetNumGEvals(ida_mem,ngevals)
    __IDAGetNumGEvals(convert(IDAMemPtr,ida_mem),pointer(ngevals))
end

function __IDAGetRootInfo(ida_mem::IDAMemPtr,rootsfound::Ptr{Cint})
    ccall((:IDAGetRootInfo,libsundials_ida),Cint,(IDAMemPtr,Ptr{Cint}),ida_mem,rootsfound)
end

function IDAGetRootInfo(ida_mem,rootsfound)
    __IDAGetRootInfo(convert(IDAMemPtr,ida_mem),pointer(rootsfound))
end

function __IDAGetIntegratorStats(ida_mem::IDAMemPtr,nsteps::Ptr{Clong},nrevals::Ptr{Clong},nlinsetups::Ptr{Clong},netfails::Ptr{Clong},qlast::Ptr{Cint},qcur::Ptr{Cint},hinused::Ptr{realtype},hlast::Ptr{realtype},hcur::Ptr{realtype},tcur::Ptr{realtype})
    ccall((:IDAGetIntegratorStats,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong},Ptr{Clong},Ptr{Clong},Ptr{Clong},Ptr{Cint},Ptr{Cint},Ptr{realtype},Ptr{realtype},Ptr{realtype},Ptr{realtype}),ida_mem,nsteps,nrevals,nlinsetups,netfails,qlast,qcur,hinused,hlast,hcur,tcur)
end

function IDAGetIntegratorStats(ida_mem,nsteps,nrevals,nlinsetups,netfails,qlast,qcur,hinused,hlast,hcur,tcur)
    __IDAGetIntegratorStats(convert(IDAMemPtr,ida_mem),pointer(nsteps),pointer(nrevals),pointer(nlinsetups),pointer(netfails),pointer(qlast),pointer(qcur),pointer(hinused),pointer(hlast),pointer(hcur),pointer(tcur))
end

function __IDAGetNumNonlinSolvIters(ida_mem::IDAMemPtr,nniters::Ptr{Clong})
    ccall((:IDAGetNumNonlinSolvIters,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nniters)
end

function IDAGetNumNonlinSolvIters(ida_mem,nniters)
    __IDAGetNumNonlinSolvIters(convert(IDAMemPtr,ida_mem),pointer(nniters))
end

function __IDAGetNumNonlinSolvConvFails(ida_mem::IDAMemPtr,nncfails::Ptr{Clong})
    ccall((:IDAGetNumNonlinSolvConvFails,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nncfails)
end

function IDAGetNumNonlinSolvConvFails(ida_mem,nncfails)
    __IDAGetNumNonlinSolvConvFails(convert(IDAMemPtr,ida_mem),pointer(nncfails))
end

function __IDAGetNonlinSolvStats(ida_mem::IDAMemPtr,nniters::Ptr{Clong},nncfails::Ptr{Clong})
    ccall((:IDAGetNonlinSolvStats,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong},Ptr{Clong}),ida_mem,nniters,nncfails)
end

function IDAGetNonlinSolvStats(ida_mem,nniters,nncfails)
    __IDAGetNonlinSolvStats(convert(IDAMemPtr,ida_mem),pointer(nniters),pointer(nncfails))
end

function __IDAGetReturnFlagName(flag::Clong)
    ccall((:IDAGetReturnFlagName,libsundials_ida),Ptr{UInt8},(Clong,),flag)
end

function IDAGetReturnFlagName(flag)
    __IDAGetReturnFlagName(convert(Clong,flag))
end

function IDAFree(ida_mem::Ref{IDAMemPtr})
    ccall((:IDAFree,libsundials_ida),Void,(Ref{IDAMemPtr},),ida_mem)
end
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_direct.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function __IDADlsSetDenseJacFn(ida_mem::IDAMemPtr,jac::IDADlsDenseJacFn)
    ccall((:IDADlsSetDenseJacFn,libsundials_ida),Cint,(IDAMemPtr,IDADlsDenseJacFn),ida_mem,jac)
end

function IDADlsSetDenseJacFn(ida_mem,jac)
    __IDADlsSetDenseJacFn(convert(IDAMemPtr,ida_mem),jac)
end

function __IDADlsSetBandJacFn(ida_mem::IDAMemPtr,jac::IDADlsBandJacFn)
    ccall((:IDADlsSetBandJacFn,libsundials_ida),Cint,(IDAMemPtr,IDADlsBandJacFn),ida_mem,jac)
end

function IDADlsSetBandJacFn(ida_mem,jac)
    __IDADlsSetBandJacFn(convert(IDAMemPtr,ida_mem),jac)
end

function __IDADlsGetWorkSpace(ida_mem::IDAMemPtr,lenrwLS::Ptr{Clong},leniwLS::Ptr{Clong})
    ccall((:IDADlsGetWorkSpace,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong},Ptr{Clong}),ida_mem,lenrwLS,leniwLS)
end

function IDADlsGetWorkSpace(ida_mem,lenrwLS,leniwLS)
    __IDADlsGetWorkSpace(convert(IDAMemPtr,ida_mem),pointer(lenrwLS),pointer(leniwLS))
end

function __IDADlsGetNumJacEvals(ida_mem::IDAMemPtr,njevals::Ptr{Clong})
    ccall((:IDADlsGetNumJacEvals,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,njevals)
end

function IDADlsGetNumJacEvals(ida_mem,njevals)
    __IDADlsGetNumJacEvals(convert(IDAMemPtr,ida_mem),pointer(njevals))
end

function __IDADlsGetNumResEvals(ida_mem::IDAMemPtr,nfevalsLS::Ptr{Clong})
    ccall((:IDADlsGetNumResEvals,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nfevalsLS)
end

function IDADlsGetNumResEvals(ida_mem,nfevalsLS)
    __IDADlsGetNumResEvals(convert(IDAMemPtr,ida_mem),pointer(nfevalsLS))
end

function __IDADlsGetLastFlag(ida_mem::IDAMemPtr,flag::Ptr{Clong})
    ccall((:IDADlsGetLastFlag,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,flag)
end

function IDADlsGetLastFlag(ida_mem,flag)
    __IDADlsGetLastFlag(convert(IDAMemPtr,ida_mem),pointer(flag))
end

function __IDADlsGetReturnFlagName(flag::Clong)
    ccall((:IDADlsGetReturnFlagName,libsundials_ida),Ptr{UInt8},(Clong,),flag)
end

function IDADlsGetReturnFlagName(flag)
    __IDADlsGetReturnFlagName(convert(Clong,flag))
end
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_spils.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function __IDASpilsSetPreconditioner(ida_mem::IDAMemPtr,pset::IDASpilsPrecSetupFn,psolve::IDASpilsPrecSolveFn)
    ccall((:IDASpilsSetPreconditioner,libsundials_ida),Cint,(IDAMemPtr,IDASpilsPrecSetupFn,IDASpilsPrecSolveFn),ida_mem,pset,psolve)
end

function IDASpilsSetPreconditioner(ida_mem,pset,psolve)
    __IDASpilsSetPreconditioner(convert(IDAMemPtr,ida_mem),pset,psolve)
end

function __IDASpilsSetJacTimesVecFn(ida_mem::IDAMemPtr,jtv::IDASpilsJacTimesVecFn)
    ccall((:IDASpilsSetJacTimesVecFn,libsundials_ida),Cint,(IDAMemPtr,IDASpilsJacTimesVecFn),ida_mem,jtv)
end

function IDASpilsSetJacTimesVecFn(ida_mem,jtv)
    __IDASpilsSetJacTimesVecFn(convert(IDAMemPtr,ida_mem),jtv)
end

function __IDASpilsSetGSType(ida_mem::IDAMemPtr,gstype::Cint)
    ccall((:IDASpilsSetGSType,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,gstype)
end

function IDASpilsSetGSType(ida_mem,gstype)
    __IDASpilsSetGSType(convert(IDAMemPtr,ida_mem),convert(Cint,gstype))
end

function __IDASpilsSetMaxRestarts(ida_mem::IDAMemPtr,maxrs::Cint)
    ccall((:IDASpilsSetMaxRestarts,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxrs)
end

function IDASpilsSetMaxRestarts(ida_mem,maxrs)
    __IDASpilsSetMaxRestarts(convert(IDAMemPtr,ida_mem),convert(Cint,maxrs))
end

function __IDASpilsSetMaxl(ida_mem::IDAMemPtr,maxl::Cint)
    ccall((:IDASpilsSetMaxl,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxl)
end

function IDASpilsSetMaxl(ida_mem,maxl)
    __IDASpilsSetMaxl(convert(IDAMemPtr,ida_mem),convert(Cint,maxl))
end

function __IDASpilsSetEpsLin(ida_mem::IDAMemPtr,eplifac::realtype)
    ccall((:IDASpilsSetEpsLin,libsundials_ida),Cint,(IDAMemPtr,realtype),ida_mem,eplifac)
end

function IDASpilsSetEpsLin(ida_mem,eplifac)
    __IDASpilsSetEpsLin(convert(IDAMemPtr,ida_mem),eplifac)
end

function __IDASpilsSetIncrementFactor(ida_mem::IDAMemPtr,dqincfac::realtype)
    ccall((:IDASpilsSetIncrementFactor,libsundials_ida),Cint,(IDAMemPtr,realtype),ida_mem,dqincfac)
end

function IDASpilsSetIncrementFactor(ida_mem,dqincfac)
    __IDASpilsSetIncrementFactor(convert(IDAMemPtr,ida_mem),dqincfac)
end

function __IDASpilsGetWorkSpace(ida_mem::IDAMemPtr,lenrwLS::Ptr{Clong},leniwLS::Ptr{Clong})
    ccall((:IDASpilsGetWorkSpace,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong},Ptr{Clong}),ida_mem,lenrwLS,leniwLS)
end

function IDASpilsGetWorkSpace(ida_mem,lenrwLS,leniwLS)
    __IDASpilsGetWorkSpace(convert(IDAMemPtr,ida_mem),pointer(lenrwLS),pointer(leniwLS))
end

function __IDASpilsGetNumPrecEvals(ida_mem::IDAMemPtr,npevals::Ptr{Clong})
    ccall((:IDASpilsGetNumPrecEvals,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,npevals)
end

function IDASpilsGetNumPrecEvals(ida_mem,npevals)
    __IDASpilsGetNumPrecEvals(convert(IDAMemPtr,ida_mem),pointer(npevals))
end

function __IDASpilsGetNumPrecSolves(ida_mem::IDAMemPtr,npsolves::Ptr{Clong})
    ccall((:IDASpilsGetNumPrecSolves,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,npsolves)
end

function IDASpilsGetNumPrecSolves(ida_mem,npsolves)
    __IDASpilsGetNumPrecSolves(convert(IDAMemPtr,ida_mem),pointer(npsolves))
end

function __IDASpilsGetNumLinIters(ida_mem::IDAMemPtr,nliters::Ptr{Clong})
    ccall((:IDASpilsGetNumLinIters,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nliters)
end

function IDASpilsGetNumLinIters(ida_mem,nliters)
    __IDASpilsGetNumLinIters(convert(IDAMemPtr,ida_mem),pointer(nliters))
end

function __IDASpilsGetNumConvFails(ida_mem::IDAMemPtr,nlcfails::Ptr{Clong})
    ccall((:IDASpilsGetNumConvFails,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nlcfails)
end

function IDASpilsGetNumConvFails(ida_mem,nlcfails)
    __IDASpilsGetNumConvFails(convert(IDAMemPtr,ida_mem),pointer(nlcfails))
end

function __IDASpilsGetNumJtimesEvals(ida_mem::IDAMemPtr,njvevals::Ptr{Clong})
    ccall((:IDASpilsGetNumJtimesEvals,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,njvevals)
end

function IDASpilsGetNumJtimesEvals(ida_mem,njvevals)
    __IDASpilsGetNumJtimesEvals(convert(IDAMemPtr,ida_mem),pointer(njvevals))
end

function __IDASpilsGetNumResEvals(ida_mem::IDAMemPtr,nrevalsLS::Ptr{Clong})
    ccall((:IDASpilsGetNumResEvals,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,nrevalsLS)
end

function IDASpilsGetNumResEvals(ida_mem,nrevalsLS)
    __IDASpilsGetNumResEvals(convert(IDAMemPtr,ida_mem),pointer(nrevalsLS))
end

function __IDASpilsGetLastFlag(ida_mem::IDAMemPtr,flag::Ptr{Clong})
    ccall((:IDASpilsGetLastFlag,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,flag)
end

function IDASpilsGetLastFlag(ida_mem,flag)
    __IDASpilsGetLastFlag(convert(IDAMemPtr,ida_mem),pointer(flag))
end

function __IDASpilsGetReturnFlagName(flag::Clong)
    ccall((:IDASpilsGetReturnFlagName,libsundials_ida),Ptr{UInt8},(Clong,),flag)
end

function IDASpilsGetReturnFlagName(flag)
    __IDASpilsGetReturnFlagName(convert(Clong,flag))
end
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_band.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function __IDABand(ida_mem::IDAMemPtr,Neq::Clong,mupper::Clong,mlower::Clong)
    ccall((:IDABand,libsundials_ida),Cint,(IDAMemPtr,Clong,Clong,Clong),ida_mem,Neq,mupper,mlower)
end

function IDABand(ida_mem,Neq,mupper,mlower)
    __IDABand(convert(IDAMemPtr,ida_mem),convert(Clong,Neq),convert(Clong,mupper),convert(Clong,mlower))
end
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_bbdpre.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function __IDABBDPrecInit(ida_mem::IDAMemPtr,Nlocal::Clong,mudq::Clong,mldq::Clong,mukeep::Clong,mlkeep::Clong,dq_rel_yy::realtype,Gres::IDABBDLocalFn,Gcomm::IDABBDCommFn)
    ccall((:IDABBDPrecInit,libsundials_ida),Cint,(IDAMemPtr,Clong,Clong,Clong,Clong,Clong,realtype,IDABBDLocalFn,IDABBDCommFn),ida_mem,Nlocal,mudq,mldq,mukeep,mlkeep,dq_rel_yy,Gres,Gcomm)
end

function IDABBDPrecInit(ida_mem,Nlocal,mudq,mldq,mukeep,mlkeep,dq_rel_yy,Gres,Gcomm)
    __IDABBDPrecInit(convert(IDAMemPtr,ida_mem),convert(Clong,Nlocal),convert(Clong,mudq),convert(Clong,mldq),convert(Clong,mukeep),convert(Clong,mlkeep),dq_rel_yy,Gres,Gcomm)
end

function __IDABBDPrecReInit(ida_mem::IDAMemPtr,mudq::Clong,mldq::Clong,dq_rel_yy::realtype)
    ccall((:IDABBDPrecReInit,libsundials_ida),Cint,(IDAMemPtr,Clong,Clong,realtype),ida_mem,mudq,mldq,dq_rel_yy)
end

function IDABBDPrecReInit(ida_mem,mudq,mldq,dq_rel_yy)
    __IDABBDPrecReInit(convert(IDAMemPtr,ida_mem),convert(Clong,mudq),convert(Clong,mldq),dq_rel_yy)
end

function __IDABBDPrecGetWorkSpace(ida_mem::IDAMemPtr,lenrwBBDP::Ptr{Clong},leniwBBDP::Ptr{Clong})
    ccall((:IDABBDPrecGetWorkSpace,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong},Ptr{Clong}),ida_mem,lenrwBBDP,leniwBBDP)
end

function IDABBDPrecGetWorkSpace(ida_mem,lenrwBBDP,leniwBBDP)
    __IDABBDPrecGetWorkSpace(convert(IDAMemPtr,ida_mem),pointer(lenrwBBDP),pointer(leniwBBDP))
end

function __IDABBDPrecGetNumGfnEvals(ida_mem::IDAMemPtr,ngevalsBBDP::Ptr{Clong})
    ccall((:IDABBDPrecGetNumGfnEvals,libsundials_ida),Cint,(IDAMemPtr,Ptr{Clong}),ida_mem,ngevalsBBDP)
end

function IDABBDPrecGetNumGfnEvals(ida_mem,ngevalsBBDP)
    __IDABBDPrecGetNumGfnEvals(convert(IDAMemPtr,ida_mem),pointer(ngevalsBBDP))
end
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_dense.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function __IDADense(ida_mem::IDAMemPtr,Neq::Clong)
    ccall((:IDADense,libsundials_ida),Cint,(IDAMemPtr,Clong),ida_mem,Neq)
end

function IDADense(ida_mem,Neq)
    __IDADense(convert(IDAMemPtr,ida_mem),convert(Clong,Neq))
end
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_impl.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_spbcgs.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function __IDASpbcg(ida_mem::IDAMemPtr,maxl::Cint)
    ccall((:IDASpbcg,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxl)
end

function IDASpbcg(ida_mem,maxl)
    __IDASpbcg(convert(IDAMemPtr,ida_mem),convert(Cint,maxl))
end
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_spgmr.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function __IDASpgmr(ida_mem::IDAMemPtr,maxl::Cint)
    ccall((:IDASpgmr,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxl)
end

function IDASpgmr(ida_mem,maxl)
    __IDASpgmr(convert(IDAMemPtr,ida_mem),convert(Cint,maxl))
end
# Julia wrapper for header: /home/astukalov/.julia/v0.5/Sundials/deps/usr/include/ida/ida_sptfqmr.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

function __IDASptfqmr(ida_mem::IDAMemPtr,maxl::Cint)
    ccall((:IDASptfqmr,libsundials_ida),Cint,(IDAMemPtr,Cint),ida_mem,maxl)
end

function IDASptfqmr(ida_mem,maxl)
    __IDASptfqmr(convert(IDAMemPtr,ida_mem),convert(Cint,maxl))
end

ext: jl


text:
testdirectory = dirname(@__FILE__)
cd(testdirectory)
files = readdir()
for file in files
    if file!="runtest.jl"
        include(joinpath(testdirectory, file))
    end
end

max_stars_repo_name: charlyalizadeh/OPFdecgen

max_issues_repo_name: charlyalizadeh/OPFdecgen

max_forks_repo_name: charlyalizadeh/OPFdecgen


text:
include("utils/main.jl")

server_start()

make_and_test_request_delete(["a" => "b"])
make_and_test_request_get(["a" => "b"])
make_and_test_request_options(["a" => "b"])
make_and_test_request_put(["a" => "b"], Dict("a" => 1), 7)
make_and_test_request_post(["a" => "b"], Dict("b" => 2), 7)

server_close()


text:
module ClassicAlgorithmsCollections

# Bit-Manipulation
include("BitManipulation/CountTotalBits.jl")
export count_total_bits
include("BitManipulation/GetSingleInteger.jl")
export get_single_integer
include("BitManipulation/Integer2Binary.jl")
export int2binary
include("BitManipulation/MagicNumber.jl")
export magic_number
include("BitManipulation/MaximumXorSubarray.jl")
export maximum_xor_subarray
include("BitManipulation/SumOfBitDifference.jl")
export sum_of_bit_difference
include("BitManipulation/SwappingBits.jl")
export swapping_even_odd_bits

# Dynamic-Programming
include("DynamicProgramming/KnackPackSolver.jl")
export knack_pack_solver
include("DynamicProgramming/LongestCommonSubsequence.jl")
export longest_common_subsequence
include("DynamicProgramming/LongestIncreasingSubsequence.jl")
export longest_increasing_subsequence
include("DynamicProgramming/MinimumOperations.jl")
export minimum_operations
include("DynamicProgramming/NumberOfSteps.jl")
export number_of_steps
include("DynamicProgramming/SubsetSumTest.jl")
export subset_sum_test

# Graph
include("Graph/BoogleWordCheck.jl")
export boogle_word_check
include("Graph/BreadthFirstSearch.jl")
export breadth_first_search
include("Graph/DepthFirstSearch.jl")
export depth_first_search
include("Graph/GraphBridgeCheck.jl")
export graph_bridge_check
include("Graph/GraphCycleCheck.jl")
export graph_cycle_check
include("Graph/MinimumSpanningTree.jl")
export minimum_spanning_tree
include("Graph/ShortestPathTree.jl")
export shortest_path_tree

# Number-Theory
include("NumberTheory/ChineseRemainderTheorem.jl")
export chinese_remainder_theorem
include("NumberTheory/EulerTotient.jl")
export euler_totient
include("NumberTheory/ModularExponentiation.jl")
export modular_exponentiation
include("NumberTheory/ModularInverse.jl")
export modular_inverse
include("NumberTheory/SieveOfEratosthenes.jl")
export sieve_of_eratosthenes

# Sorting and Searching
include("SortingAndSearching/BinaryPivotSearch.jl")
export binary_pivot_search
include("SortingAndSearching/BinarySearch.jl")
export binary_search
include("SortingAndSearching/BubbleSorting.jl")
export bubble_sorting
include("SortingAndSearching/ClosetPairSearch.jl")
export closet_pair_search
include("SortingAndSearching/HeapSorting.jl")
export heap_sorting
include("SortingAndSearching/InsertionSorting.jl")
export insertion_sorting
include("SortingAndSearching/InterpolationSearch.jl")
export interpolation_search
include("SortingAndSearching/MergeSorting.jl")
export merge_sorting
include("SortingAndSearching/QuickSorting.jl")
export quick_sorting

# String and Array
include("StringAndArray/CombinationsOf2Arrays.jl")
export combinations_of_2arrays
include("StringAndArray/CountPythagoreanElements.jl")
export count_pythagorean_elements
include("StringAndArray/CountTripletElements.jl")
export count_triplet_elements
include("StringAndArray/FindMaxLengthSubarray.jl")
export find_max_length_subarray
include("StringAndArray/FindSmallestNonelement.jl")
export find_smallest_nonelement
include("StringAndArray/ReversePureString.jl")
export reverse_pure_string
include("StringAndArray/SmallestSubset4Sum.jl")
export smallest_subset4_sum
include("StringAndArray/SumOfPositiveGradients.jl")
export sum_of_positive_gradients
include("StringAndArray/ZigZagOrdering.jl")
export zig_zag_ordering

end # module

max_stars_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_issues_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_forks_repo_name: Anselmoo/ClassicAlgorithmsCollections


text:
using BrainWave, Compat
## ### simulate data of an EEG recording
## sampRate = 256
## nSec = 120
## # 16 channels, 120 seconds
## rec = rand(16, sampRate*nSec)*150
## evt = repeat([1, 2], outer=[12])
## shuffle!(evt)
## startPoints = [257:256*5:256*119]
## evtTab = @compat Dict{String,Any}("code" => evt,
##                                   "idx" => startPoints)

sampRate = 256
rec, evtTab = simulateRecording(sampRate=256, minVolt=-85, maxVolt=85)

filterContinuous!(rec, sampRate, "bandpass", 512, [1, 30], transitionWidth=0.2)

epochStart = -0.2
epochEnd = 0.5
segs, nRaw = segment(rec, evtTab, epochStart, epochEnd,
                     sampRate, eventsList=[1, 2])

baselineCorrect!(segs, epochStart, abs(epochStart), sampRate)

thresh = 75
toRemoveDict = findArtefactThresh(segs, thresh)
removeEpochs!(segs, toRemoveDict)

ave, nSegs = averageEpochs(segs)


text:
"""

```
velocity_distribution(
  velfile::String,l
  vmax::Float64=10.,
  nbins::Int=10,
  T::DataType=Point2D
)
```

Computes the distribution of velocities. If `T=Point3D` the system will be read as three-dimensional.

"""
function velocity_distribution(
  sys::System{T},
  velfile::String;
  vmax::Float64=2.,
  nbins::Int=100
) where T

  # Initialize histogram
  @unpack n = sys
  Δv = vmax/nbins
  vvals = vmax*[ (i-1/2)*Δv for i in 1:nbins ]
  vcount = zeros(nbins)
  vavg = zero(T)
  vavg_norm = 0.
  kavg = 0.

  # Reading velocities, computing distances, and adding to histogram
  nframes = 0
  open(velfile) do file
    while !(eof(file))
      readline(file) # number of atoms, ignore
      readline(file) # title, ignore
      nframes += 1
      # read atomic coordinates
      for i in 1:n
        atom_data = split(readline(file))
        v = T(ntuple(i -> parse(Float64,atom_data[i+1]), dim(T)))
        ibin = floor(Int,(norm(v)/vmax)/Δv) + 1
        if ibin <= nbins
          vcount[ibin] += 1
        end
        vavg += v
        vavg_norm += norm(v)
        kavg += norm2(v)/2
      end
    end
  end
  println("Number of frames read = ", nframes)

  # Normalizing by the number of frames and number of atoms
  for i in 1:nbins
    vcount[i] = vcount[i] / (nframes*n*Δv)
  end
  vavg = vavg / (nframes*n)
  println(" Average velocity = ", vavg)
  println(" Average velocity norm = ", vavg_norm/(nframes*n))
  println(" Average kinetic energy = ", kavg/(nframes*n))

  return vvals, vcount
end


text:
###########Underlying Types
#Abstract
abstract type AbstractUnderlying end

#Scalar dividend
mutable struct UnderlyingScalar{num <: Number, num2 <: Number} <: AbstractUnderlying
    S0::num
    d::num2
    function UnderlyingScalar(S0::num_, d::num_2 = 0.0) where {num_ <: Number, num_2 <: Number}
        if (S0 < zero(num_))
            error("Underlying starting value must be positive")
        else
            return new{num_, num_2}(S0, d)
        end
    end
end
#Curve dividend
mutable struct UnderlyingVec{num <: Number, num2 <: Number, num3 <: Number} <: AbstractUnderlying
    S0::num
    d::Curve{num2, num3}
    function UnderlyingVec(S0::num_, d::Curve{num2, num3}) where {num_ <: Number, num2 <: Number, num3 <: Number}
        if (S0 < zero(num_))
            error("Underlying starting value must be positive")
        else
            return new{num_, num2, num3}(S0, d)
        end
    end
end

#Common Constructors
function Underlying(S0::num_, d::Curve{num2, num3}) where {num_ <: Number, num2 <: Number, num3 <: Number}
    return UnderlyingVec(S0, d)
end
function Underlying(S0::num_, d::num_2 = 0.0) where {num_ <: Number, num_2 <: Number}
    return UnderlyingScalar(S0, d)
end

export Underlying;


text:
# light transport, e.g. reflection, refraction

"""Compute reflection vector for v (pointing to surface) and normal n⃗.

	See [diagram](https://raytracing.github.io/books/RayTracingInOneWeekend.html#metal/mirroredlightreflection)"""
@inline @fastmath reflect(v::Vec3{T}, n⃗::Vec3{T}) where T = v - (2v⋅n⃗)*n⃗

"""
	Args:
		refraction_ratio: incident refraction index divided by refraction index of
			hit surface. i.e. η/η′ in the figure above"""
@inline @fastmath function refract(dir::Vec3{T}, n⃗::Vec3{T}, refraction_ratio::T) where T
	cosθ = min(-dir ⋅ n⃗, one(T))
	r_out_perp = refraction_ratio * (dir + cosθ*n⃗)
	r_out_parallel = -√(abs(one(T)-squared_length(r_out_perp))) * n⃗
	normalize(r_out_perp + r_out_parallel)
end

@inline @fastmath function reflectance(cosθ, refraction_ratio)
	# Use Schlick's approximation for reflectance.
	# claforte: may be buggy? I'm getting black pixels in the Hollow Glass Sphere...
	r0 = (1-refraction_ratio) / (1+refraction_ratio)
	r0 = r0^2
	r0 + (1-r0)*((1-cosθ)^5)
end


text:
module BioMASS

using Printf
using LinearAlgebra
using StatsBase
using Statistics
using DelimitedFiles

export Model,
    optimize,
    optimize_continue,
    param2biomass,
    run_simulation,
    create_diffeq,
    new_curve!,
    get_bistable_regime

const requirements = [
    joinpath("name2idx", "parameters.jl"),
    joinpath("name2idx", "species.jl"),
    "set_model.jl",
    "observable.jl",
    "simulation.jl",
    "experimental_data.jl",
    "set_search_param.jl",
    "fitness.jl",
]

struct Model
    path::String
    parameters::Module
    species::Module
    observables::Vector{String}
    sim::Module
    exp::Module
    obj_func::Function
    cond2idx::Function
    search_idx::Function
    search_region::Function
    update_param::Function
    gene2val::Function
    val2gene::Function
    bestIndivVal2randGene::Function
end
function Model(model_path::String, show_info::Bool=false)
    for req in requirements
        include(joinpath(model_path, req))
    end
    if show_info
        print(
            "Model information\n"
            * "-----------------\n"
            * @sprintf(
                "%d species\n%d parameters, of which %d to be estimated",
                length(V.NAMES), length(C.NAMES), length(get_search_index()[1])
            )
        )
    end
    Model(
        model_path,
        C,
        V,
        observables,
        Sim,
        Exp,
        objective,
        conditions_index,
        get_search_index,
        get_search_region,
        update_param,
        decode_gene2val,
        encode_val2gene,
        encode_bestIndivVal2randGene,
    )
end

function isinstalled(pymodule::String)::Bool
    try
        pyimport(pymodule)
        return true
    catch
        return false
    end
end

include("convert.jl")
include("optimize.jl")
include("estimation/initial_population.jl")
include("estimation/converging.jl")
include("estimation/local_search.jl")
include("estimation/ga.jl")
if isinstalled("matplotlib")
    include("visualize.jl")
else
    function visualize(model::Model; kwargs...)
        error(
            "The Python package matplotlib could not be imported by pyimport.\n"
            * "Usually this means that you did not install matplotlib in the "
            * "Python version being used by PyCall."
        )
    end
end
include("continuation.jl")
end # module


text:
import Automa
import Automa.RegExp: @re_str
const re = Automa.RegExp

sp = re" "
tab = re"\t"
lf = re"\n"
num = re.cat(re.rep1(re"[ \t]"), "\n")
label = num

actions = Automa.compile(
    re.cat("  ", num)       => :(num(:push, 2)),
    re" \n "                => :(emit(:dup)),
    re.cat(" \t ", num)     => :(num(:copy, 3)),
    re" \n\t"               => :(emit(:swap)),
    re" \n\n"               => :(emit(:discard)),
    re.cat(" \t\n", num)    => :(num(:slide, 3)),
    re"\t   "               => :(emit(:add)),
    re"\t  \t"              => :(emit(:sub)),
    re"\t  \n"              => :(emit(:mul)),
    re"\t \t "              => :(emit(:div)),
    re"\t \t\t"             => :(emit(:mod)),
    re"\t\t "               => :(emit(:heap_write)),
    re"\t\t\t"              => :(emit(:heap_read)),
    re.cat("\n  ", label)   => :(label(:label, 3)),
    re.cat("\n \t", label)  => :(label(:call, 3)),
    re.cat("\n \n", label)  => :(label(:jump, 3)),
    re.cat("\n\t ", label)  => :(label(:jump_zero, 3)),
    re.cat("\n\t\t", label) => :(label(:jump_nega, 3)),
    re"\n\t\n"              => :(emit(:return)),
    re"\n\n\n"              => :(emit(:exit)),
    re"\t\n  "              => :(emit(:char_out)),
    re"\t\n \t"             => :(emit(:num_out)),
    re"\t\n\t "             => :(emit(:char_in)),
    re"\t\n\t\t"            => :(emit(:num_in))
)

context = Automa.CodeGenContext()

@eval function tokenize(data)
    $(Automa.generate_init_code(context, actions))
    p_end = p_eof = sizeof(data)
    tokens = Tuple{Symbol,String}[]

    emit(kind) = push!(tokens, (kind, data[ts:te]))

    # name, l: symbol of operation, length of matched string
    function num(name, l)
        push!(tokens, (name, data[ts:ts+l-1]))
        str = data[ts+l:te-1]
        str = replace(str, r"\A\t" => "-")
        str = replace(str, r"\A " => "+")
        str = replace(str, r" " => "0")
        str = replace(str, r"\t" => "1")
        push!(tokens, (:num, string(parse(Int, str, base=2))))
    end

    function label(name, l)
        push!(tokens, (name, data[ts:ts+l-1]))
        push!(tokens, (:label_name, data[ts+l:te-1]))
    end

    while p ≤ p_eof && cs > 0
        $(Automa.generate_exec_code(context, actions))
    end
    if cs < 0
        error("failed to tokenize")
    end
    return tokens
end


text:
function main(β, γ, μ, n)
    @grounding begin
        S => Noun(person)
        I => Noun(patient)
        J => Noun(patient)
        R => Noun(person)
        λ₁ => Verb(h3n2)
        λ₄ => Verb(ebola)
        λ₅ => Verb(treatment)
        λ₂ => Verb(treatment)
        λ₃ => Verb(loss_of_immunity)
    end

    @reaction begin
        λ₁, S + I -> 2I
        λ₄, S + J -> 2J
        λ₅, J -> R
        λ₂, I -> R
        λ₃, R -> S
    end, λ₁, λ₂, λ₃, λ₄, λ₅

    # β, 1S + 1I -> 0S + 2I
    # γ, 0R + 1I -> 0I + 1R
    # μ, 1R + 0S -> 1S + 0R

    Δ = [
        (S,I) -> (S-1, I+1),
        (S,J) -> (S-1, J+1),
        (J,R) -> (J-1, R+1),
        (I,R) -> (I-1, R+1),
        (R,S) -> (R-1, S+1),
    ]

    ϕ = [
        (S, I) -> S > 0 && I > 0,
        (S, J) -> S > 0 && J > 0,
        (J) -> J > 0,
        (I) -> I > 0,
        (R) -> R > 0,
    ]

    Λ = [
        λ₁(S,I) = begin β*S*I/n end,
        λ₄(S,J) = begin β*S*J/n end,
        λ₅(J) = begin γ*J end,
        λ₂(I) = begin γ*I end,
        λ₃(R) = begin μ*R end
    ]
    m = Petri.Model(g, Δ, ϕ, Λ)
    d = convert(ODEProblem, m)
    soln = solve(m) #discrete
    soln = solve(d) #continuos
end

max_stars_repo_name: uncharted-aske/AMIDOL

max_issues_repo_name: uncharted-aske/AMIDOL

max_forks_repo_name: uncharted-aske/AMIDOL


text:
@testset "ZonedDateTime plot recipe" begin
    # Note: in these tests we use `RecipesBase.apply_recipe` rather than `plot` as it
    # lets use avoid a Plots.jl dependency and issues with running that during tests.
    # `RecipesBase.apply_recipe` is not a documented API, but is fairly usable.
    # Comments above each use show the matching `plot` function command
    start_zdt = ZonedDateTime(2017,1,1,0,0,0, tz"EST")
    end_zdt = ZonedDateTime(2017,1,1,10,30,0, tz"EST")
    zoned_dates = start_zdt:Hour(1):end_zdt

    # what the point should be after recipe is applied
    expected_dates = DateTime.(zoned_dates)

    @testset "No label (should now say the Timezone)" begin
        # The below use of `apply_recipe` is equivelent to:
        # plot(zoned_dates, 1:11)
        result, = RecipesBase.apply_recipe(Dict{Symbol, Any}(), zoned_dates, 1:11)
        xs, ys = result.args
        @test xs == expected_dates
        @test ys == 1:11
        @test result.plotattributes[:xguide] == "Time zone: EST"
    end

    @testset "label (should append to it)" begin
        # The below use of `apply_recipe` is equivelent to:
        # plot(zoned_dates, 1:11; xguide="X-Axis")
        result, = RecipesBase.apply_recipe(Dict{Symbol, Any}(:xguide=>"X-Axis"), zoned_dates, 1:11)
        xs, ys = result.args
        @test xs == expected_dates
        @test ys == 1:11
        @test result.plotattributes[:xguide] == "X-Axis (EST)"
    end

    @testset "No items" begin
        empty_xs = ZonedDateTime[]
        empty_ys = 0:-1
        result, = RecipesBase.apply_recipe(
           Dict{Symbol, Any}(:xguide=>"X-Axis"), empty_xs, empty_ys
        )
        xs, ys = result.args
        @test isempty(xs)  # not nesc same type
        @test ys == empty_ys

        @test result.plotattributes[:xguide] == "X-Axis"  # no change to axis
    end
end


text:
module SfRelativity

using PhysicalConstants.CODATA2018: c_0, g_n, G
using Unitful
using UnitfulAstro

using ..SfUnits

import ..SfPhysics: kinetic_energy

export lorentz_factor, lorentz_velocity, relativistic_kinetic_energy, relativistic_brachistochrone_transit_time,
	proper_relativistic_brachistochrone_transit_time, relativistic_velocity, relativistic_delta_v

"""
	lorentz_factor(v::Unitful.Velocity)

Compute the Lorentz factor associated with the given velocity.

Note that for small values of `v` floating point precision issues can produce substantial
inaccuracies unless velocities are specified as `BigInt` or `BigFloat`.
"""
lorentz_factor(v::Unitful.Velocity) = 1/sqrt(1-(v/c_0)^2) |> u"m/m"
lorentz_factor(t::Unitful.Time, acc::Unitful.Acceleration) = sqrt(1 + (acc*t/c_0)^2) |> u"m/m"
lorentz_factor(d::Unitful.Length, acc::Unitful.Acceleration) = 1 + (acc * d)/c_0^2 |> u"m/m"

lorentz_velocity(γ) = sqrt(1 - (1/γ)^2) * c_0 |> u"c"

"""
	relativistic_kinetic_energy(m::Unitful.Mass, v::Unitful.Velocity)

Compute the kinetic energy of a body with mass `m` travelling at velocity `v`.

Relativistic corrections are included. Note that for small values of `v` floating point precision issues
can produce substantial inaccuracies unless velocities are specified as `BigInt` or `BigFloat`.
"""
relativistic_kinetic_energy(m::SfUnits.Mass, v::Unitful.Velocity) = (m * big(c_0)^2)* (lorentz_factor(v) - 1) |> u"J"

"""
	relativistic_velocity(m::SfUnits.Mass, ke::Unitful.Energy)

Velocity of a particle of mass `m` with kinetic energy `ke`, accounting for relativity.
"""
function relativistic_velocity(m::SfUnits.Mass, ke::Unitful.Energy)
	x = 1 + ke / (m * c_0^2)
	return sqrt(c_0^2 - c_0^2 / x^2)
end

function relativistic_brachistochrone_transit_time(dist::Unitful.Length, acc::Unitful.Acceleration)
	hd = dist/2

	2 * sqrt((hd/c_0)^2 + (2 * hd / acc))
end

function proper_relativistic_brachistochrone_transit_time(d::Unitful.Length, acc::Unitful.Acceleration)
	hd = d/2

	2 * (c_0 / acc) * acosh(((acc * hd) / c_0^2) + 1)
end

"""
    relativistic_velocity(t::Unitful.Time, acc::Unitful.Acceleration)

Velocity attained by a body undergoing constant acceleration `acc` for time `t`, accounting for relativistic effects.
"""
relativistic_velocity(t::Unitful.Time, acc::Unitful.Acceleration) = (acc*t)/sqrt(1+((acc*t)/c_0)^2|>u"s/s") |>u"m/s"

"""
    relativistic_delta_v(ve::Unitful.Velocity, mr)

Delta-V of a rocket with exhaust velocity `ve` and mass ration `mr` accounting for relativistic effects.
"""
relativistic_delta_v(ve::Unitful.Velocity, mr) = c_0 * tanh((ve/c_0) * log(mr)) |>u"m/s"

end

max_stars_repo_name: icantbelieveitsnotphysics/SfPhysics

max_issues_repo_name: icantbelieveitsnotphysics/SfPhysics

max_forks_repo_name: icantbelieveitsnotphysics/SfPhysics


text:
using NEAT
using Test

#reload("NEAT")
include("config_tests.jl")
include("genome_tests.jl")
include("chromosome_test.jl")
include("species_test.jl")
include("population_test.jl")
include("nn_tests.jl")
include("XOR_test.jl")


text:
import PWS: collect_trajectory, Thin, MergeWith, sub_trajectory, merge_trajectories
using Test
using StaticArrays

num_samples = 10000
rand_u = [rand([0, 1], 2) for i = 1:num_samples]
rand_t = cumsum(-log.(rand(num_samples)))
rand_i = collect(1:num_samples)
iter = zip(rand_u, rand_t, rand_i)
all_events = collect(iter)

thinned_events = all_events |> Thin() |> collect

for event in thinned_events
    @test event ∈ all_events
end

for (index, (u, t, i)) in enumerate(all_events)
    if index == 1
        continue
    end
    (uprev, tprev, iprev) = all_events[index - 1]
    du = u - uprev
    if all(du .== 0)
        @test tprev ∉ getindex.(thinned_events, 2)
    else
        @test (uprev, tprev, iprev) ∈ thinned_events
    end
end

for i in 1:length(thinned_events) - 2
    @test thinned_events[i][1] != thinned_events[i + 1][1]
end

@test thinned_events[end][1:2] == all_events[end][1:2]

sub1 = sub_trajectory(iter, [1])
sub2 = sub_trajectory(iter, [2])
merg = sub1 |> MergeWith(sub2) |> collect

@test merg == thinned_events

sub1_trim  = collect(sub_trajectory(iter, [1]))[100:110] |> collect_trajectory
a = sub1_trim |> MergeWith(sub2) |> collect
b = sub2 |> MergeWith(sub1_trim) |> collect

@test getindex.(a, 2) == getindex.(b, 2)
for (a, b) in zip(a, b)
    @test a[1][[1,2]]==b[1][[2,1]]
end


text:
using ChainRulesCore, LinearAlgebra

function ChainRulesCore.rrule(::Type{<:TransmutedDimsArray{T,N,P,Q,AT}}, A::AbstractArray) where {T,N,P,Q,AT}
    B = TransmutedDimsArray{T,N,P,Q,AT}(A)
    function transmute_back(Δ::AbstractArray)
        if unique_or_zero(Val(P))
            (ZeroTangent(), transmute(Δ, Q), ZeroTangent())
        else
            (ZeroTangent(), _undiagonal(Δ, P, Q), ZeroTangent())
        end
    end
    function transmute_back(Δ::Tangent)
        (ZeroTangent(), Δ.parent, ZeroTangent())
    end
    B, transmute_back
end

function _undiagonal(Δ::AbstractArray, P::NTuple{N,Int}, Q::NTuple{M,Int}) where {M,N}
    if P == (1,1) && Q == (2,) && ndims(Δ) == 2
        return Δ[LinearAlgebra.diagind(Δ)]
    end
    axe = map(Q) do q
        q == 0 ? Base.OneTo(1) : axes(Δ,q)
    end
    for d in 1:N
        if P[d] == 0
            size(Δ,d) == 1 || throw(DimensionMismatch(
                "expected size(Δ,$d) == 1, got size(Δ) = $(size(Δ)). P = $P, Q = $Q"))
        else
            axes(Δ,d) == axe[P[d]] || throw(DimensionMismatch(
                "expected axes(Δ,$d) == $(axe[P[d]]), got $(axes(Δ,d)). P = $P, Q = $Q"))
        end
    end
    out = fill!(similar(Δ, axe), 0)
    @inbounds for I in CartesianIndices(axe)
        J = CartesianIndex(map(p -> I[p], P))
        out[I] = Δ[J]
    end
    out
end


text:
function getPlot_accuracy(train_data)
    the_plot = plot(treino.accuracy,
             label="Accuracy",
             xlabel="Epochs",
             ylabel="Accuracy as %",
             title="Development of accuracy at each iteration");
    return the_plot
end

function getPlot_cost(train_data)
    the_plot = plot(treino.costs,
             label="Cost Function",
             xlabel="Epochs",
             ylabel="Cost",
             color="red",
             title="Development of cost at each iteration");
    return the_plot
end

function plot_nn(train_data)
    Plots.plot(getPlot_accuracy(train_data), getPlot_cost(train_data), layout = (2, 1), size = (800, 600))
end


text:
#==============================================================================#
# AWSLambda.jl
#
# AWS Lambda API.
#
# See http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html
#
# Copyright Sam O'Connor 2014 - All rights reserved
#==============================================================================#

__precompile__()

module AWSLambda

export list_lambdas, create_lambda, update_lambda, delete_lambda, invoke_lambda,
       async_lambda, create_jl_lambda, invoke_jl_lambda, create_lambda_role,
       @λ, @lambda, serialize64, deserialize64,
       lambda_compilecache,
       create_jl_lambda_base, merge_lambda_zip,
       lambda_configuration,
       lambda_create_alias, lambda_update_alias, lambda_publish_version,
       apigateway, apigateway_restapis, apigateway_create,
       @lambda_eval, @lambda_call, lambda_include, lambda_include_string

using AWSCore
using AWSS3
using AWSEC2
using AWSIAM
using JSON
using InfoZIP
using Retry
using SymDict
using DataStructures
using Glob
using Base.Pkg

import Nettle: hexdigest

# For compatibility with Julia 0.4
using Compat.readstring
using Compat.read

#-------------------------------------------------------------------------------
# AWS Lambda REST API.
#-------------------------------------------------------------------------------

function lambda(aws::SymbolDict, verb; path="", query="", headers = Dict())

    resource = "/2015-03-31/functions/$path"

    r = @SymDict(
        service  = "lambda",
        url      = aws_endpoint("lambda", aws[:region]) * resource,
        content  = query == "" ? "" : json(query),
        headers,
        resource,
        verb,
        aws...
    )

    r = do_request(r)

    if isa(r, Dict)
        r = SymbolDict(r)
    end

    return r
end

list_lambdas(aws) = [SymbolDict(f) for f in lambda(aws, "GET")[:Functions]]

function lambda_configuration(aws, name)

    @protected try

        return lambda(aws, "GET", path="$name/configuration")

    catch e
        @ignore if e.code == "404" end
    end

    return nothing
end

function lambda_update_configuration(aws, name, options)

    lambda(aws, "PUT", path="$name/configuration", query=options)
end

lambda_exists(aws, name) = lambda_configuration(aws, name) != nothing

function create_lambda(aws, name, S3Key;
                       S3Bucket=aws[:lambda_bucket],
                       Handler="$name.main",
                       Role=create_lambda_role(aws, name),
                       Runtime="python2.7",
                       Timeout=300,
                       args...)

   query = @SymDict(FunctionName = name,
                    Code = @SymDict(S3Key, S3Bucket),
                    Handler,
                    Role,
                    Runtime,
                    Timeout,
                    args...)

    @repeat 5 try

        lambda(aws, "POST", query=query)

    catch e
        # Retry in case Role was just created and is not yet active...
        @delay_retry if e.code == "400" end
    end
end

function update_lambda(aws, name, S3Key;
                       S3Bucket=aws[:lambda_bucket], args...)

    @sync begin

        @async lambda(aws, "PUT", path="$name/code",
                      query=@SymDict(S3Key, S3Bucket))

        @async if !isempty(args)
            lambda(aws, "PUT", path="$name/configuration", query=@SymDict(args...))
        end
    end
end

function lambda_publish_version(aws, name, alias)

    r = lambda(aws, "POST", path="$name/versions")
    @protected try
        lambda_create_alias(aws, name, alias, FunctionVersion=r[:Version])
    catch e
        @ignore if e.code == "409"
            lambda_update_alias(aws, name, alias, FunctionVersion=r[:Version])
        end
    end
end

function lambda_create_alias(aws, name, alias; FunctionVersion="\$LATEST")

    lambda(aws, "POST", path="$name/aliases",
                        query=@SymDict(FunctionVersion, Name=alias))
end

function lambda_update_alias(aws, name, alias; FunctionVersion="\$LATEST")

    lambda(aws, "PUT", path="$name/aliases/$alias",
                       query=@SymDict(FunctionVersion))
end

function delete_lambda(aws, name)

    @protected try
        lambda(aws, "DELETE", path=name)
    catch e
        @ignore if e.code == "404" end
    end
end

export AWSLambdaException

type AWSLambdaException <: Exception
    name::AbstractString
    message::AbstractString
end

function Base.show(io::IO, e::AWSLambdaException)

    println(io, string("AWSLambdaException \"", e.name, "\":\n", e.message, "\n"))
end

function invoke_lambda(aws, name, args; async=false)

    @protected try

        r = lambda(aws, "POST",
                        path="$name/invocations",
                        headers=Dict("X-Amz-Invocation-Type" =>
                                     async ? "Event" : "RequestResponse"),
                        query=args)

        if isa(r, Dict) && haskey(r, :errorMessage)
            throw(AWSLambdaException(string(name), r[:errorMessage]))
        end

        return r

    catch e
        @ignore if e.code == "429"
            message = "HTTP 429 $(e.message)\nSee " *
                      "http://docs.aws.amazon.com/lambda/latest/dg/limits.html"
            throw(AWSLambdaException(string(name), message))
        end
    end

    @assert false # Unreachable
end

invoke_lambda(aws, name; args...) = invoke_lambda(aws, name, SymbolDict(args))

async_lambda(aws, name, args) = invoke_lambda(aws, name, args; async=true)

function create_lambda_role(aws, name, policy="")

    name = "$(name)_lambda_role"

    @protected try

        r = AWSIAM.iam(aws, Action = "CreateRole",
                        Path = "/",
                        RoleName = name,
                        AssumeRolePolicyDocument = """{
                            "Version": "2012-10-17",
                            "Statement": [ {
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": "lambda.amazonaws.com"
                                },
                                "Action": "sts:AssumeRole"
                            } ]
                        }""")

    catch e
        @ignore if e.code == "EntityAlreadyExists" end
    end

    if policy == ""
        policy = """{
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "logs:CreateLogGroup",
                        "logs:CreateLogStream",
                        "logs:PutLogEvents"
                    ],
                    "Resource": "arn:aws:logs:*:*:*"
                }
            ]
        }"""
    end

    AWSIAM.iam(aws, Action = "PutRolePolicy",
                    RoleName = name,
                    PolicyName = name,
                    PolicyDocument = policy)

    return role_arn(aws, name)
end

#-------------------------------------------------------------------------------
# Python Code Support.
#-------------------------------------------------------------------------------

function create_py_lambda(aws, name, py_code;
                          Role=create_lambda_role(aws, name))

    delete_lambda(aws, name)

    # Create .ZIP file containing "py_code"...
    zip = create_zip("$name.py" => py_code)

    # Upload .ZIP file to S3...
    zip_filename = "ocaws_lambda_$name.zip"
    s3_put(aws, aws[:lambda_bucket], zip_filename, zip)

    # Create lambda...
    create_lambda(aws, name, zip_filename, Role=Role, MemorySize=1024)
end

#-------------------------------------------------------------------------------
# S3 ZIP File Patching.
#-------------------------------------------------------------------------------

# Add "files" to .ZIP stored under "from_key" in "aws[:lambda_bucket]".
# Store result under "to_key".
# Implemented using Python zipfile library running on AWS Lambda
# (to avoid downloading/uploading .ZIP to/from local machine).

function create_lambda_zip(aws, to_key, from_key, files::Associative)

    bucket = aws[:lambda_bucket]
    lambda_name = "ocaws_create_lambda_zip"

#    delete_lambda(aws, lambda_name)

    files = [n => base64encode(v) for (n,v) in files]

    @repeat 2 try

        # Call lambda function to update ZIP stored in S3...
        invoke_lambda(aws, lambda_name,
                      @SymDict(bucket, to_key, from_key, files))

    catch e

        # Deploy create_lambda_zip lambda function if needed...
        @retry if e.code == "404"

            role_name = string(lambda_name, '-', aws[:region])

            create_py_lambda(aws, lambda_name,
            """
            import boto3
            import botocore
            import zipfile

            def main(event, context):

                # Get bucket object...
                bucket = event['bucket']
                region = boto3.client('s3').get_bucket_location(Bucket=bucket)
                region = region['LocationConstraint']
                bucket = boto3.resource('s3', region_name = region).Bucket(bucket)

                # Download zip file...
                bucket.download_file(event['from_key'], '/tmp/lambda.zip')

                # Patch zip file...
                with zipfile.ZipFile('/tmp/lambda.zip', 'a') as z:
                    for file in event['files']:
                        info = zipfile.ZipInfo(file)
                        info.compress_type = zipfile.ZIP_DEFLATED
                        info.external_attr = 0777 << 16L
                        z.writestr(info, event['files'][file].decode('base64'))

                # Upload updated zip file...
                bucket.upload_file('/tmp/lambda.zip', event['to_key'])
            """;
            Role = create_lambda_role(aws, role_name, """{
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": [
                            "s3:GetObject",
                            "s3:PutObject",
                            "s3:GetBucketLocation"
                        ],
                        "Resource": "arn:aws:s3:::$bucket*"
                    },
                    {
                        "Effect": "Allow",
                        "Action": [
                            "logs:CreateLogGroup",
                            "logs:CreateLogStream",
                            "logs:PutLogEvents"
                        ],
                        "Resource": "arn:aws:logs:*:*:*"
                    }
                ]
            }"""))
        end
    end
end

function merge_lambda_zip(aws, to_key, from_key, new_keys)

    lambda_name = "ocaws_merge_lambda_zip"
    bucket = aws[:lambda_bucket]
#    delete_lambda(aws, lambda_name)

    @repeat 2 try

        # Call lambda function to update ZIP stored in S3...
        invoke_lambda(aws, lambda_name,
                           @SymDict(bucket, to_key, from_key, new_keys))

    catch e

        # Deploy merge_lambda_zip lambda function if needed...
        @retry if e.code == "404"

            role_name = string(lambda_name, '-', aws[:region])

            create_py_lambda(aws, lambda_name,
            """
            import os
            import tempfile
            import zipfile
            import shutil
            import subprocess
            import boto3
            import botocore

            def main(event, context):

                # Create temporary working directory...
                tmpdir = tempfile.mkdtemp()
                os.chdir(tmpdir)

                # Get bucket object...
                bucket = event['bucket']
                region = boto3.client('s3').get_bucket_location(Bucket=bucket)
                region = region['LocationConstraint']
                bucket = boto3.resource('s3', region_name = region).Bucket(bucket)

                # Download base zip file...
                bucket.download_file(event['from_key'], 'base.zip')

                # Download new zip file and merge into base zip file...
                with zipfile.ZipFile('base.zip', 'a') as za:
                    for key in event['new_keys']:
                        bucket.download_file(key, 'new.zip')
                        with zipfile.ZipFile('new.zip', 'r') as zb:
                            for i in zb.infolist():
                                za.writestr(i, zb.open(i.filename).read())

                # Upload new zip file...
                bucket.upload_file('base.zip', event['to_key'])
                os.chdir("..")
                shutil.rmtree(tmpdir)
            """,
            Role = create_lambda_role(aws, role_name, """{
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": [
                            "s3:GetObject",
                            "s3:PutObject",
                            "s3:GetBucketLocation"
                        ],
                        "Resource": "arn:aws:s3:::$bucket*"
                    },
                    {
                        "Effect": "Allow",
                        "Action": [
                            "logs:CreateLogGroup",
                            "logs:CreateLogStream",
                            "logs:PutLogEvents"
                        ],
                        "Resource": "arn:aws:logs:*:*:*"
                    }
                ]
            }"""))
        end
    end
end

#-------------------------------------------------------------------------------
# Julia Code Support.
#-------------------------------------------------------------------------------

# Create an AWS Lambda to run "jl_code".
# The Julia runtime is copied from "aws[:lambda_bucket]/jl_lambda_base.zip".
# "jl_code" is added to the .ZIP as "$name.jl".
# A Python wrapper ("$name.py") is passes the .jl file to bin/julia.

function create_jl_lambda(aws, name, jl_code,
                          modules=Symbol[], options=SymDict())

    # Find files and load path for required modules...
    load_path, mod_files = module_files(aws, modules)
    py_load_path = "[$(join(["'$d'" for d in load_path], ","))]"

    env = get(options, :env,
          get(aws, :lambda_env, Dict()))
    py_env = join(["os.environ['$n'] = '$v'" for (n,v) in env], "\n")

    error_sns_arn = get(options, :error_sns_arn,
                    get(aws, :lambda_error_sns_arn, ""))

    # Wrapper to set up Julia environemnt and run "jl_code"...
    const lambda_py_wrapper =
    """
    from __future__ import print_function
    import subprocess
    import os
    import json
    import threading
    import time
    import select

    # Set Julia package directory...
    root = os.environ['LAMBDA_TASK_ROOT']
    os.environ['HOME'] = '/tmp/'
    os.environ['JULIA_PKGDIR'] = root + '/julia'
    load_path = ':'.join([root + '/' + d for d in $py_load_path])
    os.environ['JULIA_LOAD_PATH'] = load_path
    $py_env

    julia_proc = None

    # Start Julia interpreter ...
    def start_julia():
        global julia_proc
        julia_proc = subprocess.Popen([root + '/bin/julia', root + "/$name.jl"],
                                      stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.STDOUT)

    # Pass args to Julia as JSON with null,newline terminator...
    def julia_eval(event, context):
        json.dump({'event': event, 'context': context.__dict__},
                  julia_proc.stdin,
                  default=lambda o: '')
        julia_proc.stdin.write('\\0\\n')
        julia_proc.stdin.flush()

    def main(event, context):

        # Clean up old return value file...
        if os.path.isfile('/tmp/lambda_out'):
            os.remove('/tmp/lambda_out')

        if julia_proc is None or julia_proc.poll() is not None:
            start_julia()

        # Pass "event" to Julia...
        threading.Thread(target=julia_eval, args=(event, context)).start()

        # Calcualte execution time limit...
        time_limit = time.time() + context.get_remaining_time_in_millis()/1000.0
        time_limit -= 5.0

        # Wait for output...
        out = ''
        timeout = True
        while time.time() < time_limit:
            ready = select.select([julia_proc.stdout], [], [], time_limit - time.time())
            if julia_proc.stdout in ready[0]:
                line = julia_proc.stdout.readline()
                if line == '\\0\\n' or line == '':
                    timeout = False
                    break
                print(line, end='')
                out += line

        if timeout:
            print('Timeout!')
            out += 'Timeout!\\n'

        # Check exit status...
        if julia_proc.poll() != None or timeout:
            if '$error_sns_arn' != '':
                if timeout:
                    subject = 'Lambda Timeout: $name '
                else:
                    subject = 'Lambda Error: $name '
                subject += json.dumps(event, separators=(',',':'))
                error = '$name\\n' + json.dumps(event) + '\\n\\n' + out
                import boto3
                try:
                    boto3.client('sns').publish(TopicArn='$error_sns_arn',
                                                Message=error,
                                                Subject=subject[:100])
                except Exception:
                    pass

            raise Exception(out)

        # Return content of output file...
        if os.path.isfile('/tmp/lambda_out'):
            with open('/tmp/lambda_out', 'r') as f:
                return {'jl_data': f.read(), 'stdout': out}
        else:
            return {'stdout': out}
    """

    # Start with zipfile from options...
    zipfile = get(options, :zipfile, UInt8[])
    delete!(options, :zipfile)

    # Add lambda source and module files to zip...
    open_zip(zipfile) do z
        merge!(z, mod_files)
        merge!(z, OrderedDict("$name.py" => lambda_py_wrapper,
                              "$name.jl" => jl_code))
    end

    # SHA256 Hash of deployed Julia code is stored in the Description field.
    old_config = lambda_configuration(aws, name)
    new_code_hash = hexdigest("sha256", serialize64(Dict(open_zip(zipfile))))
    old_code_hash = get(old_config, :Description, nothing)

    # Don't create a new lambda if one already exists with same code...
    if new_code_hash == old_code_hash && !get(aws, :lambda_force_update, false)
        return
    end

    # Add new files to base Julia system .ZIP file...
    base_file=get(aws, :lambda_base, "jl_lambda_base.zip")
    lambda_id="jl_lambda_$(name)_$(new_code_hash)"
    s3_put(aws, aws[:lambda_bucket], "$lambda_id.new.zip", zipfile)
    merge_lambda_zip(aws, "$lambda_id.zip", base_file, ["$lambda_id.new.zip"])

    options = @SymDict(MemorySize=1024,
                       Description=new_code_hash,
                       options...)

    # Deploy the lambda to AWS...
    if old_config == nothing
        r = create_lambda(aws, name, "$lambda_id.zip"; options...)
    else
        r = update_lambda(aws, name, "$lambda_id.zip"; options...)
    end

    if get(aws, :lambda_precompile, true)

        # Download .ji cache from the lambda sandbox.
        r = invoke_lambda(aws, name, jl_precompile = true)
        ji_cache = deserialize64(r[:jl_data])

        if !isempty(ji_cache)

            # Add .ji cache files to .ZIP...
            create_lambda_zip(aws, "$lambda_id.ji.zip",
                              "$lambda_id.zip", ji_cache)

            # Update lambda using new .ZIP...
            update_lambda(aws, name, "$lambda_id.ji.zip")
        end
    end

    @sync begin

        # Update config...
        @async lambda_update_configuration(aws, name, options)

        # Clean up S3 files...
        for z in [".new.zip", ".zip", ".ji.zip"]
            @async s3_delete(aws, aws[:lambda_bucket], "$lambda_id$z")
        end
    end
end

function serialize64(a)

    buf = IOBuffer()
    b64 = Base64EncodePipe(buf)
    serialize(b64, a)
    close(b64)
    takebuf_string(buf)
end

function deserialize64(a)

    deserialize(Base64DecodePipe(IOBuffer(a)))
end

# Invoke a Julia AWS Lambda function.
# Serialise "args" and deserialise result.

function invoke_jl_lambda(aws, name, args...)

    r = invoke_lambda(aws, name, jl_data = serialize64(args))
    try
        println(r[:stdout])
    end
    try
        return deserialize64(r[:jl_data])
    end
    return r
end

# See https://github.com/JuliaLang/julia/issues/15299#issuecomment-190553775
clean_ex(ex) = ex
function clean_ex(ex::Expr)
    args = map(clean_ex, ex.args)
    if ex.head in [:break, :continue]; return ex.head; end
    if ex.head != :block; return Expr(ex.head, args...); end

    args = collect(filter(ex->(!is_linenumber(ex)), args))
    length(args) == 1 ? args[1] : Expr(ex.head, args...)
end
is_linenumber(ex) = isa(ex, LineNumberNode) || Base.Meta.isexpr(ex, :line)

# Create an AWS Lambda function.
#
# e.g.
#
#   f = @lambda aws function hello(a, b)
#
#       message = "Hello $a$b"
#
#       println("Log: $message")
#
#       return message
#   end
#
#   f("World", "!")
#   Hello World!
#
# @lambda deploys an AWS Lambda that contains the body of the Julia function.
# It then rewrites the local Julia function to call invocke_lambda().

macro lambda(args...)

    usage = "usage: @lambda aws [options::SymDict] function..."

    @assert length(args) <= 3 usage

    aws = args[1]

    f = args[end]
    @assert isa(f, Expr) usage
    @assert f.head == :function usage

    options = length(args) > 2 ? esc(args[2]) : :(Dict())

    call, body = f.args
    name = call.args[1]
    args = call.args[2:end]

    # Split "using module" lines out of body...
    modules = Expr(:block, filter(e->isa(e, Expr) && e.head == :using, body.args)...)

    body.args = filter(e->!isa(e, Expr) || e.head != :using, body.args)

    arg_names = [isa(a, Expr) ? a.args[1] : a for a in args]
    get_args = join(["""get(event,"$a",nothing)""" for a in arg_names], ", ")

    body = clean_ex(body)

    jl_code =
    """
        eval(Base, :(is_interactive = true))

        insert!(Base.LOAD_CACHE_PATH, 1, ENV["LAMBDA_TASK_ROOT"])
        mkpath("/tmp/jl_cache")
        insert!(Base.LOAD_CACHE_PATH, 1, "/tmp/jl_cache")

        using JSON

        $modules

        # Define lambda function...
        function $call
            $body
        end

        # Run lambda function...
        function main(event, context)

            global LAMBDA_CONTEXT = context

            out = open("/tmp/lambda_out", "w")

            if haskey(event, "jl_precompile")

                cd("/tmp/jl_cache")
                b64_out = Base64EncodePipe(out)
                serialize(b64_out, [f => read(f) for f in readdir()])
                close(b64_out)

            elseif haskey(event, "jl_data")

                args = deserialize(Base64DecodePipe(IOBuffer(event["jl_data"])))
                b64_out = Base64EncodePipe(out)
                serialize(b64_out, $name(args...))
                close(b64_out)

            else
                JSON.print(out, $name($get_args))
            end

            close(out)
            println("\\0")
        end

        # Read from STDIN into buf...
        buf = UInt8[]
        while true
            chunk = readavailable(STDIN)
            append!(buf, chunk)
            @assert length(chunk) > 0

            # When end of input is found, call main()...
            if length(buf) >  1 && buf[end-1:end] == ['\\0','\\n']
                input = JSON.parse(UTF8String(buf[1:end-2]))
                main(input["event"], input["context"])
                empty!(buf)
            end
        end
    """

    # Add "aws" dict as first arg...
    insert!(f.args[1].args, 2, :aws)

    # Replace function body with Lambda invocation...
    f.args[2] = :(invoke_jl_lambda(aws, $name, $(args...)))

    modules = Symbol[m.args[1] for m in modules.args]

    quote
        create_jl_lambda($(esc(aws)),
                         $(string(name)), $jl_code, $modules, $options)
        $(esc(f))
        $(Expr(:tuple, args...)) -> $(esc(name))($(esc(aws)), $(args...))
    end
end

macro λ(args...)
    esc(:(@lambda $(args...)))
end

# Create anonymous function to call "func" in the Lambda sandbox.

macro lambda_call(aws, func)

    func = Expr(:quote, func)

    esc(quote
        (args...) -> begin
            Retry.@repeat 2 try

                invoke_jl_lambda($aws, :jl_lambda_call, $func, args)

            catch e
                @retry if e.code == "404"
                    @λ $aws function jl_lambda_call(func, args)
                        eval(func)(args...)
                    end
                end
            end
        end
    end)
end

function lambda_include_string(aws, code)
    @lambda_call(aws, include_string)(code)
end

function lambda_include(aws, filename)
    code = readstring(filename)
    @lambda_call(aws, include_string)(code, filename)
end

# Evaluate "expr" in the Lambda sandbox.

macro lambda_eval(aws, expr)

    # Separate "using" statements from expression...
    usings = Expr(:block, filter(e->isa(e, Expr) && e.head == :using, expr.args)...)
    expr.args = filter(e->!isa(e, Expr) || e.head != :using, expr.args)

    # Eval "using" statements before rest of expression...
    expr = quote
        eval($(Expr(:quote, usings)))
        eval($(Expr(:quote, expr)))
    end

    esc(quote @lambda_call($aws,()->$expr)() end)
end

# List of modules in the Lambda sandbox ".ji" cache.

function lambda_module_cache(aws)

    if !lambda_exists(aws, "jl_lambda_call")
        return [symbol(p) for p in aws[:lambda_packages]]
    end

    @lambda_eval aws [symbol(splitext(f)[1]) for f in
                        [[readdir(p) for p in
                            filter(isdir, Base.LOAD_CACHE_PATH)]...;]]
end

# List of modules in local ".ji" cache.

function local_module_cache()

    [symbol(splitext(f)[1]) for f in
        [[readdir(p) for p in
            filter(isdir, Base.LOAD_CACHE_PATH)]...;]]
end

# List of source files required by "modules".

function precompiled_module_files(aws, modules::Vector{Symbol})

    ex = [lambda_module_cache(aws)..., :Main, :Base, :Core]

    modules = collect(filter(m->!(m in ex), modules))

    return unique([[_precompiled_module_files(i, ex) for i in modules]...;])
end

function _precompiled_module_files(m, exclude_modules)

    # Module must be precompiled...
    @assert m in local_module_cache()

    r = Dict()
    for p in Base.find_all_in_cache_path(m)
        modules, files = Base.cache_dependencies(p)
        for (f,t) in files
            r[f] = nothing
        end
        for (m,t) in modules
            if m in exclude_modules
                continue
            end
            for f in _precompiled_module_files(m, exclude_modules)
                r[f] = nothing
            end
        end
    end
    return collect(keys(r))
end

# Split paths from common prefix...

function path_prefix_split(paths::Vector)

    @assert length(paths) > 0

    # Find longest common prefix...
    i = 1
    for i = 1:length(paths[1])
        if any(f -> length(f) <= i || f[1:i] != paths[1][1:i], paths)
            break
        end
    end

    # Ensure prefix is a dir path...
    while i > 0 && any(f->!isdirpath(f[1:i]), paths)
        i -= 1
    end

    return paths[1][1:i], [p[i+1:end] for p in paths]
end

# Find load path and source files for "modules"...

function module_files(aws, modules::Vector{Symbol})

    if length(modules) == 0
        return [], OrderedDict()
    end

    pkgd = realpath(Pkg.dir())

    # Build a dict of files for each load path location...
    d = Dict()
    for file in precompiled_module_files(aws, modules)
        file = realpath(file)

        for p in filter(isdir, [LOAD_PATH...; pkgd])
            p = realpath(abspath(p))
            if startswith(file, p)
                file = file[length(p)+2:end]
                if !haskey(d, p)
                    d[p] = [file]
                else
                    push!(d[p], file)
                end
            end
        end
    end

    if isempty(d)
        return [], OrderedDict()
    end

    # Remove common prefix from load path locations...
    load_path = collect(filter(p->p != pkgd, keys(d)))
    prefix, short_load_path = path_prefix_split(load_path)

    # Build archive of file content...
    archive = OrderedDict()
    for (p, s) in zip([load_path...; pkgd], [short_load_path...; "julia"])
        for f in get(d,p,[])
            archive[joinpath(s, f)] = read(joinpath(p, f))
        end
    end

    return short_load_path, archive
end

#-------------------------------------------------------------------------------
# Julia Runtime Build Script
#-------------------------------------------------------------------------------

# Build the Julia runtime using a temporary EC2 server.
# Takes about 1 hour, (or about 5 minutes if full rebuild is not done).
# Upload the Julia runtime to "aws[:lambda_bucket]/jl_lambda_base.zip".

function create_jl_lambda_base(aws; release = "release-0.4")

    # List of Amazon Linux packages to install...
    yum_list = ["git",
                "cmake",
                "m4",
                "patch",
                "gcc",
                "gcc-c++",
                "gcc-gfortran",
                "libgfortran",
                "openssl-devel"]

    append!(yum_list, get(aws, :lambda_yum_packages, []))

    if !("JSON" in aws[:lambda_packages])
        push!(aws[:lambda_packages], "JSON")
    end

    build_env = []
    for (k,v) in get(aws, :lambda_build_env, Dict())
        push!(build_env, "export $k=\"$v\"\n")
    end

    # List of Julia packages to install...
    pkg_add_cmd = ["/var/task/bin/julia -e 'Pkg.init()'\n"]
    pkg_using_cmd = []
    for p in aws[:lambda_packages]
        if isa(p, Tuple)
            p, url = p
            push!(pkg_add_cmd, "/var/task/bin/julia -e 'Pkg.clone(\"$url\")'\n")
            push!(pkg_add_cmd, "/var/task/bin/julia -e 'Pkg.build(\"$p\")'\n")
        else
            push!(pkg_add_cmd, "/var/task/bin/julia -e 'Pkg.add(\"$p\")'\n")
        end
        push!(pkg_using_cmd, "/var/task/bin/julia -e 'using $p'\n")
    end

    # FIXME
    # consider downloading base tarball from here:
    # https://github.com/samoconnor/AWSLambda.jl/releases/download/v0.0.10/jl_lambda_base.tgz

    ec2_bash(aws,

        """
        cd /

        # Set up /var/task Lambda staging dir...
        mkdir -p /var/task/julia
        export HOME=/var/task
        export JULIA_PKGDIR=/var/task/julia
        export AWS_DEFAULT_REGION=$(aws[:region])
        """,

        build_env...,

        """
        if aws s3 cp s3://$(aws[:lambda_bucket])/jl_lambda_base.tgz \\
                     /jl_lambda_base.tgz
        then
            tar xzf jl_lambda_base.tgz
        else

            # Download Julia source code...
            git clone git://github.com/JuliaLang/julia.git
            cd julia
            git checkout $release

            # Configure Julia for the Xeon E5-2680 CPU used by AWS Lambda...
            cp Make.inc Make.inc.orig
            find='OPENBLAS_TARGET_ARCH=.*\$'
            repl='OPENBLAS_TARGET_ARCH=SANDYBRIDGE\\nMARCH=core-avx-i'
            sed s/\$find/\$repl/ < Make.inc.orig > Make.inc

            # Build and install Julia under /var/task...
            make -j2 prefix= DESTDIR=/var/task all
            make prefix= DESTDIR=/var/task install

            # Save tarball of raw Julia build...
            cd /
            tar czfP jl_lambda_base.tgz var/task
            aws --region $(aws[:region]) \\
                s3 cp /jl_lambda_base.tgz \\
                      s3://$(aws[:lambda_bucket])/jl_lambda_base.tgz
        fi

        # Disable yum to prevent BinDeps.jl from using it...
        # https://github.com/JuliaLang/BinDeps.jl/issues/168
        chmod 000 /usr/bin/yum

        # Precompile Julia modules...
        /var/task/bin/julia -e 'Pkg.init()'
        """,

        pkg_add_cmd...,
        pkg_using_cmd...,

        """
        # Copy minimal set of files to /task-staging...
        mkdir -p /task-staging/bin
        mkdir -p /task-staging/lib/julia
        cd /task-staging
        cp /var/task/bin/julia bin/
        cp -a /var/task/lib/julia/*.so* lib/julia
        rm -f lib/julia/*-debug.so
        cp -a /usr/lib64/libgfortran.so* lib/julia
        cp -a /usr/lib64/libquadmath.so* lib/julia

        # Copy pre-compiled modules to /tmp/task...
        cp -a /var/task/julia .
        chmod -R a+r julia/lib/
        find julia -name '.git' \\
                   -o -name '.cache' \\
                   -o -name '.travis.yml' \\
                   -o -name '.gitignore' \\
                   -o -name 'REQUIRE' \\
                   -o -name 'test' \\
                   -o -path '*/deps/downloads' \\
                   -o -path '*/deps/builds' \\
                   -o \\( \\
                        -type f \\
                        -path '*/deps/src/*' \\
                      ! -name '*.so.*' \\
                    \\) \\
                   -o -path '*/deps/usr/include' \\
                   -o -path '*/deps/usr/bin' \\
                   -o -path '*/deps/usr/lib/*.a' \\
                   -o -name 'doc' \\
                   -o -name '*.md' \\
                   -o -name 'METADATA' \\
            | xargs rm -rf

        # Copy extra bins...
        cp /usr/bin/zip bin/

        # Create .zip file...
        zip -u --symlinks -r -9 /jl_lambda_base.zip *

        # Upload .zip file to S3...
        aws --region $(aws[:region]) \\
            s3 cp /jl_lambda_base.zip \\
                  s3://$(aws[:lambda_bucket])/jl_lambda_base.zip
        """,

        instance_name = "ocaws_jl_lambda_build_server",

        image = "amzn-ami-hvm-2015.09.1.x86_64-gp2",

        packages = yum_list,

        policy = """{
            "Version": "2012-10-17",
            "Statement": [ {
                "Effect": "Allow",
                "Action": [ "s3:PutObject", "s3:GetObject" ],
                "Resource": [
                    "arn:aws:s3:::$(aws[:lambda_bucket])/jl_lambda_base.*"
                ]
            } ]
        }""")
end

#-------------------------------------------------------------------------------
# API Gateway support http://docs.aws.amazon.com/apigateway/
#-------------------------------------------------------------------------------

hallink(hal, name) = hal["_links"][name]["href"]

function apigateway(aws::SymbolDict, verb, resource; args...)
    apigateway(aws, verb, resource, Dict(args))
end

function apigateway(aws::SymbolDict, verb, resource="/restapis", query=Dict())

    r = @SymDict(
        service  = "apigateway",
        url      = AWSCore.aws_endpoint("apigateway", aws[:region]) * resource,
        content  = isempty(query) ? "" : json(query),
        headers  = Dict(),
        resource,
        verb,
        aws...
    )

    r = AWSCore.do_request(r)

    return r
end

function apigateway_restapis(aws)
    r = apigateway(aws, "GET", "/restapis")
    if haskey(r, "_embedded")
        r = r["_embedded"]
        r = get(r, "item", r)
        if !isa(r, Vector)
            r = [r]
        end
    else
        r = []
    end
    return r
end

function apigateway_lambda_arn(aws, name)
    name = arn(aws, "lambda", "function:$name")
    f = "/2015-03-31/functions/$name/invocations"
    "arn:aws:apigateway:$(aws[:region]):lambda:path$f"
end

function apigateway_create(aws, name, args)

    lambda_arn = apigateway_lambda_arn(aws, name)
    api = apigateway(aws, "POST", "/restapis", name = name)
    id = api["id"]
    method = "$(hallink(api, "resource:create"))/methods/GET"
    params = Dict(["method.request.querystring.$a" => false for a in args])
    map = "{\n$(join(["\"$a\" : \$input.params(\"$a\")" for a in args], ",\n"))\n}"

    apigateway(aws, "PUT", method,
               authorizationType = "NONE",
               requestParameters = params)

    apigateway(aws, "PUT", "$method/responses/200",
               "responseModels" => Dict("application/json" => "Empty"))

    apigateway(aws, "PUT", "$method/integration/", Dict(
               "type" => "AWS", "httpMethod" => "POST", "uri" => lambda_arn,
               "requestTemplates" => Dict("application/json" => map)))

    apigateway(aws, "PUT", "$method/integration/responses/200",
               responseTemplates = Dict("application/json" => nothing))

    lambda(aws, "POST"; path="$name/policy", query=Dict(
           "Action" => "lambda:InvokeFunction",
           "Principal" => "apigateway.amazonaws.com",
           "SourceArn" => arn(aws, "execute-api", "$id/*/GET/"),
           "StatementId" => "apigateway_$(id)_GET"))
end

end # module AWSLambda

#==============================================================================#
# End of file.
#==============================================================================#


text:
module SimplePool

# simple scan into a list of free buffers

using ..CuArrays
using ..CuArrays: @pool_timeit

using CUDAdrv

## tunables

# how much larger a buf can be to fullfil an allocation request.
# lower values improve efficiency, but increase pressure on the underlying GC.
function max_oversize(sz)
    if sz <= 2^20       # 1 MiB
        # small buffers are fine no matter
        return typemax(Int)
    elseif sz <= 2^20   # 32 MiB
        return 2^20
    else
        return 2^22
    end
end

## block of memory

struct Block
    ptr::CuPtr{Nothing}
    sz::Int
end

Base.pointer(block::Block) = block.ptr
Base.sizeof(block::Block) = block.sz

@inline function actual_alloc(sz)
    ptr = CuArrays.actual_alloc(sz)
    block = ptr === nothing ? nothing : Block(ptr, sz)
end

function actual_free(block::Block)
    CuArrays.actual_free(pointer(block))
    return
end

## pooling

const available = Set{Block}()
const allocated = Dict{CuPtr{Nothing},Block}()

function scan(sz)
    for block in available
        if sz <= sizeof(block) <= max_oversize(sz)
            delete!(available, block)
            return block
        end
    end
    return
end

function reclaim(sz::Int=typemax(Int))
    freed = 0
    while freed < sz && !isempty(available)
        block = pop!(available)
        freed += sizeof(block)
        actual_free(block)
    end
    return freed
end

function pool_alloc(sz)
    block = nothing
    for phase in 1:3
        if phase == 2
            @pool_timeit "$phase.0 gc (incremental)" GC.gc(false)
        elseif phase == 3
            @pool_timeit "$phase.0 gc (full)" GC.gc(true)
        end

        @pool_timeit "$phase.1 scan" begin
            block = scan(sz)
        end
        block === nothing || break

        @pool_timeit "$phase.2 alloc" begin
            block = actual_alloc(sz)
        end
        block === nothing || break

        @pool_timeit "$phase.3 reclaim + alloc" begin
            reclaim(sz)
            block = actual_alloc(sz)
        end
        block === nothing || break
    end

    return block
end

function pool_free(block)
    @assert !in(block, available)
    push!(available, block)
end

## interface

init() = return

function alloc(sz)
    block = pool_alloc(sz)
    if block !== nothing
        ptr = pointer(block)
        allocated[ptr] = block
        return ptr
    else
        return nothing
    end
end

function free(ptr)
    block = allocated[ptr]
    delete!(allocated, block)
    pool_free(block)
    return
end

used_memory() = isempty(allocated) ? 0 : sum(sizeof, values(allocated))

cached_memory() = isempty(available) ? 0 : sum(sizeof, available)

dump() = return

end


text:
function piechart(; x::AbstractVector = Real[], y::AbstractVector = [], holesize::Int = 0)

    v = VegaVisualization(height = 250, width = 250)

    add_data!(v, x = x, y = y, group = x)

    #Get unique table name
    table = v.data[1].name

    legend!(v)
    default_scales!(v)

    v.scales[3].domain = VegaDataRef(data = table, field = "x")

    v.marks = [VegaMark(_type = "arc",
                       from = VegaMarkFrom(data = table,
                                           transform = [VegaTransform(Dict{Any, Any}("type"=> "pie", "field"=> "y"))]),
                       properties = VegaMarkProperties(enter = VegaMarkPropertySet(
                                                                                endAngle = VegaValueRef(field = "layout_end"),
                                                                                fill = VegaValueRef(field = "group", scale = "group"),
                                                                                innerRadius = VegaValueRef(value = holesize),
                                                                                outerRadius = VegaValueRef(value = v.height),
                                                                                startAngle = VegaValueRef(field = "layout_start"),
                                                                                stroke = VegaValueRef(value = "white"),
                                                                                x = VegaValueRef(group = "width", mult = 0.5),
                                                                                y = VegaValueRef(group = "height", mult = 0.5)
                                                                                )
                                                      )
                        )
                ]

    return v
end

max_stars_repo_name: jpthor/vega


text:
using SQLAlchemy

@table type User("Users")
    name::("name",UTF8String)
    age::("age", Float64)
    id::("id", Int, primary_key=true)
end

jon=User(name="Jon", age=27)
engine = createengine("sqlite:///:memory:", echo=true)
session=Session(engine)
createall(SQLAlchemy.metadata, engine)


text:
libcufft = dlopen("libcufft")
libcuplus = dlopen("libcuplus")

CUFFT_R2C = int32(0x2a)
CUFFT_C2R = int32(0x2c)
CUFFT_C2C = int32(0x29)
CUFFT_D2Z = int32(0x6a)
CUFFT_Z2D = int32(0x6c)
CUFFT_Z2Z = int32(0x69)

CUFFT_FORWARD = int32(-1)
CUFFT_INVERSE = int32(1)

CUFFT_COMPATIBILITY_NATIVE          = int32(0x00)
CUFFT_COMPATIBILITY_FFTW_PADDING    = int32(0x01)
CUFFT_COMPATIBILITY_FFTW_ASYMMETRIC = int32(0x02)
CUFFT_COMPATIBILITY_FFTW_ALL        = int32(0x03)

function cufftPlan1d(nx::Int32, cufft_type::Int32, batch::Int32)
    ccall(dlsym(libcuplus, :cuda_cufftPlan1d),
          Uint32, (Int32, Int32, Int32),
          nx, cufft_type, batch)
end

function cufftPlan2d(nx::Int32, ny::Int32, cufft_type::Int32)
    ccall(dlsym(libcuplus, :cuda_cufftPlan2d),
          Uint32, (Int32, Int32, Int32),
          nx, ny, cufft_type)
end

function cufftPlan3d(nx::Int32, ny::Int32, nz::Int32, cufft_type::Int32)
    ccall(dlsym(libcuplus, :cuda_cufftPlan3d),
          Uint32, (Int32, Int32, Int32, Int32),
          nx, ny, nz, cufft_type)
end

function cufftPlanMany(rank::Int32, n::Ptr{Int32}, inembed::Ptr{Int32}, istride::Int32,
                       idist::Int32, onembed::Ptr{Int32}, ostride::Int32, odist::Int32,
                       cufft_type::Int32, batch::Int32)
    ccall(dlsym(libcuplus, :cuda_cufftPlanMany),
          Uint32, (Int32, Ptr{Int32}, Ptr{Int32}, Int32, Int32, Ptr{Int32}, Int32, Int32, Int32, Int32),
          rank, n, inembed, istride, idist, onembed, ostride, odist, cufft_type, batch)
end

cufftPlan1d(nx::Integer, cufft_type::Int32, batch::Integer) = cufftPlan1d(int32(nx), cufft_type, int32(batch))
cufftPlan1d(nx::Integer, cufft_type::Int32) = cufftPlan1d(int32(nx), cufft_type, int32(1))
cufftPlan1d(nx::Integer) = cufftPlan1d(int32(nx), CUFFT_C2C, int32(1))
cufftPlan2d(nx::Integer, ny::Integer, cufft_type::Int32) = cufftPlan2d(int32(nx), int32(ny), cufft_type)
cufftPlan2d(nx::Integer, ny::Integer) = cufftPlan2d(int32(nx), int32(ny), CUFFT_C2C)
cufftPlan3d(nx::Integer, ny::Integer, nz::Integer, cufft_type::Int32) = cufftPlan2d(int32(nx), int32(ny), int(nz), cufft_type)
cufftPlan3d(nx::Integer, ny::Integer, nz::Integer) = cufftPlan2d(int32(nx), int32(ny), int(nz), CUFFT_C2C)

function cufftDestroy(plan::Uint32)
    ccall(dlsym(libcufft, :cufftDestroy),
          Void, (Uint32,), plan)
end

function cufftExecC2C(plan::Uint32, idata::Ptr{Complex64}, odata::Ptr{Complex64}, direction::Int32)
    ccall(dlsym(libcufft, :cufftExecC2C),
          Void, (Uint32, Ptr{Complex64}, Ptr{Complex64}, Int32),
          plan, idata, odata, direction)
end

function cufftExecR2C(plan::Uint32, idata::Ptr{Float32}, odata::Ptr{Complex64})
    ccall(dlsym(libcufft, :cufftExecR2C),
          Void, (Uint32, Ptr{Float32}, Ptr{Complex64}),
          plan, idata, odata)
end

function cufftExecC2R(plan::Uint32, idata::Ptr{Complex64}, odata::Ptr{Float32})
    ccall(dlsym(libcufft, :cufftExecC2R),
          Void, (Uint32, Ptr{Complex64}, Ptr{Float32}),
          plan, idata, odata)
end

function cufftExecZ2Z(plan::Uint32, idata::Ptr{Complex128}, odata::Ptr{Complex128}, direction::Int32)
    ccall(dlsym(libcufft, :cufftExecZ2Z),
          Void, (Uint32, Ptr{Complex128}, Ptr{Complex128}, Int32),
          plan, idata, odata, direction)
end

function cufftExecD2Z(plan::Uint32, idata::Ptr{Float64}, odata::Ptr{Complex128})
    ccall(dlsym(libcufft, :cufftExecC2Z),
          Void, (Uint32, Ptr{Float64}, Ptr{Complex128}),
          plan, idata, odata)
end

function cufftExecZ2D(plan::Uint32, idata::Ptr{Complex128}, odata::Ptr{Float64})
    ccall(dlsym(libcufft, :cufftExecZ2D),
          Void, (Uint32, Ptr{Complex128}, Ptr{Float64}),
          plan, idata, odata)
end

function cufftSetCompatibilityMode(plan::Uint32, mode::Int32)
    ccall(dlsym(libcufft, :cufftSetCompatibilityMode),
          Void, (Uint32, Int32), plan, mode)
end

function cufftGetVersion()
    ccall(dlsym(libcuplus, :cuda_cufftGetVersion),
          Int32, ())
end

max_stars_repo_name: stefan-k/julia-CuMatrix

max_issues_repo_name: stefan-k/julia-CuMatrix

max_forks_repo_name: stefan-k/julia-CuMatrix