text:
function ListAll(DeviceType::LJDeviceType, ConnectionType::LJConnectionType, NumFound::Ref{Int32}, aDeviceTypes::Vector{Int32}, aConnectionTypes::Vector{Int32}, aSerialNumbers::Vector{Int32}, aIPAddresses::Vector{Int32})
    ccall((:LJM_ListAll, :libLabJackM), Cint, (Cint, Cint, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}), DeviceType, ConnectionType, NumFound, aDeviceTypes, aConnectionTypes, aSerialNumbers, aIPAddresses)
end

function ListAllS(DeviceType::LJDeviceType, ConnectionType::LJConnectionType, NumFound::Ref{Int32}, aDeviceTypes::Vector{Int32}, aConnectionTypes::Vector{Int32}, aSerialNumbers::Vector{Int32}, aIPAddresses::Vector{Int32})
    ccall((:LJM_ListAllS, :libLabJackM), Cint, (Cstring, Cstring, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}), DeviceType, ConnectionType, NumFound, aDeviceTypes, aConnectionTypes, aSerialNumbers, aIPAddresses)
end

function ListAllExtended(DeviceType::LJDeviceType, ConnectionType::LJConnectionType, NumAddresses::Integer, aAddresses::Vector{Cint}, aNumRegs::Vector{Cint}, MaxNumFound::Integer, NumFound::Ref{Cint}, aDeviceTypes::Vector{Cint}, aConnectionTypes::Vector{Cint}, aSerialNumbers::Vector{Cint}, aIPAddresses::Vector{Cint}, aBytes::Vector{Cuchar})
    ccall((:LJM_ListAllExtended, :libLabJackM), Cint, (Cint, Cint, Cint, Ref{Cint}, Ref{Cint}, Cint, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cuchar}), DeviceType, ConnectionType, NumAddresses, aAddresses, aNumRegs, MaxNumFound, NumFound, aDeviceTypes, aConnectionTypes, aSerialNumbers, aIPAddresses, aBytes)
end

function OpenS(DeviceType::String, ConnectionType::String, Identifier, Handle::Ref{Cint})
    ccall((:LJM_OpenS, :libLabJackM), Cint, (Cstring, Cstring, Cstring, Ref{Cint}), DeviceType, ConnectionType, Identifier, Handle)
end

function Open(DeviceType::LJDeviceType, ConnectionType::LJConnectionType, Identifier, Handle::Ref{Cint})
    ccall((:LJM_Open, :libLabJackM), Cint, (Cint, Cint, Cstring, Ref{Cint}), DeviceType, ConnectionType, Identifier, Handle)
end

function GetHandleInfo(Handle::Cint, DeviceType::Ref{Cint}, ConnectionType::Ref{Cint}, SerialNumber::Ref{Cint}, IPAddress::Ref{Cint}, Port::Ref{Cint}, MaxBytesPerMB::Ref{Cint})
    ccall((:LJM_GetHandleInfo, :libLabJackM), Cint, (Cint, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}), Handle, DeviceType, ConnectionType, SerialNumber, IPAddress, Port, MaxBytesPerMB)
end

function Close(Handle::Cint)
    ccall((:LJM_Close, :libLabJackM), Cint, (Cint,), Handle)
end

function CloseAll()
    ccall((:LJM_CloseAll, :libLabJackM), Cint, ())
end

function CleanInfo(InfoHandle::Cint)
    ccall((:LJM_CleanInfo, :libLabJackM), Cint, (Cint,), InfoHandle)
end

function eWriteAddress(Handle::Cint, Address::Integer, type::LJMDataType, Value)
    ccall((:LJM_eWriteAddress, :libLabJackM), Cint, (Cint, Cint, Cint, Cdouble), Handle, Address, type, Value)
end

function eReadAddress(Handle::Cint, Address::Integer, type::LJMDataType, Value::Ref{Cdouble})
    ccall((:LJM_eReadAddress, :libLabJackM), Cint, (Cint, Cint, Cint, Ptr{Cdouble}), Handle, Address, type, Value)
end

function eWriteName(Handle::Cint, Name::String, Value)
    ccall((:LJM_eWriteName, :libLabJackM), Cint, (Cint, Cstring, Cdouble), Handle, Name, Value)
end

function eReadName(Handle::Cint, Name::String, Value)
    ccall((:LJM_eReadName, :libLabJackM), Cint, (Cint, Cstring, Ptr{Cdouble}), Handle, Name, Value)
end

function eReadAddresses(Handle::Cint, NumFrames::Integer, aAddresses::Vector{T}, aTypes::Vector{LJMDataType}, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint}) where {T <: Integer}
    ccall((:LJM_eReadAddresses, :libLabJackM), Cint, (Cint, Cint, Ref{Cint}, Ref{Cint}, Ref{Cdouble}, Ref{Cint}), Handle, NumFrames, Cint.(aAddresses), aTypes, aValues, ErrorAddress)
end

function eReadNames(Handle::Cint, NumFrames::Integer, aNames::Vector{String}, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eReadNames, :libLabJackM), Cint, (Cint, Cint, Ref{Cstring}, Ref{Cdouble}, Ref{Cint}), Handle, NumFrames, aNames, aValues, ErrorAddress)
end

function eWriteAddresses(Handle::Cint, NumFrames::Integer, aAddresses::Vector{T}, aTypes::Vector{LJMDataType}, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint}) where {T <: Integer}
    ccall((:LJM_eWriteAddresses, :libLabJackM), Cint, (Cint, Cint, Ref{Cint}, Ref{Cint}, Ref{Cdouble}, Ref{Cint}), Handle, NumFrames, Cint.(aAddresses), aTypes, aValues, ErrorAddress)
end

function eWriteNames(Handle::Cint, NumFrames::Integer, aNames::Vector{String}, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eWriteNames, :libLabJackM), Cint, (Cint, Cint, Ref{Cstring}, Ref{Cdouble}, Ref{Cint}), Handle, NumFrames, aNames, aValues, ErrorAddress)
end

function eReadAddressArray(Handle::Cint, Address::Integer, type::LJMDataType, NumValues::Integer, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eReadAddressArray, :libLabJackM), Cint, (Cint, Cint, Cint, Cint, Ref{Cdouble}, Ref{Cint}), Handle, Address, type, NumValues, aValues, ErrorAddress)
end

function eReadNameArray(Handle::Cint, Name::String, NumValues::Integer, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eReadNameArray, :libLabJackM), Cint, (Cint, Cstring, Cint, Ref{Cdouble}, Ref{Cint}), Handle, Name, NumValues, aValues, ErrorAddress)
end

function eWriteAddressArray(Handle::Cint, Address::Integer, type::LJMDataType, NumValues::Integer, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eWriteAddressArray, :libLabJackM), Cint, (Cint, Cint, Cint, Cint, Ref{Cdouble}, Ref{Cint}), Handle, Address, type, NumValues, aValues, ErrorAddress)
end

function eWriteNameArray(Handle::Cint, Name::String, NumValues::Integer, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eWriteNameArray, :libLabJackM), Cint, (Cint, Cstring, Cint, Ref{Cdouble}, Ref{Cint}), Handle, Name, NumValues, aValues, ErrorAddress)
end

function eReadAddressByteArray(Handle::Cint, Address::Integer, NumBytes::Integer, aBytes::Vector{UInt8}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eReadAddressByteArray, :libLabJackM), Cint, (Cint, Cint, Cint, Ref{UInt8}, Ref{Cint}), Handle, Address, NumBytes, aBytes, ErrorAddress)
end

function eReadNameByteArray(Handle::Cint, Name::String, NumBytes::Integer, aBytes::Vector{UInt8}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eReadNameByteArray, :libLabJackM), Cint, (Cint, Cstring, Cint, Ref{UInt8}, Ref{Cint}), Handle, Name, NumBytes, aBytes, ErrorAddress)
end

function eWriteAddressByteArray(Handle::Cint, Address::Integer, NumBytes::Integer, aBytes::Vector{UInt8}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eWriteAddressByteArray, :libLabJackM), Cint, (Cint, Cint, Cint, Ref{UInt8}, Ref{Cint}), Handle, Address, NumBytes, aBytes, ErrorAddress)
end

function eWriteNameByteArray(Handle::Cint, Name::String, NumBytes::Integer, aBytes::Vector{UInt8}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eWriteNameByteArray, :libLabJackM), Cint, (Cint, Cstring, Cint, Ref{UInt8}, Ref{Cint}), Handle, Name, NumBytes, aBytes, ErrorAddress)
end

function eAddresses(Handle::Cint, NumFrames::Integer, aAddresses::Vector{<:Integer}, aTypes::Vector{LJMDataType}, aWrites::Vector{<:Integer}, aNumValues::Vector{<:Integer}, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint}) where {T <: Integer}
    ccall((:LJM_eAddresses, :libLabJackM), Cint, (Cint, Cint, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cdouble}, Ref{Cint}), Handle, NumFrames, Cint.(aAddresses), aTypes, Cint.(aWrites), Cint.(aNumValues), aValues, ErrorAddress)
end

function eNames(Handle::Cint, NumFrames::Integer, aNames::Vector{Cstring}, aWrites::Vector{<:Integer}, aNumValues::Vector{<:Integer}, aValues::Vector{Cdouble}, ErrorAddress::Ref{Cint})
    ccall((:LJM_eNames, :libLabJackM), Cint, (Cint, Cint, Ref{Cstring}, Ref{Cint}, Ref{Cint}, Ref{Cdouble}, Ref{Cint}), Handle, NumFrames, aNames, Cint.(aWrites), Cint.(aNumValues), aValues, ErrorAddress)
end

function eReadNameString(Handle::Cint, Name::String, ret_string::Vector{UInt8})
    ccall((:LJM_eReadNameString, :libLabJackM), Cint, (Cint, Cstring, Ptr{UInt8}), Handle, Name, ret_string)
end

function eReadAddressString(Handle::Cint, Address::Integer, ret_string::Vector{UInt8})
    ccall((:LJM_eReadAddressString, :libLabJackM), Cint, (Cint, Cint, Ptr{UInt8}), Handle, Address, ret_string)
end

function eWriteNameString(Handle::Cint, Name::String, input_string::String)
    ccall((:LJM_eWriteNameString, :libLabJackM), Cint, (Cint, Cstring, Cstring), Handle, Name, input_string)
end

function eWriteAddressString(Handle::Cint, Address::Integer, input_string::String)
    ccall((:LJM_eWriteAddressString, :libLabJackM), Cint, (Cint, Cint, Cstring), Handle, Address, input_string)
end

function eStreamStart(Handle::Cint, ScansPerRead::Integer, NumAddresses::Integer, aScanList::Vector{<:Integer}, ScanRate::Ref{Cdouble})
    ccall((:LJM_eStreamStart, :libLabJackM), Cint, (Cint, Cint, Cint, Ref{Cint}, Ref{Cdouble}), Handle, ScansPerRead, NumAddresses, Cint.(aScanList), ScanRate)
end

function eStreamRead(Handle::Cint, aData::Vector{Cdouble}, DeviceScanBacklog::Ref{Cint}, LJMScanBacklog::Ref{Cint})
    ccall((:LJM_eStreamRead, :libLabJackM), Cint, (Cint, Ref{Cdouble}, Ref{Cint}, Ref{Cint}), Handle, aData, DeviceScanBacklog, LJMScanBacklog)
end

function SetStreamCallback(Handle::Cint, Callback::LJM_StreamReadCallback, Arg::T) where {T}
    ccall((:LJM_SetStreamCallback, :libLabJackM), Cint, (Cint, LJM_StreamReadCallback, Ptr{T}), Handle, Callback, Arg)
end

function eStreamStop(Handle::Cint)
    ccall((:LJM_eStreamStop, :libLabJackM), Cint, (Cint,), Handle)
end

function StreamBurst(Handle::Cint, NumAddresses::Integer, aScanList::Vector{<:Integer}, ScanRate::Ref{Cdouble}, NumScans::Integer, aData::Vector{Cdouble})
    ccall((:LJM_StreamBurst, :libLabJackM), Cint, (Cint, Cint, Ref{Cint}, Ref{Cdouble}, UInt32, Ref{Cdouble}), Handle, NumAddresses, Cint.(aScanList), ScanRate, NumScans, aData)
end

function GetStreamTCPReceiveBufferStatus(Handle::Cint, ReceiveBufferBytesSize::Ref{UInt32}, ReceiveBufferBytesBacklog::Ref{UInt32})
    ccall((:LJM_GetStreamTCPReceiveBufferStatus, :libLabJackM), Cint, (Cint, Ref{UInt32}, Ref{UInt32}), Handle, ReceiveBufferBytesSize, ReceiveBufferBytesBacklog)
end

function WriteRaw(Handle::Cint, Data::Vector{Cuchar}, NumBytes::Integer)
    ccall((:LJM_WriteRaw, :libLabJackM), Cint, (Cint, Ref{Cuchar}, Cint), Handle, Data, NumBytes)
end

function ReadRaw(Handle::Cint, Data::Vector{Cuchar}, NumBytes::Integer)
    ccall((:LJM_ReadRaw, :libLabJackM), Cint, (Cint, Ref{Cuchar}, Cint), Handle, Data, NumBytes)
end

function AddressesToMBFB(MaxBytesPerMBFB::Integer, aAddresses::Ref{<:Integer}, aTypes::Vector{LJMDataType}, aWrites::Vector{<:Integer}, aNumValues::Vector{<:Integer}, aValues::Vector{Cdouble}, NumFrames::Vector{Cint}, aMBFBCommand::Vector{Cuchar})
    ccall((:LJM_AddressesToMBFB, :libLabJackM), Cint, (Cint, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cdouble}, Ref{Cint}, Ref{Cuchar}), MaxBytesPerMBFB, Cint.(aAddresses), aTypes, Cint.(aWrites), Cint.(aNumValues), aValues, NumFrames, aMBFBCommand)
end

function MBFBComm(Handle::Cint, UnitID::Cuchar, aMBFB::Ref{Cuchar}, ErrorAddress::Ref{Cint})
    ccall((:LJM_MBFBComm, :libLabJackM), Cint, (Cint, Cuchar, Ref{Cuchar}, Ref{Cint}), Handle, UnitID, aMBFB, ErrorAddress)
end

function UpdateValues(aMBFBResponse::Ref{Cuchar}, aTypes::Ref{Cint}, aWrites::Ref{Cint}, aNumValues::Ref{Cint}, NumFrames::Cint, aValues::Ref{Cdouble})
    ccall((:LJM_UpdateValues, :libLabJackM), Cint, (Ref{Cuchar}, Ref{Cint}, Ref{Cint}, Ref{Cint}, Cint, Ref{Cdouble}), aMBFBResponse, aTypes, aWrites, aNumValues, NumFrames, aValues)
end

function NamesToAddresses(NumFrames::Cint, aNames::Ref{Cstring}, aAddresses::Ref{Cint}, aTypes::Ref{Cint})
    ccall((:LJM_NamesToAddresses, :libLabJackM), Cint, (Cint, Ref{Cstring}, Ref{Cint}, Ref{Cint}), NumFrames, aNames, aAddresses, aTypes)
end

function NameToAddress(Name, Address::Ref{Cint}, Type::Ref{Cint})
    ccall((:LJM_NameToAddress, :libLabJackM), Cint, (Cstring, Ref{Cint}, Ref{Cint}), Name, Address, Type)
end

function AddressesToTypes(NumAddresses::Integer, aAddresses::Vector{<:Integer}, aTypes::Vector{Cint})
    ccall((:LJM_AddressesToTypes, :libLabJackM), Cint, (Cint, Ref{Cint}, Ref{Cint}), NumAddresses, Cint.(aAddresses), aTypes)
end

function AddressToType(Address::Integer, Type::Ref{Cint})
    ccall((:LJM_AddressToType, :libLabJackM), Cint, (Cint, Ref{Cint}), Address, Type)
end

function LookupConstantValue(Scope::String, ConstantName::String, ConstantValue::Ref{Cdouble})
    ccall((:LJM_LookupConstantValue, :libLabJackM), Cint, (Cstring, Cstring, Ref{Cdouble}), Scope, ConstantName, ConstantValue)
end

function LookupConstantName(Scope::String, ConstantValue::Cdouble, ConstantName::Vector{UInt8})
    ccall((:LJM_LookupConstantName, :libLabJackM), Cint, (Cstring, Cdouble, Ref{UInt8}), Scope, ConstantValue, ConstantName)
end

function ErrorToString(ErrorCode::Integer, ErrorString)
    ccall((:LJM_ErrorToString, :libLabJackM), Cint, (Cint, Cstring), ErrorCode, ErrorString)
end

function LoadConstants()
    ccall((:LJM_LoadConstants, :libLabJackM), Cint, ())
end

function LoadConstantsFromFile(FileName::String)
    ccall((:LJM_LoadConstantsFromFile, :libLabJackM), Cint, (Cstring,), FileName)
end

function LoadConstantsFromString(JsonString::String)
    ccall((:LJM_LoadConstantsFromString, :libLabJackM), Cint, (Cstring,), JsonString)
end

function TCVoltsToTemp(TCType::Cint, TCVolts::Cdouble, CJTempK::Cdouble, pTCTempK::Ref{Cdouble})
    ccall((:LJM_TCVoltsToTemp, :libLabJackM), Cint, (Cint, Cdouble, Cdouble, Ref{Cdouble}), TCType, TCVolts, CJTempK, pTCTempK)
end

function FLOAT32ToByteArray(aFLOAT32::Ref{Cfloat}, RegisterOffset::Cint, NumFLOAT32::Cint, aBytes::Ref{Cuchar})
    ccall((:LJM_FLOAT32ToByteArray, :libLabJackM), Cint, (Ref{Cfloat}, Cint, Cint, Ref{Cuchar}), aFLOAT32, RegisterOffset, NumFLOAT32, aBytes)
end

function ByteArrayToFLOAT32(aBytes::Ref{Cuchar}, RegisterOffset::Cint, NumFLOAT32::Cint, aFLOAT32::Ref{Cfloat})
    ccall((:LJM_ByteArrayToFLOAT32, :libLabJackM), Cint, (Ref{Cuchar}, Cint, Cint, Ref{Cfloat}), aBytes, RegisterOffset, NumFLOAT32, aFLOAT32)
end

function UINT16ToByteArray(aUINT16::Ref{UInt16}, RegisterOffset::Cint, NumUINT16::Cint, aBytes::Ref{Cuchar})
    ccall((:LJM_UINT16ToByteArray, :libLabJackM), Cint, (Ref{UInt16}, Cint, Cint, Ref{Cuchar}), aUINT16, RegisterOffset, NumUINT16, aBytes)
end

function ByteArrayToUINT16(aBytes::Ref{Cuchar}, RegisterOffset::Cint, NumUINT16::Cint, aUINT16::Ref{UInt16})
    ccall((:LJM_ByteArrayToUINT16, :libLabJackM), Cint, (Ref{Cuchar}, Cint, Cint, Ref{UInt16}), aBytes, RegisterOffset, NumUINT16, aUINT16)
end

function UINT32ToByteArray(aUINT32::Ref{UInt32}, RegisterOffset::Cint, NumUINT32::Cint, aBytes::Ref{Cuchar})
    ccall((:LJM_UINT32ToByteArray, :libLabJackM), Cint, (Ref{UInt32}, Cint, Cint, Ref{Cuchar}), aUINT32, RegisterOffset, NumUINT32, aBytes)
end

function ByteArrayToUINT32(aBytes::Ref{Cuchar}, RegisterOffset::Cint, NumUINT32::Cint, aUINT32::Ref{UInt32})
    ccall((:LJM_ByteArrayToUINT32, :libLabJackM), Cint, (Ref{Cuchar}, Cint, Cint, Ref{UInt32}), aBytes, RegisterOffset, NumUINT32, aUINT32)
end

function INT32ToByteArray(aINT32::Ref{Cint}, RegisterOffset::Cint, NumINT32::Cint, aBytes::Ref{Cuchar})
    ccall((:LJM_INT32ToByteArray, :libLabJackM), Cint, (Ref{Cint}, Cint, Cint, Ref{Cuchar}), aINT32, RegisterOffset, NumINT32, aBytes)
end

function ByteArrayToINT32(aBytes::Ref{Cuchar}, RegisterOffset::Cint, NumINT32::Cint, aINT32::Ref{Cint})
    ccall((:LJM_ByteArrayToINT32, :libLabJackM), Cint, (Ref{Cuchar}, Cint, Cint, Ref{Cint}), aBytes, RegisterOffset, NumINT32, aINT32)
end

function NumberToIP(Number::UInt32, IPv4String)
    ccall((:LJM_NumberToIP, :libLabJackM), Cint, (UInt32, Cstring), Number, IPv4String)
end

function IPToNumber(IPv4String, Number::Ref{UInt32})
    ccall((:LJM_IPToNumber, :libLabJackM), Cint, (Cstring, Ref{UInt32}), IPv4String, Number)
end

function NumberToMAC(Number::Culonglong, MACString)
    ccall((:LJM_NumberToMAC, :libLabJackM), Cint, (Culonglong, Cstring), Number, MACString)
end

function MACToNumber(MACString, Number::Ref{Culonglong})
    ccall((:LJM_MACToNumber, :libLabJackM), Cint, (Cstring, Ref{Culonglong}), MACString, Number)
end

function GetHostTick()
    ccall((:LJM_GetHostTick, :libLabJackM), Cint, ())
end

function GetHostTick32Bit(TickUpper::Ref{UInt32}, TickLower::Ref{UInt32})
    ccall((:LJM_GetHostTick32Bit, :libLabJackM), Cint, (Ref{UInt32}, Ref{UInt32}), TickUpper, TickLower)
end

function StartInterval(IntervalHandle::Cint, Microseconds::Cint)
    ccall((:LJM_StartInterval, :libLabJackM), Cint, (Cint, Cint), IntervalHandle, Microseconds)
end

function WaitForNextInterval(IntervalHandle::Cint, SkippedIntervals::Ref{Cint})
    ccall((:LJM_WaitForNextInterval, :libLabJackM), Cint, (Cint, Ref{Cint}), IntervalHandle, SkippedIntervals)
end

function CleanInterval(IntervalHandle::Cint)
    ccall((:LJM_CleanInterval, :libLabJackM), Cint, (Cint,), IntervalHandle)
end

function WriteLibraryConfigS(Parameter, Value::Cdouble)
    ccall((:LJM_WriteLibraryConfigS, :libLabJackM), Cint, (Cstring, Cdouble), Parameter, Value)
end

function WriteLibraryConfigStringS(Parameter, String)
    ccall((:LJM_WriteLibraryConfigStringS, :libLabJackM), Cint, (Cstring, Cstring), Parameter, String)
end

function ReadLibraryConfigS(Parameter, Value::Ref{Cdouble})
    ccall((:LJM_ReadLibraryConfigS, :libLabJackM), Cint, (Cstring, Ref{Cdouble}), Parameter, Value)
end

function ReadLibraryConfigStringS(Parameter, String)
    ccall((:LJM_ReadLibraryConfigStringS, :libLabJackM), Cint, (Cstring, Cstring), Parameter, String)
end

function LoadConfigurationFile(FileName)
    ccall((:LJM_LoadConfigurationFile, :libLabJackM), Cint, (Cstring,), FileName)
end

function GetSpecificIPsInfo(InfoHandle::Ref{Cint}, Info::Ref{Cstring})
    ccall((:LJM_GetSpecificIPsInfo, :libLabJackM), Cint, (Ref{Cint}, Ref{Cstring}), InfoHandle, Info)
end

function GetDeepSearchInfo(InfoHandle::Ref{Cint}, Info::Ref{Cstring})
    ccall((:LJM_GetDeepSearchInfo, :libLabJackM), Cint, (Ref{Cint}, Ref{Cstring}), InfoHandle, Info)
end

function Log(Level::Cint, String)
    ccall((:LJM_Log, :libLabJackM), Cint, (Cint, Cstring), Level, String)
end

function ResetLog()
    ccall((:LJM_ResetLog, :libLabJackM), Cint, ())
end

function RegisterDeviceReconnectCallback(Handle::Cint, Callback::LJM_DeviceReconnectCallback)
    ccall((:LJM_RegisterDeviceReconnectCallback, :libLabJackM), Cint, (Cint, LJM_DeviceReconnectCallback), Handle, Callback)
end


text:
mutable struct BD_CovMatrix{T<:AbstractFloat, K <: MatTypes} <: CovMatrix
    C::K
    B::K
    D::Vector{T}
    c_cov::T
end

function BD_CovMatrix(::Type{K}, n, μ_w) where K <: MatTypes

    c_cov = 1/μ_w * 2/((n+1.3)^2) + (1-1/μ_w)*min(1,2*(μ_w-1)/((n+2)^2 +μ_w))
#    c_cov *= 2
    C,B = init_matrix(K,n), init_matrix(K,n)
    D = ones(n)

    BD_CovMatrix(C,B,D,c_cov)
end

cov_matrix(cov_mat::BD_CovMatrix) = cov_mat.C
eigvals(cov_mat::BD_CovMatrix) = cov_mat.D

function update_p_σ(::Type{BD_CovMatrix{T,K}},c_σ, p_σ, μ_w, B, ẑ) where {T,K}
    (1-c_σ)*p_σ  + √(c_σ*(2-c_σ)*μ_w)*B*ẑ
end

function update_p_c(::Type{BD_CovMatrix{T,K}},c_c, p_c, H_σ, c_σ, μ_w, BD, ẑ) where {T,K}
    (1-c_c)*p_c + H_σ*√(c_σ*(2 - c_σ)*μ_w)*BD*ẑ
end

function update_C(::Type{BD_CovMatrix{T,K}}, C::K, c_cov, μ_w, p_c, w, BD, z, μ) where {T,K}
    C = (1-c_cov) * C +
        c_cov * 1/μ_w * ⊗(K,p_c) +
        c_cov * (1-1/μ_w) * ∑( w[i]* ⊗(K,BD*z[i]) for i=1:μ)
    C
end

function update_state!(d, state::CMAState{T,CM}, method::CMA) where {T,CM <: BD_CovMatrix}

    @unpack w,n,μ_w,c_σ,d_σ,c_c,p_σ,p_c,cov_mat,m,chi_D,σ,t,xs = state
    @unpack C,B,D,c_cov = cov_mat

    state.f_x_previous = state.f_x
    copy!(state.x_previous, state.x)

    λ = method.λ
    μ = floor(Int,λ/2)

    BD = B*Diagonal(D)

    z = [randn(n) for i=1:λ]
    x = [m + σ*BD*z[i] for i=1:λ]

    fx = eval_objfun(T, λ, d, x)

    idx = sortperm(fx)
    x,z,fx = x[idx], z[idx], fx[idx]

    m = ∑( w[i] * x[i] for i=1:μ )
    ẑ = ∑( w[i] * z[i] for i=1:μ )

    p_σ = update_p_σ(CM, c_σ, p_σ, μ_w, B, ẑ)
    H_σ = update_H_σ(CM, p_σ, c_σ, t, n)
    p_c = update_p_c(CM, c_c, p_c, H_σ, c_σ, μ_w, BD, ẑ)
    C = update_C(CM, C, c_cov, μ_w, p_c, w, BD, z, μ)

    σ = update_σ(CM, σ, c_σ, d_σ, p_σ, chi_D)

    D,B = eigen(C)
    B = typeof(C) <: Diagonal ? Diagonal(B) : B

    D = sqrt.(abs.(D)) #eigenvalues can become negative because of numerical errors

    t += 1
    state.x = x[1]
    state.f_x = fx[1]
    xs = x

    @pack! cov_mat = C,B,D,c_cov
    @pack! state = w,n,μ_w,c_σ,d_σ,c_c,p_σ,p_c,cov_mat,m,chi_D,σ,t,xs

    false # should the procedure force quit?
end

ext: jl


text:
typealias Store Dict{Any,Any}

function storetransform(expr::Expr)
    storearg = symbol("##store")
    emptystoreexpr = :(Stochy.Store())
    Expr(:block, Expr(symbol("="), storearg, emptystoreexpr), pass_store(expr, storearg))
end

function store_exit(store, value)
    debug() && println("store@exit: $store")
    value
end

function pass_store(expr::Expr, arg::Symbol)
    p(expr) = pass_store(expr, arg)
    if expr.head == :function
        @assert length(expr.args) == 2
        @assert expr.args[2].head == :block
        func = expr.args[1].args[1]
        args = expr.args[1].args[2:end]
        body = expr.args[2]
        Expr(:function, Expr(:call, func, [arg, args]...), p(body))
    elseif expr.head == :->
        @assert length(expr.args) == 2
        @assert expr.args[2].head == :block
        args = isa(expr.args[1], Symbol) ? [expr.args[1]] : expr.args[1].args
        body = expr.args[2]
        Expr(:->, Expr(:tuple, [arg,args]...), p(body))
    elseif expr.head == :call && expr.args[1] == :(Stochy.Thunk)
        @assert expr.args[2].head == :->
        @assert length(expr.args) == 2
        @assert length(expr.args[2].args) == 2
        Expr(:call, expr.args[1], Expr(:->, expr.args[2].args[1], p(expr.args[2].args[2])))
    elseif expr.head == :call && !((expr.args[1] in primitives) || (expr.args[1] == :(Stochy.trampoline)))
        func = expr.args[1]
        args = expr.args[2:end]
        Expr(:call, p(func), [arg, [p(a) for a in args]]...)
    elseif expr.head in [:block,:if,:||,:&&,:comparison,:call,:.,:quote,:vcat,:ref,:...]
        Expr(expr.head, [p(e) for e in expr.args]...)
    elseif expr.head == :line
        expr
    else
        error("unhandled $(expr.head) expression in pass_store")
    end
end

pass_store(expr::LineNumberNode, _) = expr
pass_store(expr::Atom, _) = expr


text:
#using GraphViz

function getgraph(net::Network)
	g = "digraph network {"
	for (ln, l) in net.layers
		for (icn, ic) in l.inputconnections
			for (pren, pre) in ic
				name = match(r"\.(.*)", string(typeof(pre))).captures[1]
				g *= "$pren -> $ln [xlabel = \"$icn.$name\"];"
			end
		end
	end
	g * "}"
end

function visualizenet(net::Network)
	g = getgraph(net)
	try
		run(pipeline(`echo $g`, `dot -Tx11`))
	catch
		warn("Is graphviz installed and in the search path?")
		println("The graph to be plotted is:\n $g")
	end
	#GraphViz.layout!(g, engine = "dot"); GraphViz.render_x11(GraphViz.Context(), g)
end
export visualizenet

max_stars_repo_name: jbrea/NetSim

max_issues_repo_name: jbrea/NetSim

max_forks_repo_name: jbrea/NetSim


text:
using BenchmarkTools
using Bessels

suite = BenchmarkGroup()

suite["besseli"] = BenchmarkGroup()
suite["besseli"]["besseli0"] = @benchmarkable besseli0(x) setup=(x = rand()*100)
suite["besseli"]["besseli1"] = @benchmarkable besseli1(x) setup=(x = rand()*100)
suite["besseli"]["besseli20"] = @benchmarkable besseli(20, x) setup=(x = rand()*100)
suite["besseli"]["besseli120"] = @benchmarkable besseli(120, x) setup=(x = rand()*100 + 1.0)

suite["besselk"] = BenchmarkGroup()
suite["besselk"]["besselk0"] = @benchmarkable besselk0(x) setup=(x = rand()*100)
suite["besselk"]["besselk1"] = @benchmarkable besselk1(x) setup=(x = rand()*100)
suite["besselk"]["besselk20"] = @benchmarkable besselk(20, x) setup=(x = rand()*100)
suite["besselk"]["besselk120"] = @benchmarkable besselk(120, x) setup=(x = rand()*100 + 1.0)

suite["besselj"] = BenchmarkGroup()
suite["besselj"]["besselj0"] = @benchmarkable besselj0(x) setup=(x = rand()*100)
suite["besselj"]["besselj1"] = @benchmarkable besselj1(x) setup=(x = rand()*100)

suite["bessely"] = BenchmarkGroup()
suite["bessely"]["bessely0"] = @benchmarkable besselj0(x) setup=(x = rand()*100)
suite["bessely"]["bessely1"] = @benchmarkable besselj1(x) setup=(x = rand()*100)

#tune!(suite)


text:
function parse_response(resp)
    return (
        HTTP.payload(resp, String) |> JSON.parse
    )
end

function header_maker(;scope="client-credentials")
    if scope == "client-credentials"
        if client_credentials_still_valid()
            return ["Authorization" => "Bearer $(spotcred().access_token)"]
        else
            @warn "Client credentials expired at $(spotcred().expires_at)"
        end
    elseif has_valid_bearer(scope)
        return ["Authorization" => "Bearer $(spotcred().ig_access_token)"]
    else
        @warn "Current scope not valid, exiting call: $scope"
    end
end

function has_valid_bearer(scope)
    if scope == "user access token"
        # No check if it has expired yet.
        spotcred().access_token != ""
    elseif has_ig_access_token()
        @info "We try the request without checking if current grant includes scope $scope." maxlog = 3
        true
    else
        @info "Starting asyncronous user authorization process. Try again later!"
        get_implicit_grant()
        #wait_for_ig_access()
        false
    end
end
"""
    strip_embed_code(sdvs<substring>)
    -> Spid(<substring>)

Get the interesting part for pasting:

Spotify app -> Right click -> Share -> Copy embed code to clipboard
"""
strip_embed_code(s) = SpId(match(r"\b[a-zA-Z0-9]{22}", s).match)


text:
# The color plan below is better in terminal dark mode
"""
Print a title.
"""
function title(msg)
    !echo_on && return
    printstyled('\n', msg, '\n', bold = true, color = :cyan)
    printstyled(repeat('=', length(msg) + 2), '\n', color=31)
end

"""
Print a subtitle.
"""
function subtitle(msg)
    !echo_on && return
    printstyled('\n', msg, '\n', color = :cyan)
    printstyled(repeat('-', length(msg) + 2), '\n', color=31)
end

"""
Print a message.
"""
function message(msg...)
    !echo_on && return
    printstyled("\nMessage: \n", color = :light_magenta)
    for m in msg
        printstyled("    - $m\n", color = 86)
    end
end

"""
Print a warning.
"""
function warning(msg...)
    !echo_on && return
    printstyled("\n! Warning: \n", color=229)
    for m in msg
        printstyled("    - $m\n", color = 86)
    end
end

"""
Print an error message
"""
function errormsg(msg...)
    !echo_on && return
    printstyled("\n!! ERROR:\n"; color=196)
    for m in msg
        printstyled("    - $m\n", color=86)
    end
end

"""
Print an item.
"""
function item(it)
    !echo_on && return
    printstyled("\n- $it\n"; color=74)
end

"""
Print a `Done` message.
"""
function done(msg... = "Done")
    !echo_on && return
    printstyled(" ... "; color=40)
    printstyled(join(msg, ' '), color=86)
    println()
end

global echo_on = true

set_echo(status::Bool = true) = (global echo_on = status)


text:
function juliadb_loader(data; ingest=false, kwargs...)
    loadtable(data; kwargs...)  # Returnes either a NDSparse or IndexedTable
end


text:
using JLD2, DataFrames, Serialization, LinearAlgebra, Distributions, LaTeXStrings
#, Distributions, Serialization, Dates, Statistics, DataFrames
import GEAS:breeding, sim_QTL, summarize, create_storage, simple_breeding,
    sim_gamma_QTL, rank_QTL, sum_qtl_frq

function gpar(nqtl, edit, fixed)
    par = begin
        Parameters = Dict(
            :nSire=> 100,
            :nDam => 200,   # male:female = 1:2
            :nSib => 40,
            :nC7e => 30,    # number of sib to be challenged
            :nG8n => 11,    # number of generations
            :nQTL => [nqtl, nqtl],
            :h²   => [.5, .5],
            :p8e  => .5,    # percentage of death after challenge
            :e19e => 1.,    # edit_successsful_rate
            :w4t  => 1,     # weight on the binary trait EBV
            :nK3n => 10,    # number of known QTL on binary trait
            :dd   => 0.01,  # A small value to be added to diagonals
            :edit => edit,
            :fix  => fixed,
            #:log  => slog
        )
        (; Parameters...)       # named tuple.  contents as above
    end
end

function t_2021_08_24()
    isdir("dat/tmp") || mkpath("dat/tmp")
    @load "dat/run/base.jld2" base
    par = gpar(100, false, false)
    qtl = sim_QTL(base, 100, 100)
    #@info "Creating storage and 1st generation"
    #snp, ped = create_storage(base, par, qtl)
    #serialize("dat/tmp/snp.ser", snp)
    #serialize("dat/tmp/ped.ser", ped)
    @info "===== Breeding generation 2-$(par.nG8n) ====="
    #breeding(ped, snp, base, qtl, par)
    snp = deserialize("dat/tmp/snp.ser")
    ped = deserialize("dat/tmp/ped.ser")
    simple_breeding(ped, snp, base, qtl, par, 3)
    snp, ped
end

"""
    function t_one_trait()
---
Test selection on `TBV`, `phenotype`, and `SNP-BLUP` on production trait only.
"""
function t_one_trait()
    BLAS.set_num_threads(12)
    nrpt = 30

    # to save the common base + generation 1
    isdir("dat/tmp") || mkpath("dat/tmp")
    @load "dat/run/base.jld2" base
    nqtl = 500
    par = gpar(nqtl, false, false)
    mtd = ["TBV", "phenotype", "EBV"]
    d = Normal()

    rst = DataFrame()
    for ir in 1:nrpt
        qtl = sim_QTL(base, par.nQTL..., d=d)
        rkq = rank_QTL(base.hap, qtl[1]) # QTL ranking in ↓ order
        @info "Creating storage and 1st generation, repeat $ir of $nrpt"
        snp, ped = create_storage(base, par, qtl)
        serialize("dat/tmp/snp.ser", snp)
        serialize("dat/tmp/ped.ser", ped)
        @info "===== Breeding generation 2-$(par.nG8n), on TBV ====="
        for op in 1:3
            println("----- Selection on $(mtd[op]) -----")
            snp = deserialize("dat/tmp/snp.ser")
            ped = deserialize("dat/tmp/ped.ser")
            simple_breeding(ped, snp, base, qtl, par, op)
            df = summarize(ped.prd, snp.prd, qtl[2])
            df.method = ones(Int, nrow(df)) .* op
            df.repeat = ones(Int, nrow(df)) .* ir
            append!(rst, df)
        end
    end
    serialize("dat/rst/one-trait.ser", rst)
    rst
end

"""
    function freq_change()
---
This to test frequency changes of the top QTL with different selection methods
and different QTL distribution.

Before with Laplacian distribution, GS was already very effective at changing
the QTL frequencies, which is suspicious.
"""
function freq_change()
    BLAS.set_num_threads(12)
    dq = [Laplace(), Normal(), Gamma(0.4)]
    isdir("dat/tmp") || mkpath("dat/tmp")
    mtd = ["TBV", "phenotype", "EBV"]
    @load "dat/run/base.jld2" base

    for nq in [100, 500]
        for d in dq
            qtl = sim_QTL(base, nq, nq, d=d)
            tpq = rank_QTL(base.hap, qtl[1])
            par = gpar(nq, false, false)
            snp, ped = create_storage(base, par, qtl)
            serialize("dat/tmp/snp.ser", snp)
            serialize("dat/tmp/ped.ser", ped)
            for op in 1:3
                println("----- Selection on $(mtd[op]) -----")
                snp = deserialize("dat/tmp/snp.ser")
                ped = deserialize("dat/tmp/ped.ser")
                simple_breeding(ped, snp, base, qtl, par, op)
                sp = snp.prd[abs.(tpq), :]
                sc = snp.prd[qtl[2].pos, :]
                prd = ped.prd
                @save "dat/tmp/q-$nq-$(string(d)[1:3])-$(mtd[op][1:3])" prd sp sc
            end
        end
    end
end

function org_one_trait_rst()
    df = deserialize("dat/rst/one-trait.ser")
    tbv, phe, ebv = groupby(df, :method)
    a = combine(groupby(tbv, :g8n),
            :mpbv => mean => :mpbv,
            :pvg => mean => :mpvg,
            :mcbv => mean => :mcbv,
            :cvg => mean => :mcvg,
                   :mica => mean => :mica)
    b = combine(groupby(phe, :g8n),
            :mpbv => mean => :mpbv,
            :pvg => mean => :mpvg,
            :mcbv => mean => :mcbv,
            :cvg => mean => :mcvg,
            :mica => mean => :mica)
    c = combine(groupby(ebv, :g8n),
            :mpbv => mean => :mpbv,
            :pvg => mean => :mpvg,
            :mcbv => mean => :mcbv,
            :cvg => mean => :mcvg,
                :mica => mean => :mica)

    p1 = plot(1:11, a.mpbv, label = "on TBV",
              ylabel = L"\textrm{Production\ }\overline{\mathrm{TBV}}",
              dpi = 300,
              legendfontsize=6,
              legend=:bottomright);
    plot!(p1, 1:11, b.mpbv, label = "on Phenotype");
    plot!(p1, 1:11, c.mpbv, label = "on EBV");

    p2 = plot(1:11, a.mpvg, label = "on TBV",
              ylabel = L"\textrm{Production\ }\overline{V_g}",
              dpi = 300,
              legendfontsize=6,
              legend=:topright);
    plot!(p2, 1:11, b.mpvg, label = "on Phenotype");
    plot!(p2, 1:11, c.mpvg, label = "on EBV");

    p3 = plot(1:11, a.mcbv, label = "on TBV",
              ylabel = L"\textrm{Challenge\ }\overline{\mathrm{TBV}}",
              dpi = 300,
              legendfontsize=6,
              legend=:bottomright);
    plot!(p3, 1:11, b.mcbv, label = "on Phenotype");
    plot!(p3, 1:11, c.mcbv, label = "on EBV");

    p4 = plot(1:11, a.mcvg, label = "on TBV",
              xlabel = "Generation",
              ylabel = L"\textrm{Challenge\ }\overline{V_g}",
              dpi = 300,
              legendfontsize=6,
              legend=:bottomleft);
    plot!(p4, 1:11, b.mcvg, label = "on Phenotype");
    plot!(p4, 1:11, c.mcvg, label = "on EBV");

    p5 = plot(1:11, a.mica, label = "on TBV",
              ylabel = L"\overline{\mathrm{Inbreeding}}",
              dpi = 300,
              legendfontsize=6,
              legend=:topleft);
    plot!(p5, 1:11, b.mica, label = "on Phenotype");
    plot!(p5, 1:11, c.mica, label = "on EBV");
    p6 = plot(p1, p2, p5, p3, p4);
    savefig(p6, "dat/rst/one-trait.pdf")
end


text:
#==============================================================================#
# CloudSearch.jl
#
# This file is generated from:
# https://github.com/aws/aws-sdk-js/blob/master/apis/cloudsearch-2013-01-01.normal.json
#==============================================================================#

__precompile__()

module CloudSearch

using AWSCore

"""
    using AWSSDK.CloudSearch.build_suggesters
    build_suggesters([::AWSConfig], arguments::Dict)
    build_suggesters([::AWSConfig]; DomainName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "BuildSuggesters", arguments::Dict)
    cloudsearch([::AWSConfig], "BuildSuggesters", DomainName=)

# BuildSuggesters Operation

Indexes the search suggestions. For more information, see [Configuring Suggesters](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html#configuring-suggesters) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

# Returns

`BuildSuggestersResponse`

# Exceptions

`BaseException`, `InternalException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/BuildSuggesters)
"""
@inline build_suggesters(aws::AWSConfig=default_aws_config(); args...) = build_suggesters(aws, args)

@inline build_suggesters(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "BuildSuggesters", args)

@inline build_suggesters(args) = build_suggesters(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.create_domain
    create_domain([::AWSConfig], arguments::Dict)
    create_domain([::AWSConfig]; DomainName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "CreateDomain", arguments::Dict)
    cloudsearch([::AWSConfig], "CreateDomain", DomainName=)

# CreateDomain Operation

Creates a new search domain. For more information, see [Creating a Search Domain](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/creating-domains.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*
A name for the domain you are creating. Allowed characters are a-z (lower-case letters), 0-9, and hyphen (-). Domain names must start with a letter or number and be at least 3 and no more than 28 characters long.

# Returns

`CreateDomainResponse`

# Exceptions

`BaseException`, `InternalException` or `LimitExceededException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/CreateDomain)
"""
@inline create_domain(aws::AWSConfig=default_aws_config(); args...) = create_domain(aws, args)

@inline create_domain(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "CreateDomain", args)

@inline create_domain(args) = create_domain(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.define_analysis_scheme
    define_analysis_scheme([::AWSConfig], arguments::Dict)
    define_analysis_scheme([::AWSConfig]; DomainName=, AnalysisScheme=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DefineAnalysisScheme", arguments::Dict)
    cloudsearch([::AWSConfig], "DefineAnalysisScheme", DomainName=, AnalysisScheme=)

# DefineAnalysisScheme Operation

Configures an analysis scheme that can be applied to a `text` or `text-array` field to define language-specific text processing options. For more information, see [Configuring Analysis Schemes](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-analysis-schemes.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `AnalysisScheme = [ ... ]` -- *Required*

```
 AnalysisScheme = [
        "AnalysisSchemeName" => <required> ::String,
        "AnalysisSchemeLanguage" => <required> "ar", "bg", "ca", "cs", "da", "de", "el", "en", "es", "eu", "fa", "fi", "fr", "ga", "gl", "he", "hi", "hu", "hy", "id", "it", "ja", "ko", "lv", "mul", "nl", "no", "pt", "ro", "ru", "sv", "th", "tr", "zh-Hans" or "zh-Hant",
        "AnalysisOptions" =>  [
            "Synonyms" =>  ::String,
            "Stopwords" =>  ::String,
            "StemmingDictionary" =>  ::String,
            "JapaneseTokenizationDictionary" =>  ::String,
            "AlgorithmicStemming" =>  "none", "minimal", "light" or "full"
        ]
    ]
```

# Returns

`DefineAnalysisSchemeResponse`

# Exceptions

`BaseException`, `InternalException`, `LimitExceededException`, `InvalidTypeException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DefineAnalysisScheme)
"""
@inline define_analysis_scheme(aws::AWSConfig=default_aws_config(); args...) = define_analysis_scheme(aws, args)

@inline define_analysis_scheme(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DefineAnalysisScheme", args)

@inline define_analysis_scheme(args) = define_analysis_scheme(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.define_expression
    define_expression([::AWSConfig], arguments::Dict)
    define_expression([::AWSConfig]; DomainName=, Expression=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DefineExpression", arguments::Dict)
    cloudsearch([::AWSConfig], "DefineExpression", DomainName=, Expression=)

# DefineExpression Operation

Configures an `[Expression](@ref)` for the search domain. Used to create new expressions and modify existing ones. If the expression exists, the new configuration replaces the old one. For more information, see [Configuring Expressions](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-expressions.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `Expression = [ ... ]` -- *Required*

```
 Expression = [
        "ExpressionName" => <required> ::String,
        "ExpressionValue" => <required> ::String
    ]
```

# Returns

`DefineExpressionResponse`

# Exceptions

`BaseException`, `InternalException`, `LimitExceededException`, `InvalidTypeException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DefineExpression)
"""
@inline define_expression(aws::AWSConfig=default_aws_config(); args...) = define_expression(aws, args)

@inline define_expression(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DefineExpression", args)

@inline define_expression(args) = define_expression(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.define_index_field
    define_index_field([::AWSConfig], arguments::Dict)
    define_index_field([::AWSConfig]; DomainName=, IndexField=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DefineIndexField", arguments::Dict)
    cloudsearch([::AWSConfig], "DefineIndexField", DomainName=, IndexField=)

# DefineIndexField Operation

Configures an `[IndexField](@ref)` for the search domain. Used to create new fields and modify existing ones. You must specify the name of the domain you are configuring and an index field configuration. The index field configuration specifies a unique name, the index field type, and the options you want to configure for the field. The options you can specify depend on the `[IndexFieldType](@ref)`. If the field exists, the new configuration replaces the old one. For more information, see [Configuring Index Fields](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-index-fields.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `IndexField = [ ... ]` -- *Required*
The index field and field options you want to configure.
```
 IndexField = [
        "IndexFieldName" => <required> ::String,
        "IndexFieldType" => <required> "int", "double", "literal", "text", "date", "latlon", "int-array", "double-array", "literal-array", "text-array" or "date-array",
        "IntOptions" =>  [
            "DefaultValue" =>  ::Int,
            "SourceField" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool,
            "SortEnabled" =>  ::Bool
        ],
        "DoubleOptions" =>  [
            "DefaultValue" =>  double,
            "SourceField" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool,
            "SortEnabled" =>  ::Bool
        ],
        "LiteralOptions" =>  [
            "DefaultValue" =>  ::String,
            "SourceField" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool,
            "SortEnabled" =>  ::Bool
        ],
        "TextOptions" =>  [
            "DefaultValue" =>  ::String,
            "SourceField" =>  ::String,
            "ReturnEnabled" =>  ::Bool,
            "SortEnabled" =>  ::Bool,
            "HighlightEnabled" =>  ::Bool,
            "AnalysisScheme" =>  ::String
        ],
        "DateOptions" =>  [
            "DefaultValue" =>  ::String,
            "SourceField" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool,
            "SortEnabled" =>  ::Bool
        ],
        "LatLonOptions" =>  [
            "DefaultValue" =>  ::String,
            "SourceField" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool,
            "SortEnabled" =>  ::Bool
        ],
        "IntArrayOptions" =>  [
            "DefaultValue" =>  ::Int,
            "SourceFields" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool
        ],
        "DoubleArrayOptions" =>  [
            "DefaultValue" =>  double,
            "SourceFields" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool
        ],
        "LiteralArrayOptions" =>  [
            "DefaultValue" =>  ::String,
            "SourceFields" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool
        ],
        "TextArrayOptions" =>  [
            "DefaultValue" =>  ::String,
            "SourceFields" =>  ::String,
            "ReturnEnabled" =>  ::Bool,
            "HighlightEnabled" =>  ::Bool,
            "AnalysisScheme" =>  ::String
        ],
        "DateArrayOptions" =>  [
            "DefaultValue" =>  ::String,
            "SourceFields" =>  ::String,
            "FacetEnabled" =>  ::Bool,
            "SearchEnabled" =>  ::Bool,
            "ReturnEnabled" =>  ::Bool
        ]
    ]
```

# Returns

`DefineIndexFieldResponse`

# Exceptions

`BaseException`, `InternalException`, `LimitExceededException`, `InvalidTypeException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DefineIndexField)
"""
@inline define_index_field(aws::AWSConfig=default_aws_config(); args...) = define_index_field(aws, args)

@inline define_index_field(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DefineIndexField", args)

@inline define_index_field(args) = define_index_field(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.define_suggester
    define_suggester([::AWSConfig], arguments::Dict)
    define_suggester([::AWSConfig]; DomainName=, Suggester=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DefineSuggester", arguments::Dict)
    cloudsearch([::AWSConfig], "DefineSuggester", DomainName=, Suggester=)

# DefineSuggester Operation

Configures a suggester for a domain. A suggester enables you to display possible matches before users finish typing their queries. When you configure a suggester, you must specify the name of the text field you want to search for possible matches and a unique name for the suggester. For more information, see [Getting Search Suggestions](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `Suggester = [ ... ]` -- *Required*

```
 Suggester = [
        "SuggesterName" => <required> ::String,
        "DocumentSuggesterOptions" => <required> [
            "SourceField" => <required> ::String,
            "FuzzyMatching" =>  "none", "low" or "high",
            "SortExpression" =>  ::String
        ]
    ]
```

# Returns

`DefineSuggesterResponse`

# Exceptions

`BaseException`, `InternalException`, `LimitExceededException`, `InvalidTypeException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DefineSuggester)
"""
@inline define_suggester(aws::AWSConfig=default_aws_config(); args...) = define_suggester(aws, args)

@inline define_suggester(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DefineSuggester", args)

@inline define_suggester(args) = define_suggester(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.delete_analysis_scheme
    delete_analysis_scheme([::AWSConfig], arguments::Dict)
    delete_analysis_scheme([::AWSConfig]; DomainName=, AnalysisSchemeName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DeleteAnalysisScheme", arguments::Dict)
    cloudsearch([::AWSConfig], "DeleteAnalysisScheme", DomainName=, AnalysisSchemeName=)

# DeleteAnalysisScheme Operation

Deletes an analysis scheme. For more information, see [Configuring Analysis Schemes](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-analysis-schemes.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `AnalysisSchemeName = ::String` -- *Required*
The name of the analysis scheme you want to delete.

# Returns

`DeleteAnalysisSchemeResponse`

# Exceptions

`BaseException`, `InternalException`, `InvalidTypeException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DeleteAnalysisScheme)
"""
@inline delete_analysis_scheme(aws::AWSConfig=default_aws_config(); args...) = delete_analysis_scheme(aws, args)

@inline delete_analysis_scheme(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DeleteAnalysisScheme", args)

@inline delete_analysis_scheme(args) = delete_analysis_scheme(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.delete_domain
    delete_domain([::AWSConfig], arguments::Dict)
    delete_domain([::AWSConfig]; DomainName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DeleteDomain", arguments::Dict)
    cloudsearch([::AWSConfig], "DeleteDomain", DomainName=)

# DeleteDomain Operation

Permanently deletes a search domain and all of its data. Once a domain has been deleted, it cannot be recovered. For more information, see [Deleting a Search Domain](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/deleting-domains.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*
The name of the domain you want to permanently delete.

# Returns

`DeleteDomainResponse`

# Exceptions

`BaseException` or `InternalException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DeleteDomain)
"""
@inline delete_domain(aws::AWSConfig=default_aws_config(); args...) = delete_domain(aws, args)

@inline delete_domain(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DeleteDomain", args)

@inline delete_domain(args) = delete_domain(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.delete_expression
    delete_expression([::AWSConfig], arguments::Dict)
    delete_expression([::AWSConfig]; DomainName=, ExpressionName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DeleteExpression", arguments::Dict)
    cloudsearch([::AWSConfig], "DeleteExpression", DomainName=, ExpressionName=)

# DeleteExpression Operation

Removes an `[Expression](@ref)` from the search domain. For more information, see [Configuring Expressions](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-expressions.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `ExpressionName = ::String` -- *Required*
The name of the `[Expression](@ref)` to delete.

# Returns

`DeleteExpressionResponse`

# Exceptions

`BaseException`, `InternalException`, `InvalidTypeException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DeleteExpression)
"""
@inline delete_expression(aws::AWSConfig=default_aws_config(); args...) = delete_expression(aws, args)

@inline delete_expression(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DeleteExpression", args)

@inline delete_expression(args) = delete_expression(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.delete_index_field
    delete_index_field([::AWSConfig], arguments::Dict)
    delete_index_field([::AWSConfig]; DomainName=, IndexFieldName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DeleteIndexField", arguments::Dict)
    cloudsearch([::AWSConfig], "DeleteIndexField", DomainName=, IndexFieldName=)

# DeleteIndexField Operation

Removes an `[IndexField](@ref)` from the search domain. For more information, see [Configuring Index Fields](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-index-fields.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `IndexFieldName = ::String` -- *Required*
The name of the index field your want to remove from the domain's indexing options.

# Returns

`DeleteIndexFieldResponse`

# Exceptions

`BaseException`, `InternalException`, `InvalidTypeException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DeleteIndexField)
"""
@inline delete_index_field(aws::AWSConfig=default_aws_config(); args...) = delete_index_field(aws, args)

@inline delete_index_field(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DeleteIndexField", args)

@inline delete_index_field(args) = delete_index_field(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.delete_suggester
    delete_suggester([::AWSConfig], arguments::Dict)
    delete_suggester([::AWSConfig]; DomainName=, SuggesterName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DeleteSuggester", arguments::Dict)
    cloudsearch([::AWSConfig], "DeleteSuggester", DomainName=, SuggesterName=)

# DeleteSuggester Operation

Deletes a suggester. For more information, see [Getting Search Suggestions](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `SuggesterName = ::String` -- *Required*
Specifies the name of the suggester you want to delete.

# Returns

`DeleteSuggesterResponse`

# Exceptions

`BaseException`, `InternalException`, `InvalidTypeException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DeleteSuggester)
"""
@inline delete_suggester(aws::AWSConfig=default_aws_config(); args...) = delete_suggester(aws, args)

@inline delete_suggester(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DeleteSuggester", args)

@inline delete_suggester(args) = delete_suggester(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.describe_analysis_schemes
    describe_analysis_schemes([::AWSConfig], arguments::Dict)
    describe_analysis_schemes([::AWSConfig]; DomainName=, <keyword arguments>)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DescribeAnalysisSchemes", arguments::Dict)
    cloudsearch([::AWSConfig], "DescribeAnalysisSchemes", DomainName=, <keyword arguments>)

# DescribeAnalysisSchemes Operation

Gets the analysis schemes configured for a domain. An analysis scheme defines language-specific text processing options for a `text` field. Can be limited to specific analysis schemes by name. By default, shows all analysis schemes and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see [Configuring Analysis Schemes](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-analysis-schemes.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*
The name of the domain you want to describe.

## `AnalysisSchemeNames = [::String, ...]`
The analysis schemes you want to describe.

## `Deployed = ::Bool`
Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`.

# Returns

`DescribeAnalysisSchemesResponse`

# Exceptions

`BaseException`, `InternalException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DescribeAnalysisSchemes)
"""
@inline describe_analysis_schemes(aws::AWSConfig=default_aws_config(); args...) = describe_analysis_schemes(aws, args)

@inline describe_analysis_schemes(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DescribeAnalysisSchemes", args)

@inline describe_analysis_schemes(args) = describe_analysis_schemes(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.describe_availability_options
    describe_availability_options([::AWSConfig], arguments::Dict)
    describe_availability_options([::AWSConfig]; DomainName=, <keyword arguments>)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DescribeAvailabilityOptions", arguments::Dict)
    cloudsearch([::AWSConfig], "DescribeAvailabilityOptions", DomainName=, <keyword arguments>)

# DescribeAvailabilityOptions Operation

Gets the availability options configured for a domain. By default, shows the configuration with any pending changes. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see [Configuring Availability Options](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-availability-options.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*
The name of the domain you want to describe.

## `Deployed = ::Bool`
Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`.

# Returns

`DescribeAvailabilityOptionsResponse`

# Exceptions

`BaseException`, `InternalException`, `InvalidTypeException`, `LimitExceededException`, `ResourceNotFoundException` or `DisabledOperationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DescribeAvailabilityOptions)
"""
@inline describe_availability_options(aws::AWSConfig=default_aws_config(); args...) = describe_availability_options(aws, args)

@inline describe_availability_options(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DescribeAvailabilityOptions", args)

@inline describe_availability_options(args) = describe_availability_options(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.describe_domains
    describe_domains([::AWSConfig], arguments::Dict)
    describe_domains([::AWSConfig]; <keyword arguments>)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DescribeDomains", arguments::Dict)
    cloudsearch([::AWSConfig], "DescribeDomains", <keyword arguments>)

# DescribeDomains Operation

Gets information about the search domains owned by this account. Can be limited to specific domains. Shows all domains by default. To get the number of searchable documents in a domain, use the console or submit a `matchall` request to your domain's search endpoint: `q=matchall&q.parser=structured&size=0`. For more information, see [Getting Information about a Search Domain](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-domain-info.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainNames = [::String, ...]`
The names of the domains you want to include in the response.

# Returns

`DescribeDomainsResponse`

# Exceptions

`BaseException` or `InternalException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DescribeDomains)
"""
@inline describe_domains(aws::AWSConfig=default_aws_config(); args...) = describe_domains(aws, args)

@inline describe_domains(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DescribeDomains", args)

@inline describe_domains(args) = describe_domains(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.describe_expressions
    describe_expressions([::AWSConfig], arguments::Dict)
    describe_expressions([::AWSConfig]; DomainName=, <keyword arguments>)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DescribeExpressions", arguments::Dict)
    cloudsearch([::AWSConfig], "DescribeExpressions", DomainName=, <keyword arguments>)

# DescribeExpressions Operation

Gets the expressions configured for the search domain. Can be limited to specific expressions by name. By default, shows all expressions and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see [Configuring Expressions](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-expressions.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*
The name of the domain you want to describe.

## `ExpressionNames = [::String, ...]`
Limits the `[DescribeExpressions](@ref)` response to the specified expressions. If not specified, all expressions are shown.

## `Deployed = ::Bool`
Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`.

# Returns

`DescribeExpressionsResponse`

# Exceptions

`BaseException`, `InternalException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DescribeExpressions)
"""
@inline describe_expressions(aws::AWSConfig=default_aws_config(); args...) = describe_expressions(aws, args)

@inline describe_expressions(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DescribeExpressions", args)

@inline describe_expressions(args) = describe_expressions(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.describe_index_fields
    describe_index_fields([::AWSConfig], arguments::Dict)
    describe_index_fields([::AWSConfig]; DomainName=, <keyword arguments>)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DescribeIndexFields", arguments::Dict)
    cloudsearch([::AWSConfig], "DescribeIndexFields", DomainName=, <keyword arguments>)

# DescribeIndexFields Operation

Gets information about the index fields configured for the search domain. Can be limited to specific fields by name. By default, shows all fields and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see [Getting Domain Information](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-domain-info.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*
The name of the domain you want to describe.

## `FieldNames = [::String, ...]`
A list of the index fields you want to describe. If not specified, information is returned for all configured index fields.

## `Deployed = ::Bool`
Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`.

# Returns

`DescribeIndexFieldsResponse`

# Exceptions

`BaseException`, `InternalException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DescribeIndexFields)
"""
@inline describe_index_fields(aws::AWSConfig=default_aws_config(); args...) = describe_index_fields(aws, args)

@inline describe_index_fields(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DescribeIndexFields", args)

@inline describe_index_fields(args) = describe_index_fields(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.describe_scaling_parameters
    describe_scaling_parameters([::AWSConfig], arguments::Dict)
    describe_scaling_parameters([::AWSConfig]; DomainName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DescribeScalingParameters", arguments::Dict)
    cloudsearch([::AWSConfig], "DescribeScalingParameters", DomainName=)

# DescribeScalingParameters Operation

Gets the scaling parameters configured for a domain. A domain's scaling parameters specify the desired search instance type and replication count. For more information, see [Configuring Scaling Options](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-scaling-options.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

# Returns

`DescribeScalingParametersResponse`

# Exceptions

`BaseException`, `InternalException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DescribeScalingParameters)
"""
@inline describe_scaling_parameters(aws::AWSConfig=default_aws_config(); args...) = describe_scaling_parameters(aws, args)

@inline describe_scaling_parameters(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DescribeScalingParameters", args)

@inline describe_scaling_parameters(args) = describe_scaling_parameters(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.describe_service_access_policies
    describe_service_access_policies([::AWSConfig], arguments::Dict)
    describe_service_access_policies([::AWSConfig]; DomainName=, <keyword arguments>)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DescribeServiceAccessPolicies", arguments::Dict)
    cloudsearch([::AWSConfig], "DescribeServiceAccessPolicies", DomainName=, <keyword arguments>)

# DescribeServiceAccessPolicies Operation

Gets information about the access policies that control access to the domain's document and search endpoints. By default, shows the configuration with any pending changes. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see [Configuring Access for a Search Domain](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-access.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*
The name of the domain you want to describe.

## `Deployed = ::Bool`
Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`.

# Returns

`DescribeServiceAccessPoliciesResponse`

# Exceptions

`BaseException`, `InternalException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DescribeServiceAccessPolicies)
"""
@inline describe_service_access_policies(aws::AWSConfig=default_aws_config(); args...) = describe_service_access_policies(aws, args)

@inline describe_service_access_policies(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DescribeServiceAccessPolicies", args)

@inline describe_service_access_policies(args) = describe_service_access_policies(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.describe_suggesters
    describe_suggesters([::AWSConfig], arguments::Dict)
    describe_suggesters([::AWSConfig]; DomainName=, <keyword arguments>)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "DescribeSuggesters", arguments::Dict)
    cloudsearch([::AWSConfig], "DescribeSuggesters", DomainName=, <keyword arguments>)

# DescribeSuggesters Operation

Gets the suggesters configured for a domain. A suggester enables you to display possible matches before users finish typing their queries. Can be limited to specific suggesters by name. By default, shows all suggesters and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see [Getting Search Suggestions](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*
The name of the domain you want to describe.

## `SuggesterNames = [::String, ...]`
The suggesters you want to describe.

## `Deployed = ::Bool`
Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`.

# Returns

`DescribeSuggestersResponse`

# Exceptions

`BaseException`, `InternalException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DescribeSuggesters)
"""
@inline describe_suggesters(aws::AWSConfig=default_aws_config(); args...) = describe_suggesters(aws, args)

@inline describe_suggesters(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "DescribeSuggesters", args)

@inline describe_suggesters(args) = describe_suggesters(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.index_documents
    index_documents([::AWSConfig], arguments::Dict)
    index_documents([::AWSConfig]; DomainName=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "IndexDocuments", arguments::Dict)
    cloudsearch([::AWSConfig], "IndexDocuments", DomainName=)

# IndexDocuments Operation

Tells the search domain to start indexing its documents using the latest indexing options. This operation must be invoked to activate options whose [OptionStatus](@ref) is `RequiresIndexDocuments`.

# Arguments

## `DomainName = ::String` -- *Required*

# Returns

`IndexDocumentsResponse`

# Exceptions

`BaseException`, `InternalException` or `ResourceNotFoundException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/IndexDocuments)
"""
@inline index_documents(aws::AWSConfig=default_aws_config(); args...) = index_documents(aws, args)

@inline index_documents(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "IndexDocuments", args)

@inline index_documents(args) = index_documents(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.list_domain_names
    list_domain_names([::AWSConfig])

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "ListDomainNames",)

# ListDomainNames Operation

Lists all search domains owned by an account.

# Returns

`ListDomainNamesResponse`

# Exceptions

`BaseException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/ListDomainNames)
"""
@inline list_domain_names(aws::AWSConfig=default_aws_config(); args...) = list_domain_names(aws, args)

@inline list_domain_names(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "ListDomainNames", args)

@inline list_domain_names(args) = list_domain_names(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.update_availability_options
    update_availability_options([::AWSConfig], arguments::Dict)
    update_availability_options([::AWSConfig]; DomainName=, MultiAZ=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "UpdateAvailabilityOptions", arguments::Dict)
    cloudsearch([::AWSConfig], "UpdateAvailabilityOptions", DomainName=, MultiAZ=)

# UpdateAvailabilityOptions Operation

Configures the availability options for a domain. Enabling the Multi-AZ option expands an Amazon CloudSearch domain to an additional Availability Zone in the same Region to increase fault tolerance in the event of a service disruption. Changes to the Multi-AZ option can take about half an hour to become active. For more information, see [Configuring Availability Options](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-availability-options.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `MultiAZ = ::Bool` -- *Required*
You expand an existing search domain to a second Availability Zone by setting the Multi-AZ option to true. Similarly, you can turn off the Multi-AZ option to downgrade the domain to a single Availability Zone by setting the Multi-AZ option to `false`.

# Returns

`UpdateAvailabilityOptionsResponse`

# Exceptions

`BaseException`, `InternalException`, `InvalidTypeException`, `LimitExceededException`, `ResourceNotFoundException` or `DisabledOperationException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/UpdateAvailabilityOptions)
"""
@inline update_availability_options(aws::AWSConfig=default_aws_config(); args...) = update_availability_options(aws, args)

@inline update_availability_options(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "UpdateAvailabilityOptions", args)

@inline update_availability_options(args) = update_availability_options(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.update_scaling_parameters
    update_scaling_parameters([::AWSConfig], arguments::Dict)
    update_scaling_parameters([::AWSConfig]; DomainName=, ScalingParameters=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "UpdateScalingParameters", arguments::Dict)
    cloudsearch([::AWSConfig], "UpdateScalingParameters", DomainName=, ScalingParameters=)

# UpdateScalingParameters Operation

Configures scaling parameters for a domain. A domain's scaling parameters specify the desired search instance type and replication count. Amazon CloudSearch will still automatically scale your domain based on the volume of data and traffic, but not below the desired instance type and replication count. If the Multi-AZ option is enabled, these values control the resources used per Availability Zone. For more information, see [Configuring Scaling Options](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-scaling-options.html) in the *Amazon CloudSearch Developer Guide*.

# Arguments

## `DomainName = ::String` -- *Required*

## `ScalingParameters = [ ... ]` -- *Required*

```
 ScalingParameters = [
        "DesiredInstanceType" =>  "search.m1.small", "search.m1.large", "search.m2.xlarge", "search.m2.2xlarge", "search.m3.medium", "search.m3.large", "search.m3.xlarge" or "search.m3.2xlarge",
        "DesiredReplicationCount" =>  ::Int,
        "DesiredPartitionCount" =>  ::Int
    ]
```

# Returns

`UpdateScalingParametersResponse`

# Exceptions

`BaseException`, `InternalException`, `LimitExceededException`, `ResourceNotFoundException` or `InvalidTypeException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/UpdateScalingParameters)
"""
@inline update_scaling_parameters(aws::AWSConfig=default_aws_config(); args...) = update_scaling_parameters(aws, args)

@inline update_scaling_parameters(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "UpdateScalingParameters", args)

@inline update_scaling_parameters(args) = update_scaling_parameters(default_aws_config(), args)

"""
    using AWSSDK.CloudSearch.update_service_access_policies
    update_service_access_policies([::AWSConfig], arguments::Dict)
    update_service_access_policies([::AWSConfig]; DomainName=, AccessPolicies=)

    using AWSCore.Services.cloudsearch
    cloudsearch([::AWSConfig], "UpdateServiceAccessPolicies", arguments::Dict)
    cloudsearch([::AWSConfig], "UpdateServiceAccessPolicies", DomainName=, AccessPolicies=)

# UpdateServiceAccessPolicies Operation

Configures the access rules that control access to the domain's document and search endpoints. For more information, see [Configuring Access for an Amazon CloudSearch Domain](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-access.html).

# Arguments

## `DomainName = ::String` -- *Required*

## `AccessPolicies = ::String` -- *Required*
The access rules you want to configure. These rules replace any existing rules.

# Returns

`UpdateServiceAccessPoliciesResponse`

# Exceptions

`BaseException`, `InternalException`, `LimitExceededException`, `ResourceNotFoundException` or `InvalidTypeException`.

See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/UpdateServiceAccessPolicies)
"""
@inline update_service_access_policies(aws::AWSConfig=default_aws_config(); args...) = update_service_access_policies(aws, args)

@inline update_service_access_policies(aws::AWSConfig, args) = AWSCore.Services.cloudsearch(aws, "UpdateServiceAccessPolicies", args)

@inline update_service_access_policies(args) = update_service_access_policies(default_aws_config(), args)

end # module CloudSearch

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


text:
function conv_block(kernelsize::Tuple{Int64,Int64}, inplanes::Int64, outplanes::Int64; stride::Int64=1, pad::Int64=0)
  conv_layer = []
  push!(conv_layer, Conv(kernelsize, inplanes => outplanes, stride = stride, pad = pad))
  push!(conv_layer, BatchNorm(outplanes, relu))
  return conv_layer
end

function inceptionblock(inplanes, out_1x1, red_3x3, out_3x3, red_5x5, out_5x5, pool_proj)
  branch1 = Chain(conv_block((1,1), inplanes, out_1x1)...)

  branch2 = Chain(conv_block((1,1), inplanes, red_3x3)...,
             conv_block((3,3), red_3x3, out_3x3; pad=1)...)

  branch3 = Chain(conv_block((1,1), inplanes, red_5x5)...,
             conv_block((5,5), red_5x5, out_5x5; pad=2)...)

  branch4 = Chain(MaxPool((3, 3), stride=1, pad=1),
             conv_block((1,1), inplanes, pool_proj)...)

  inception_layer = x -> begin
    y1 = branch1(x)
    y2 = branch2(x)
    y3 = branch3(x)
    y4 = branch4(x)

    return cat(y1, y2, y3, y4; dims=3)

  end

end

function googlenet()
  layers = Chain(conv_block((7,7), 3, 64; stride=2, pad=3)...,
                 MaxPool((3,3), stride=2, pad=1),
                 conv_block((1,1), 64, 64)...,
                 conv_block((3,3), 64, 192; pad=1)...,
                 MaxPool((3,3), stride=2, pad=1),
                 inceptionblock(192, 64, 96, 128, 16, 32, 32),
                 inceptionblock(256, 128, 128, 192, 32, 96, 64),
                 MaxPool((3,3), stride=2, pad=1),
                 inceptionblock(480, 192, 96, 208, 16, 48, 64),
                 inceptionblock(512, 160, 112, 224, 24, 64, 64),
                 inceptionblock(512, 128, 128, 256, 24, 64, 64),
                 inceptionblock(512, 112, 144, 288, 32, 64, 64),
                 inceptionblock(528, 256, 160, 320, 32, 128, 128),
                 MaxPool((3,3), stride=2, pad=1),
                 inceptionblock(832, 256, 160, 320, 32, 128, 128),
                 inceptionblock(832, 384, 192, 384, 48, 128, 128),
                 AdaptiveMeanPool((1,1)),
                 flatten,
                 Dropout(0.2),
                 Dense(1024, 1000), softmax)
  Flux.testmode!(layers, false)
  return layers
end


text:
"""
Copyright Marcus Greiff 2020

Tests of the robust attitude FSF controller on SO(3)
"""

# Include modules and recompile if running test standalone
if !isdefined(Main, :runAllTests)
    using Test, AerialVehicleControl, LinearAlgebra
    recompile();
end

# Testing fixture
function fixture()

    qref = rand(4,1); qref = qref./norm(qref); wref = rand(3,1); aref = rand(3,1); fref = 0.5;
    R = ref_state_qw_t(hcat(qref), hcat(wref), hcat(aref), fref)

    q = rand(4,1); q = q./norm(q); w = rand(3,1);
    S = dyn_state_qw_t(hcat(q), hcat(w))

    J   = rand(3,3); J  = J + J'; J  = J + I*maximum(abs.(eigvals(J)));
    kR  = 1.0;
    kw  = 1.0;
    kc  = 0.5 * maximal_feasible_kc_SO3(kR, kw, J);
    eps = 0.001;
    L   = 1.0;
    C   = con_state_qw_fsf_t(J, kR, kc, kw; eps=eps, L=L);

    return R, S, C, qref, wref, aref, q, w, kR, kc, kw, eps, L, J
end

@verbose(1, "Testing robust FSF on SO(3)...")
@testset "Test the robust FSF controller on SO(3)" begin
    @testset "Check that R is in SO(3)" begin
        # Fixture
        Rstruct, Sstruct, Cstruct, qref, wref, aref, q, w, kR, kc, kw, eps, L, J = fixture()
        Rstruct_copy = deepcopy(Rstruct)
        Sstruct_copy = deepcopy(Sstruct)
        Cstruct_copy = deepcopy(Cstruct)

        # Compute what the controls/distances should be based on the current memory
        R   = quat_2_SO3(q );
        Rr  = quat_2_SO3(qref);
        eR  = SO3_vee(Rr'*R - R'*Rr) / 2.0;
        ew  = w -  R'*Rr * wref;
        eA  = ew + kc * (J \ eR);
        mu  = -(L^2 / (L * norm(eA) + eps)) * eA;
        ff  = SO3_hat(w) * (J * w) - J*(SO3_hat(w)*R'*Rr*wref -  R'*Rr*aref);

        tau = -kR * eR - kw * ew + ff + mu;
        Psi   = 0.5 * tr(Matrix{Float64}(I, 3, 3) - Rr'*R);
        Gamma = 0.5 * tr(Matrix{Float64}(I, 2, 2) - quat_2_SU2(qref)'*quat_2_SU2(q));
        attpart  = kR * Psi;
        crosspart= kc * ew'*eR;
        ratepart = ew'*J*ew/2.0;
        Lyap     = attpart + crosspart[1,1] + ratepart[1,1];

        # Test
        status = ccall((:update_attitude_FSF_SO3_robust, AerialVehicleControl.CONT_LIB_PATH),
            Cint,
            (Ref{ref_state_qw_t}, Ref{dyn_state_qw_t}, Ref{con_state_qw_fsf_t},),
            Rstruct,
            Sstruct,
            Cstruct)

        # Test that the computations passed
        @test isapprox(status, 1);

        # Check that all of the values in the controller memory that should remain constant are unchanged
        allFieldsEqual(Sstruct, Sstruct_copy);
        allFieldsEqual(Rstruct, Rstruct_copy);
        allFieldsEqual(Cstruct, Cstruct_copy, false);

        # Check that the distances have changed
        @test !isapprox(Cstruct.dist_Psi,       Cstruct_copy.dist_Psi );
        @test !isapprox(Cstruct.dist_Gamma,     Cstruct_copy.dist_Gamma );
        @test !isapprox(Cstruct.dist_lyapunov,  Cstruct_copy.dist_lyapunov );

        # Check that the values of the controller structure that should be
        # updated is updated, and that these values corresponds to the above
        # computed torques and distances
        for i = 1:3
            @test isapprox(Cstruct.torques[i], tau[i,1]);
        end
        @test isapprox(Cstruct.dist_Psi,      Psi );
        @test isapprox(Cstruct.dist_Gamma,    Gamma );
        @test isapprox(Cstruct.dist_lyapunov, Lyap  );

    end
end


text:
Base.@kwdef mutable struct NewtonSolver{T, LS<:AbstractLinearSolver{T}} <: AbstractNonlinearSolver{T}
    prob::NonlinearProblem{T}
    linalg::LS
    maxiters::Int
    P_tol::T
    r_tol::T
    iter::Int
    norm_r::T
    dP_rel::T
    P::Vector{T}
    P_old::Vector{T}
    r::Vector{T}
    success::Bool
end

function NewtonSolver{T}(prob::NonlinearProblem{T}, linalg::AbstractLinearSolver{T}, opts) where {T}
    Nt = size(prob.C, 2)
    kwargs = (
        maxiters = opts["maxiters"],
        P_tol = opts["P_tol"],
        r_tol = opts["r_tol"],
        iter = 0,
        norm_r = zero(T),
        dP_rel = zero(T),
        P = Array{T}(undef, Nt),
        P_old = Array{T}(undef, Nt),
        r = Array{T}(undef, Nt),
        success = false,
    )
    NewtonSolver{T, typeof(linalg)}(; prob, linalg, kwargs...)
end

function perform_step!(solver::NewtonSolver, Δt, n)

    @unpack P, P_old, r, linalg, prob, P_tol, r_tol = solver

    iter, success = 0, false
    for outer iter = 1:solver.maxiters
        J = getjac(linalg, n)
        val_and_jac!(r, J, P, Δt, prob, n)

        copyto!(P_old, P)
        solve!(P, r, n, linalg)
        @turbo for i = 1:length(P)
            P[i] = P_old[i] - P[i]
        end

        x_converged, f_converged = assess_convergence(P, P_old, r, P_tol, r_tol)
        (success = x_converged | f_converged) && break
    end
    setjac!(linalg, n)
    norm_r = maximum(abs, r)
    dP_rel = maxdiff(P, P_old) / maximum(abs, P)

    @pack! solver = iter, norm_r, dP_rel, success

    return solver
end


text:
###########################################################
# Polynomial eigenvalue problem - PEP
#

"""
    struct PEP <: AbstractSPMF
    function PEP(AA::Vector{AbstractMatrix})

The type `PEP` defines a polynomial eigenvalue
 problem via its monomial coefficients.
A polynomial eigenvalue problem (PEP) is defined by the sum the
```math
Σ_i A_i λ^i,
```
where ``i = 0,1,2,``, and  all of the matrices are of size ``n×n``.
The vector `AA` contains ``A_1,...``.

# Example

```julia-repl
julia> A0=[1.0 3; 4 5]; A1=A0.+one(2); A2=ones(2,2);
julia> pep=PEP([A0,A1,A2])
julia> compute_Mder(pep,3)-(A0+A1*3+A2*9)
2×2 Array{Float64,2}:
 0.0  0.0
 0.0  0.0
```

See also [`polyeig`](methods.md#NonlinearEigenproblems.NEPSolver.polyeig), [`companion`](methods.md#NonlinearEigenproblems.NEPSolver.companion), [`ChebPEP`](@ref), [`interpolate`](@ref).
"""
struct PEP <: AbstractSPMF{AbstractMatrix}
    n::Int
    A::Array   # Monomial coefficients of PEP
end

function PEP(AA::Array)
    n=size(AA[1],1)
    AA=reshape(AA,size(AA,1))
    return PEP(n,AA)
end

# Computes the sum ``Σ_i M_i V f_i(S)`` for a PEP
function compute_MM(nep::PEP,S,V)
    T=promote_type(promote_type(eltype(nep.A[1]),eltype(S)),eltype(V))
    local Z
    if (issparse(nep))
        Z=spzeros(T,size(V,1),size(V,2))
        Si=sparse(one(T)*I, size(S,1), size(S,1))
    else
        Z=zeros(T,size(V,1),size(V,2))
        Si=Matrix(one(T)*I, size(S,1), size(S,1))
    end
    for i=1:size(nep.A,1)
        Z+=nep.A[i]*V*Si;
        Si=Si*S;
    end
    return Z
end

# Compute the ith derivative of a PEP
function compute_Mder(nep::PEP,λ::Number,i::Integer=0)
    if (issparse(nep))
        Z=spzeros(eltype(nep.A[1]),size(nep,1),size(nep,1));
    else
        Z=zeros(eltype(nep.A[1]),size(nep,1),size(nep,1));
    end
    for j=(i+1):size(nep.A,1)
        # Derivatives of monimials
        Z+= nep.A[j]*(λ^(j-i-1)*factorial(j-1)/factorial(j-i-1))
    end
    return Z
end

#  Fetch the Av's, since they are not explicitly stored in PEPs
function get_Av(nep::PEP)
    return nep.A;
end
#  Fetch the Fv's, since they are not explicitly stored in PEPs
function get_fv(nep::PEP)
    fv=Vector{Function}(undef, size(nep.A,1))
    # Construct monomial functions
    for i=1:size(nep.A,1)
        if (i==1); # optimization for constant and linear term
            fv[1] = S -> one(S);
        elseif (i==2);
            fv[2]=S->S;
        else
            # we need to introuce j otherwise the function is not typestable
            j=i-1; # power of the coefficient
            fv[i]=S->S^j;
        end
    end
    return fv;
end

"""
    interpolate([T=ComplexF64,] nep::NEP, intpoints::Array)

Interpolates a NEP in the points `intpoints` and returns a [`PEP`](@ref), i.e., a polynomial eigenvalue problem in a monomial basis. See [`ChebPEP`](@ref) for Chebyshev interpolation. The optional argument `T` is the type in which the matrices of the PEP should be defined.

See also [`ChebPEP`](@ref).
"""
interpolate(nep::NEP, intpoints::Array) = interpolate(ComplexF64, nep, intpoints)
function interpolate(::Type{T}, nep::NEP, intpoints::Array) where {T<:Number}

    n = size(nep, 1)
    d = length(intpoints)

    V = zeros(T,d,d) #Vandermonde matrix
    pwr = ones(d,1)
    for i = 1:d
        V[:,i] = pwr
        pwr = pwr.*intpoints
    end

    if (issparse(nep)) #If Sparse, do elementwise interpolation
        b = Vector{SparseMatrixCSC{T}}(undef, d)
        AA = Vector{SparseMatrixCSC{T}}(undef, d)
        V = factorize(V) # Will be used multiple times, factorize

        for i=1:d
            b[i] = compute_Mder(nep, intpoints[i])
        end

        # OBS: The following lines and hence the following method assumes that Sparsity-structure is the same!
        nnz_AA = nnz(b[1])
        for i=1:d
            AA[i] = copy(b[1])
        end

        f = zeros(d,1)
        for i = 1:nnz_AA
            for j = 1:d
                f[j] = b[j].nzval[i]
            end
            a = \(V,f)
            for j = 1:d
                AA[j].nzval[i] = a[j]
            end
        end

    else # If dense, use Vandermonde
        b = zeros(T,n*d,n)
        AA = Vector{Matrix{T}}(undef,d)
        (L, U, p) = lu(V)

        LL = kron(L, SparseMatrixCSC(I,(n,n)))
        UU = kron(U, SparseMatrixCSC(I,(n,n)))

        for i = 1:d
            b[(1:n).+(i-1)*n,:] =  compute_Mder(nep,intpoints[p[i]])
        end

        A = \(UU, \(LL,b))

        for i = 1:d
            AA[i] = A[(1:n).+(i-1)*n,:]
        end
    end

    return PEP(AA)
end

include("types_cheb_pep.jl");