answer
stringlengths
15
1.25M
## array.jl: Dense arrays typealias Vector{T} Array{T,1} typealias Matrix{T} Array{T,2} typealias VecOrMat{T} Union(Vector{T}, Matrix{T}) typealias DenseVector{T} DenseArray{T,1} typealias DenseMatrix{T} DenseArray{T,2} typealias DenseVecOrMat{T} Union(DenseVector{T}, DenseMatrix{T}) typealias StridedArray{T,N,A<:DenseArray} Union(DenseArray{T,N}, SubArray{T,N,A}) typealias StridedVector{T,A<:DenseArray} Union(DenseArray{T,1}, SubArray{T,1,A}) typealias StridedMatrix{T,A<:DenseArray} Union(DenseArray{T,2}, SubArray{T,2,A}) typealias StridedVecOrMat{T} Union(StridedVector{T}, StridedMatrix{T}) ## Basic functions ## size(a::Array) = arraysize(a) size(a::Array, d) = arraysize(a, d) size(a::Matrix) = (arraysize(a,1), arraysize(a,2)) length(a::Array) = arraylen(a) elsize{T}(a::Array{T}) = isbits(T) ? sizeof(T) : sizeof(Ptr) sizeof(a::Array) = elsize(a) * length(a) strides{T}(a::Array{T,1}) = (1,) strides{T}(a::Array{T,2}) = (1, size(a,1)) strides{T}(a::Array{T,3}) = (1, size(a,1), size(a,1)*size(a,2)) isassigned(a::Array, i::Int...) = isdefined(a, i...) ## copy ## function unsafe_copy!{T}(dest::Ptr{T}, src::Ptr{T}, N) ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Uint), dest, src, N*sizeof(T)) return dest end function unsafe_copy!{T}(dest::Array{T}, dsto, src::Array{T}, so, N) if isbits(T) unsafe_copy!(pointer(dest, dsto), pointer(src, so), N) else for i=0:N-1 @inbounds arrayset(dest, src[i+so], i+dsto) end end return dest end function copy!{T}(dest::Array{T}, dsto::Integer, src::Array{T}, so::Integer, N::Integer) if so+N-1 > length(src) || dsto+N-1 > length(dest) || dsto < 1 || so < 1 throw(BoundsError()) end unsafe_copy!(dest, dsto, src, so, N) end copy!{T}(dest::Array{T}, src::Array{T}) = copy!(dest, 1, src, 1, length(src)) function reinterpret{T,S}(::Type{T}, a::Array{S,1}) nel = int(div(length(a)*sizeof(S),sizeof(T))) # TODO: maybe check that remainder is zero? return reinterpret(T, a, (nel,)) end function reinterpret{T,S}(::Type{T}, a::Array{S}) if sizeof(S) != sizeof(T) error("result shape not specified") end reinterpret(T, a, size(a)) end function reinterpret{T,S,N}(::Type{T}, a::Array{S}, dims::NTuple{N,Int}) if !isbits(T) error("cannot reinterpret to type ", T) end if !isbits(S) error("cannot reinterpret Array of type ", S) end nel = div(length(a)*sizeof(S),sizeof(T)) if prod(dims) != nel throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(nel)")) end ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) end # reshaping to same # of dimensions function reshape{T,N}(a::Array{T,N}, dims::NTuple{N,Int}) if prod(dims) != length(a) throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(length(a))")) end if dims == size(a) return a end ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) end # reshaping to different # of dimensions function reshape{T,N}(a::Array{T}, dims::NTuple{N,Int}) if prod(dims) != length(a) throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(length(a))")) end ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) end ## Constructors ## similar(a::Array, T, dims::Dims) = Array(T, dims) similar{T}(a::Array{T,1}) = Array(T, size(a,1)) similar{T}(a::Array{T,2}) = Array(T, size(a,1), size(a,2)) similar{T}(a::Array{T,1}, dims::Dims) = Array(T, dims) similar{T}(a::Array{T,1}, m::Int) = Array(T, m) similar{T}(a::Array{T,1}, S) = Array(S, size(a,1)) similar{T}(a::Array{T,2}, dims::Dims) = Array(T, dims) similar{T}(a::Array{T,2}, m::Int) = Array(T, m) similar{T}(a::Array{T,2}, S) = Array(S, size(a,1), size(a,2)) # T[x...] constructs Array{T,1} function getindex(T::NonTupleType, vals...) a = Array(T,length(vals)) for i = 1:length(vals) a[i] = vals[i] end return a end getindex(T::(Type...)) = Array(T,0) # T[a:b] and T[a:s:b] also contruct typed ranges function getindex{T<:Number}(::Type{T}, r::Range) copy!(Array(T,length(r)), r) end function getindex{T<:Number}(::Type{T}, r1::Range, rs::Range...) a = Array(T,length(r1)+sum(length,rs)) o = 1 copy!(a, o, r1) o += length(r1) for r in rs copy!(a, o, r) o += length(r) end return a end function fill!{T<:Union(Int8,Uint8)}(a::Array{T}, x::Integer) ccall(:memset, Ptr{Void}, (Ptr{Void}, Int32, Csize_t), a, x, length(a)) return a end function fill!{T<:Union(Integer,FloatingPoint)}(a::Array{T}, x) # note: preserve -0.0 for floats if isbits(T) && T<:Integer && convert(T,x) == 0 ccall(:memset, Ptr{Void}, (Ptr{Void}, Int32, Csize_t), a,0,length(a)*sizeof(T)) else for i = 1:length(a) @inbounds a[i] = x end end return a end fill(v, dims::Dims) = fill!(Array(typeof(v), dims), v) fill(v, dims::Integer...) = fill!(Array(typeof(v), dims...), v) cell(dims::Integer...) = Array(Any, dims...) cell(dims::(Integer...)) = Array(Any, convert((Int...), dims)) for (fname, felt) in ((:zeros,:zero), (:ones,:one)) @eval begin ($fname)(T::Type, dims...) = fill!(Array(T, dims...), ($felt)(T)) ($fname)(dims...) = fill!(Array(Float64, dims...), ($felt)(Float64)) ($fname){T}(A::AbstractArray{T}) = fill!(similar(A), ($felt)(T)) end end function eye(T::Type, m::Integer, n::Integer) a = zeros(T,m,n) for i = 1:min(m,n) a[i,i] = one(T) end return a end eye(m::Integer, n::Integer) = eye(Float64, m, n) eye(T::Type, n::Integer) = eye(T, n, n) eye(n::Integer) = eye(Float64, n) eye{T}(x::AbstractMatrix{T}) = eye(T, size(x, 1), size(x, 2)) function one{T}(x::AbstractMatrix{T}) m,n = size(x) m==n || throw(DimensionMismatch("multiplicative identity defined only for square matrices")) eye(T, m) end linspace(start::Integer, stop::Integer, n::Integer) = linspace(float(start), float(stop), n) function linspace(start::Real, stop::Real, n::Integer) (start, stop) = promote(start, stop) T = typeof(start) a = Array(T, int(n)) if n == 1 a[1] = start return a end n -= 1 S = promote_type(T, Float64) for i=0:n a[i+1] = start*(convert(S, (n-i))/n) + stop*(convert(S, i)/n) end a end linspace(start::Real, stop::Real) = linspace(start, stop, 100) logspace(start::Real, stop::Real, n::Integer) = 10.^linspace(start, stop, n) logspace(start::Real, stop::Real) = logspace(start, stop, 50) ## Conversions ## convert{T,n}(::Type{Array{T}}, x::Array{T,n}) = x convert{T,n}(::Type{Array{T,n}}, x::Array{T,n}) = x convert{T,n,S}(::Type{Array{T}}, x::Array{S,n}) = convert(Array{T,n}, x) convert{T,n,S}(::Type{Array{T,n}}, x::Array{S,n}) = copy!(similar(x,T), x) function collect(T::Type, itr) if applicable(length, itr) # when length() isn't defined this branch might pollute the # type of the other. a = Array(T,length(itr)::Integer) i = 0 for x in itr a[i+=1] = x end else a = Array(T,0) for x in itr push!(a,x) end end return a end collect(itr) = collect(eltype(itr), itr) ## Indexing: getindex ## getindex(a::Array) = arrayref(a,1) getindex(A::Array, i0::Real) = arrayref(A,to_index(i0)) getindex(A::Array, i0::Real, i1::Real) = arrayref(A,to_index(i0),to_index(i1)) getindex(A::Array, i0::Real, i1::Real, i2::Real) = arrayref(A,to_index(i0),to_index(i1),to_index(i2)) getindex(A::Array, i0::Real, i1::Real, i2::Real, i3::Real) = arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3)) getindex(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real) = arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4)) getindex(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real) = arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4),to_index(i5)) getindex(A::Array, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real, I::Real...) = arrayref(A,to_index(i0),to_index(i1),to_index(i2),to_index(i3),to_index(i4),to_index(i5),to_index(I)...) # Fast copy using copy! for UnitRange function getindex(A::Array, I::UnitRange{Int}) lI = length(I) X = similar(A, lI) if lI > 0 copy!(X, 1, A, first(I), lI) end return X end function getindex{T<:Real}(A::Array, I::AbstractVector{T}) return [ A[i] for i in to_index(I) ] end function getindex{T<:Real}(A::Range, I::AbstractVector{T}) return [ A[i] for i in to_index(I) ] end function getindex(A::Range, I::AbstractVector{Bool}) checkbounds(A, I) return [ A[i] for i in to_index(I) ] end # logical indexing function getindex_bool_1d(A::Array, I::AbstractArray{Bool}) checkbounds(A, I) n = sum(I) out = similar(A, n) c = 1 for i = 1:length(I) if I[i] out[c] = A[i] c += 1 end end out end getindex(A::Vector, I::AbstractVector{Bool}) = getindex_bool_1d(A, I) getindex(A::Vector, I::AbstractArray{Bool}) = getindex_bool_1d(A, I) getindex(A::Array, I::AbstractVector{Bool}) = getindex_bool_1d(A, I) getindex(A::Array, I::AbstractArray{Bool}) = getindex_bool_1d(A, I) ## Indexing: setindex! ## setindex!{T}(A::Array{T}, x) = arrayset(A, convert(T,x), 1) setindex!{T}(A::Array{T}, x, i0::Real) = arrayset(A, convert(T,x), to_index(i0)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4), to_index(i5)) setindex!{T}(A::Array{T}, x, i0::Real, i1::Real, i2::Real, i3::Real, i4::Real, i5::Real, I::Real...) = arrayset(A, convert(T,x), to_index(i0), to_index(i1), to_index(i2), to_index(i3), to_index(i4), to_index(i5), to_index(I)...) function setindex!{T<:Real}(A::Array, x, I::AbstractVector{T}) for i in I A[i] = x end return A end function setindex!{T}(A::Array{T}, X::Array{T}, I::UnitRange{Int}) if length(X) != length(I) <API key>(X, (I,)) end copy!(A, first(I), X, 1, length(I)) return A end function setindex!{T<:Real}(A::Array, X::AbstractArray, I::AbstractVector{T}) if length(X) != length(I) <API key>(X, (I,)) end count = 1 if is(X,A) X = copy(X) end for i in I A[i] = X[count] count += 1 end return A end # logical indexing function <API key>!(A::Array, x, I::AbstractArray{Bool}) checkbounds(A, I) for i = 1:length(I) if I[i] A[i] = x end end A end function <API key>!(A::Array, X::AbstractArray, I::AbstractArray{Bool}) checkbounds(A, I) c = 1 for i = 1:length(I) if I[i] A[i] = X[c] c += 1 end end if length(X) != c-1 throw(DimensionMismatch("assigned $(length(X)) elements to length $(c-1) destination")) end A end setindex!(A::Array, X::AbstractArray, I::AbstractVector{Bool}) = <API key>!(A, X, I) setindex!(A::Array, X::AbstractArray, I::AbstractArray{Bool}) = <API key>!(A, X, I) setindex!(A::Array, x, I::AbstractVector{Bool}) = <API key>!(A, x, I) setindex!(A::Array, x, I::AbstractArray{Bool}) = <API key>!(A, x, I) # efficiently grow an array function _growat!(a::Vector, i::Integer, delta::Integer) n = length(a) if i < div(n,2) _growat_beg!(a, i, delta) else _growat_end!(a, i, delta) end return a end function _growat_beg!(a::Vector, i::Integer, delta::Integer) ccall(:jl_array_grow_beg, Void, (Any, Uint), a, delta) if i > 1 ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), pointer(a, 1), pointer(a, 1+delta), (i-1)*elsize(a)) end return a end function _growat_end!(a::Vector, i::Integer, delta::Integer) ccall(:jl_array_grow_end, Void, (Any, Uint), a, delta) n = length(a) if n >= i+delta ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), pointer(a, i+delta), pointer(a, i), (n-i-delta+1)*elsize(a)) end return a end # efficiently delete part of an array function _deleteat!(a::Vector, i::Integer, delta::Integer) n = length(a) last = i+delta-1 if i-1 < n-last _deleteat_beg!(a, i, delta) else _deleteat_end!(a, i, delta) end return a end function _deleteat_beg!(a::Vector, i::Integer, delta::Integer) if i > 1 ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), pointer(a, 1+delta), pointer(a, 1), (i-1)*elsize(a)) end ccall(:jl_array_del_beg, Void, (Any, Uint), a, delta) return a end function _deleteat_end!(a::Vector, i::Integer, delta::Integer) n = length(a) if n >= i+delta ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), pointer(a, i), pointer(a, i+delta), (n-i-delta+1)*elsize(a)) end ccall(:jl_array_del_end, Void, (Any, Uint), a, delta) return a end ## Dequeue functionality ## const _grow_none_errmsg = "[] cannot grow. Instead, initialize the array with \"T[]\", where T is the desired element type." function push!{T}(a::Array{T,1}, item) if is(T,None) error(_grow_none_errmsg) end # convert first so we don't grow the array if the assignment won't work item = convert(T, item) ccall(:jl_array_grow_end, Void, (Any, Uint), a, 1) a[end] = item return a end function push!(a::Array{Any,1}, item::ANY) ccall(:jl_array_grow_end, Void, (Any, Uint), a, 1) arrayset(a, item, length(a)) return a end function append!{T}(a::Array{T,1}, items::AbstractVector) if is(T,None) error(_grow_none_errmsg) end n = length(items) ccall(:jl_array_grow_end, Void, (Any, Uint), a, n) copy!(a, length(a)-n+1, items, 1, n) return a end function prepend!{T}(a::Array{T,1}, items::AbstractVector) if is(T,None) error(_grow_none_errmsg) end n = length(items) ccall(:jl_array_grow_beg, Void, (Any, Uint), a, n) if a === items copy!(a, 1, items, n+1, n) else copy!(a, 1, items, 1, n) end return a end function resize!(a::Vector, nl::Integer) l = length(a) if nl > l ccall(:jl_array_grow_end, Void, (Any, Uint), a, nl-l) else if nl < 0 throw(BoundsError()) end ccall(:jl_array_del_end, Void, (Any, Uint), a, l-nl) end return a end function sizehint(a::Vector, sz::Integer) ccall(:jl_array_sizehint, Void, (Any, Uint), a, sz) a end function pop!(a::Vector) if isempty(a) error("array must be non-empty") end item = a[end] ccall(:jl_array_del_end, Void, (Any, Uint), a, 1) return item end function unshift!{T}(a::Array{T,1}, item) if is(T,None) error(_grow_none_errmsg) end item = convert(T, item) ccall(:jl_array_grow_beg, Void, (Any, Uint), a, 1) a[1] = item return a end function shift!(a::Vector) if isempty(a) error("array must be non-empty") end item = a[1] ccall(:jl_array_del_beg, Void, (Any, Uint), a, 1) return item end function insert!{T}(a::Array{T,1}, i::Integer, item) 1 <= i <= length(a)+1 || throw(BoundsError()) i == length(a)+1 && return push!(a, item) item = convert(T, item) _growat!(a, i, 1) a[i] = item return a end function deleteat!(a::Vector, i::Integer) if !(1 <= i <= length(a)) throw(BoundsError()) end return _deleteat!(a, i, 1) end function deleteat!{T<:Integer}(a::Vector, r::UnitRange{T}) n = length(a) f = first(r) l = last(r) if !(1 <= f && l <= n) throw(BoundsError()) end return _deleteat!(a, f, length(r)) end function deleteat!(a::Vector, inds) n = length(a) s = start(inds) done(inds, s) && return a (p, s) = next(inds, s) q = p+1 while !done(inds, s) (i,s) = next(inds, s) if !(q <= i <= n) i < q && error("indices must be unique and sorted") throw(BoundsError()) end while q < i @inbounds a[p] = a[q] p += 1; q += 1 end q = i+1 end while q <= n @inbounds a[p] = a[q] p += 1; q += 1 end ccall(:jl_array_del_end, Void, (Any, Uint), a, n-p+1) return a end const _default_splice = [] function splice!(a::Vector, i::Integer, ins::AbstractArray=_default_splice) v = a[i] m = length(ins) if m == 0 _deleteat!(a, i, 1) elseif m == 1 a[i] = ins[1] else _growat!(a, i, m-1) for k = 1:m a[i+k-1] = ins[k] end end return v end function splice!{T<:Integer}(a::Vector, r::UnitRange{T}, ins::AbstractArray=_default_splice) v = a[r] m = length(ins) if m == 0 deleteat!(a, r) return v end n = length(a) f = first(r) l = last(r) d = length(r) if m < d delta = d - m if f-1 < n-l _deleteat_beg!(a, f, delta) else _deleteat_end!(a, l-delta+1, delta) end elseif m > d delta = m - d if f-1 < n-l _growat_beg!(a, f, delta) else _growat_end!(a, l+1, delta) end end for k = 1:m a[f+k-1] = ins[k] end return v end function empty!(a::Vector) ccall(:jl_array_del_end, Void, (Any, Uint), a, length(a)) return a end ## Unary operators ## function conj!{T<:Number}(A::AbstractArray{T}) for i=1:length(A) A[i] = conj(A[i]) end return A end for f in (:-, :~, :conj, :sign) @eval begin function ($f)(A::StridedArray) F = similar(A) for i=1:length(A) F[i] = ($f)(A[i]) end return F end end end (-)(A::StridedArray{Bool}) = reshape([ -A[i] for i=1:length(A) ], size(A)) real(A::StridedArray) = reshape([ real(x) for x in A ], size(A)) imag(A::StridedArray) = reshape([ imag(x) for x in A ], size(A)) real{T<:Real}(x::StridedArray{T}) = x imag{T<:Real}(x::StridedArray{T}) = zero(x) function !(A::StridedArray{Bool}) F = similar(A) for i=1:length(A) F[i] = !A[i] end return F end ## Binary arithmetic operators ## promote_array_type{Scalar, Arry}(::Type{Scalar}, ::Type{Arry}) = promote_type(Scalar, Arry) promote_array_type{S<:Real, A<:FloatingPoint}(::Type{S}, ::Type{A}) = A promote_array_type{S<:Union(Complex, Real), AT<:FloatingPoint}(::Type{S}, ::Type{Complex{AT}}) = Complex{AT} promote_array_type{S<:Integer, A<:Integer}(::Type{S}, ::Type{A}) = A promote_array_type{S<:Integer}(::Type{S}, ::Type{Bool}) = S ./{T<:Integer}(x::Integer, y::StridedArray{T}) = reshape([ x ./ y[i] for i=1:length(y) ], size(y)) ./{T<:Integer}(x::StridedArray{T}, y::Integer) = reshape([ x[i] ./ y for i=1:length(x) ], size(x)) ./{T<:Integer}(x::Integer, y::StridedArray{Complex{T}}) = reshape([ x ./ y[i] for i=1:length(y) ], size(y)) ./{T<:Integer}(x::StridedArray{Complex{T}}, y::Integer) = reshape([ x[i] ./ y for i=1:length(x) ], size(x)) ./{S<:Integer,T<:Integer}(x::Complex{S}, y::StridedArray{T}) = reshape([ x ./ y[i] for i=1:length(y) ], size(y)) ./{S<:Integer,T<:Integer}(x::StridedArray{S}, y::Complex{T}) = reshape([ x[i] ./ y for i=1:length(x) ], size(x)) # ^ is difficult, since negative exponents give a different type .^(x::Number, y::StridedArray) = reshape([ x ^ y[i] for i=1:length(y) ], size(y)) .^(x::StridedArray, y::Number ) = reshape([ x[i] ^ y for i=1:length(x) ], size(x)) for f in (:+, :-, :div, :mod, :&, :|, :$) @eval begin function ($f){S,T}(A::StridedArray{S}, B::StridedArray{T}) F = similar(A, promote_type(S,T), promote_shape(size(A),size(B))) for i=1:length(A) @inbounds F[i] = ($f)(A[i], B[i]) end return F end # interaction with Ranges function ($f){S,T<:Real}(A::StridedArray{S}, B::Range{T}) F = similar(A, promote_type(S,T), promote_shape(size(A),size(B))) i = 1 for b in B @inbounds F[i] = ($f)(A[i], b) i += 1 end return F end function ($f){S<:Real,T}(A::Range{S}, B::StridedArray{T}) F = similar(B, promote_type(S,T), promote_shape(size(A),size(B))) i = 1 for a in A @inbounds F[i] = ($f)(a, B[i]) i += 1 end return F end end end for f in (:.+, :.-, :.*, :./, :.\, :.%, :div, :mod, :rem, :&, :|, :$) @eval begin function ($f){T}(A::Number, B::StridedArray{T}) F = similar(B, promote_array_type(typeof(A),T)) for i=1:length(B) @inbounds F[i] = ($f)(A, B[i]) end return F end function ($f){T}(A::StridedArray{T}, B::Number) F = similar(A, promote_array_type(typeof(B),T)) for i=1:length(A) @inbounds F[i] = ($f)(A[i], B) end return F end end end (+)(A::AbstractArray{Bool},x::Bool) = A .+ x (+)(x::Bool,A::AbstractArray{Bool}) = x .+ A (-)(A::AbstractArray{Bool},x::Bool) = A .- x (-)(x::Bool,A::AbstractArray{Bool}) = x .- A (+)(A::AbstractArray,x::Number) = A .+ x (+)(x::Number,A::AbstractArray) = x .+ A (-)(A::AbstractArray,x::Number) = A .- x (-)(x::Number,A::AbstractArray) = x .- A # functions that should give an Int result for Bool arrays for f in (:.+, :.-) @eval begin function ($f)(A::Bool, B::StridedArray{Bool}) F = similar(B, Int, size(B)) for i=1:length(B) @inbounds F[i] = ($f)(A, B[i]) end return F end function ($f)(A::StridedArray{Bool}, B::Bool) F = similar(A, Int, size(A)) for i=1:length(A) @inbounds F[i] = ($f)(A[i], B) end return F end end end for f in (:+, :-) @eval begin function ($f)(A::StridedArray{Bool}, B::StridedArray{Bool}) F = similar(A, Int, promote_shape(size(A), size(B))) for i=1:length(A) @inbounds F[i] = ($f)(A[i], B[i]) end return F end end end ## promotion to complex ## function complex{S<:Real,T<:Real}(A::Array{S}, B::Array{T}) if size(A) != size(B); throw(DimensionMismatch("")); end F = similar(A, typeof(complex(zero(S),zero(T)))) for i=1:length(A) @inbounds F[i] = complex(A[i], B[i]) end return F end function complex{T<:Real}(A::Real, B::Array{T}) F = similar(B, typeof(complex(A,zero(T)))) for i=1:length(B) @inbounds F[i] = complex(A, B[i]) end return F end function complex{T<:Real}(A::Array{T}, B::Real) F = similar(A, typeof(complex(zero(T),B))) for i=1:length(A) @inbounds F[i] = complex(A[i], B) end return F end # use memcmp for lexcmp on byte arrays function lexcmp(a::Array{Uint8,1}, b::Array{Uint8,1}) c = ccall(:memcmp, Int32, (Ptr{Uint8}, Ptr{Uint8}, Uint), a, b, min(length(a),length(b))) c < 0 ? -1 : c > 0 ? +1 : cmp(length(a),length(b)) end ## data movement ## function slicedim(A::Array, d::Integer, i::Integer) d_in = size(A) leading = d_in[1:(d-1)] d_out = tuple(leading..., 1, d_in[(d+1):end]...) M = prod(leading) N = length(A) stride = M * d_in[d] B = similar(A, d_out) index_offset = 1 + (i-1)*M l = 1 if M==1 for j=0:stride:(N-stride) B[l] = A[j + index_offset] l += 1 end else for j=0:stride:(N-stride) offs = j + index_offset for k=0:(M-1) B[l] = A[offs + k] l += 1 end end end return B end function flipdim{T}(A::Array{T}, d::Integer) nd = ndims(A) sd = d > nd ? 1 : size(A, d) if sd == 1 || isempty(A) return copy(A) end B = similar(A) nnd = 0 for i = 1:nd nnd += int(size(A,i)==1 || i==d) end if nnd==nd # flip along the only non-singleton dimension for i = 1:sd B[i] = A[sd+1-i] end return B end d_in = size(A) leading = d_in[1:(d-1)] M = prod(leading) N = length(A) stride = M * sd if M==1 for j = 0:stride:(N-stride) for i = 1:sd ri = sd+1-i B[j + ri] = A[j + i] end end else if isbits(T) && M>200 for i = 1:sd ri = sd+1-i for j=0:stride:(N-stride) offs = j + 1 + (i-1)*M boffs = j + 1 + (ri-1)*M copy!(B, boffs, A, offs, M) end end else for i = 1:sd ri = sd+1-i for j=0:stride:(N-stride) offs = j + 1 + (i-1)*M boffs = j + 1 + (ri-1)*M for k=0:(M-1) B[boffs + k] = A[offs + k] end end end end end return B end function rotl90(A::StridedMatrix) m,n = size(A) B = similar(A,(n,m)) for i=1:m, j=1:n B[n-j+1,i] = A[i,j] end return B end function rotr90(A::StridedMatrix) m,n = size(A) B = similar(A,(n,m)) for i=1:m, j=1:n B[j,m-i+1] = A[i,j] end return B end function rot180(A::StridedMatrix) m,n = size(A) B = similar(A) for i=1:m, j=1:n B[m-i+1,n-j+1] = A[i,j] end return B end function rotl90(A::AbstractMatrix, k::Integer) k = mod(k, 4) k == 1 ? rotl90(A) : k == 2 ? rot180(A) : k == 3 ? rotr90(A) : copy(A) end rotr90(A::AbstractMatrix, k::Integer) = rotl90(A,-k) rot180(A::AbstractMatrix, k::Integer) = mod(k, 2) == 1 ? rot180(A) : copy(A) # note: probably should be StridedVector or AbstractVector function reverse(A::AbstractVector, s=1, n=length(A)) B = similar(A) for i = 1:s-1 B[i] = A[i] end for i = s:n B[i] = A[n+s-i] end for i = n+1:length(A) B[i] = A[i] end B end reverse(v::StridedVector) = (n=length(v); [ v[n-i+1] for i=1:n ]) reverse(v::StridedVector, s, n=length(v)) = reverse!(copy(v), s, n) function reverse!(v::StridedVector, s=1, n=length(v)) r = n for i=s:div(s+n-1,2) v[i], v[r] = v[r], v[i] r -= 1 end v end function vcat{T}(arrays::Array{T,1}...) n = 0 for a in arrays n += length(a) end arr = Array(T, n) ptr = pointer(arr) offset = 0 if isbits(T) elsz = sizeof(T) else elsz = div(WORD_SIZE,8) end for a in arrays nba = length(a)*elsz ccall(:memcpy, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Uint), ptr+offset, a, nba) offset += nba end return arr end ## find ## # returns the index of the next non-zero element, or 0 if all zeros function findnext(A, start::Integer) for i = start:length(A) if A[i] != 0 return i end end return 0 end findfirst(A) = findnext(A,1) # returns the index of the next matching element function findnext(A, v, start::Integer) for i = start:length(A) if A[i] == v return i end end return 0 end findfirst(A,v) = findnext(A,v,1) # returns the index of the next element for which the function returns true function findnext(testf::Function, A, start::Integer) for i = start:length(A) if testf(A[i]) return i end end return 0 end findfirst(testf::Function, A) = findnext(testf, A, 1) function find(testf::Function, A::StridedArray) # use a dynamic-length array to store the indexes, then copy to a non-padded # array for the return tmpI = Array(Int, 0) for i = 1:length(A) if testf(A[i]) push!(tmpI, i) end end I = similar(A, Int, length(tmpI)) copy!(I, tmpI) I end function find(A::StridedArray) nnzA = countnz(A) I = similar(A, Int, nnzA) count = 1 for i=1:length(A) if A[i] != 0 I[count] = i count += 1 end end return I end find(x::Number) = x == 0 ? Array(Int,0) : [1] find(testf::Function, x) = find(testf(x)) findn(A::AbstractVector) = find(A) function findn(A::StridedMatrix) nnzA = countnz(A) I = similar(A, Int, nnzA) J = similar(A, Int, nnzA) count = 1 for j=1:size(A,2), i=1:size(A,1) if A[i,j] != 0 I[count] = i J[count] = j count += 1 end end return (I, J) end function findnz{T}(A::StridedMatrix{T}) nnzA = countnz(A) I = zeros(Int, nnzA) J = zeros(Int, nnzA) NZs = zeros(T, nnzA) count = 1 if nnzA > 0 for j=1:size(A,2), i=1:size(A,1) Aij = A[i,j] if Aij != 0 I[count] = i J[count] = j NZs[count] = Aij count += 1 end end end return (I, J, NZs) end function findmax(a) if isempty(a) error("array must be non-empty") end m = a[1] mi = 1 for i=2:length(a) ai = a[i] if ai > m || m!=m m = ai mi = i end end return (m, mi) end function findmin(a) if isempty(a) error("array must be non-empty") end m = a[1] mi = 1 for i=2:length(a) ai = a[i] if ai < m || m!=m m = ai mi = i end end return (m, mi) end indmax(a) = findmax(a)[2] indmin(a) = findmin(a)[2] # similar to Matlab's ismember # returns a vector containing the highest index in b for each value in a that is a member of b function indexin(a::AbstractArray, b::AbstractArray) bdict = Dict(b, 1:length(b)) [get(bdict, i, 0) for i in a] end # findin (the index of intersection) function findin(a, b::UnitRange) ind = Array(Int, 0) f = first(b) l = last(b) for i = 1:length(a) if f <= a[i] <= l push!(ind, i) end end ind end function findin(a, b) ind = Array(Int, 0) bset = union!(Set(), b) for i = 1:length(a) if in(a[i], bset) push!(ind, i) end end ind end # Copying subregions function indcopy(sz::Dims, I::Vector) n = length(I) s = sz[n] for i = n+1:length(sz) s *= sz[i] end dst = eltype(I)[findin(I[i], i < n ? (1:sz[i]) : (1:s)) for i = 1:n] src = eltype(I)[I[i][findin(I[i], i < n ? (1:sz[i]) : (1:s))] for i = 1:n] dst, src end function indcopy(sz::Dims, I::(RangeIndex...)) n = length(I) s = sz[n] for i = n+1:length(sz) s *= sz[i] end dst::typeof(I) = ntuple(n, i-> findin(I[i], i < n ? (1:sz[i]) : (1:s)))::typeof(I) src::typeof(I) = ntuple(n, i-> I[i][findin(I[i], i < n ? (1:sz[i]) : (1:s))])::typeof(I) dst, src end ## Filter ## # given a function returning a boolean and an array, return matching elements filter(f::Function, As::AbstractArray) = As[map(f, As)::AbstractArray{Bool}] function filter!(f::Function, a::Vector) insrt = 1 for curr = 1:length(a) if f(a[curr]) a[insrt] = a[curr] insrt += 1 end end deleteat!(a, insrt:length(a)) return a end function filter(f::Function, a::Vector) r = Array(eltype(a), 0) for i = 1:length(a) if f(a[i]) push!(r, a[i]) end end return r end ## Transpose ## const transposebaselength=64 function transpose!(B::StridedMatrix,A::StridedMatrix) m, n = size(A) size(B) == (n,m) || throw(DimensionMismatch("transpose")) if m*n<=4*transposebaselength @inbounds begin for j = 1:n for i = 1:m B[j,i] = transpose(A[i,j]) end end end else transposeblock!(B,A,m,n,0,0) end return B end function transposeblock!(B::StridedMatrix,A::StridedMatrix,m::Int,n::Int,offseti::Int,offsetj::Int) if m*n<=transposebaselength @inbounds begin for j = offsetj+(1:n) for i = offseti+(1:m) B[j,i] = transpose(A[i,j]) end end end elseif m>n newm=m>>1 transposeblock!(B,A,newm,n,offseti,offsetj) transposeblock!(B,A,m-newm,n,offseti+newm,offsetj) else newn=n>>1 transposeblock!(B,A,m,newn,offseti,offsetj) transposeblock!(B,A,m,n-newn,offseti,offsetj+newn) end return B end function ctranspose!(B::StridedMatrix,A::StridedMatrix) m, n = size(A) size(B) == (n,m) || throw(DimensionMismatch("transpose")) if m*n<=4*transposebaselength @inbounds begin for j = 1:n for i = 1:m B[j,i] = ctranspose(A[i,j]) end end end else ctransposeblock!(B,A,m,n,0,0) end return B end function ctransposeblock!(B::StridedMatrix,A::StridedMatrix,m::Int,n::Int,offseti::Int,offsetj::Int) if m*n<=transposebaselength @inbounds begin for j = offsetj+(1:n) for i = offseti+(1:m) B[j,i] = ctranspose(A[i,j]) end end end elseif m>n newm=m>>1 ctransposeblock!(B,A,newm,n,offseti,offsetj) ctransposeblock!(B,A,m-newm,n,offseti+newm,offsetj) else newn=n>>1 ctransposeblock!(B,A,m,newn,offseti,offsetj) ctransposeblock!(B,A,m,n-newn,offseti,offsetj+newn) end return B end function transpose(A::StridedMatrix) B = similar(A, size(A, 2), size(A, 1)) transpose!(B, A) end function ctranspose(A::StridedMatrix) B = similar(A, size(A, 2), size(A, 1)) ctranspose!(B, A) end ctranspose{T<:Real}(A::StridedVecOrMat{T}) = transpose(A) transpose(x::StridedVector) = [ transpose(x[j]) for i=1, j=1:size(x,1) ] ctranspose{T}(x::StridedVector{T}) = T[ ctranspose(x[j]) for i=1, j=1:size(x,1) ] # set-like operators for vectors # These are moderately efficient, preserve order, and remove dupes. function intersect(v1, vs...) ret = Array(eltype(v1),0) for v_elem in v1 inall = true for i = 1:length(vs) if !in(v_elem, vs[i]) inall=false; break end end if inall push!(ret, v_elem) end end ret end function union(vs...) ret = Array(promote_eltype(vs...),0) seen = Set() for v in vs for v_elem in v if !in(v_elem, seen) push!(ret, v_elem) push!(seen, v_elem) end end end ret end # setdiff only accepts two args function setdiff(a, b) args_type = promote_type(eltype(a), eltype(b)) bset = Set(b) ret = Array(args_type,0) seen = Set() for a_elem in a if !in(a_elem, seen) && !in(a_elem, bset) push!(ret, a_elem) push!(seen, a_elem) end end ret end # symdiff is associative, so a relatively clean # way to implement this is by using setdiff and union, and # recursing. Has the advantage of keeping order, too, but # not as fast as other methods that make a single pass and # store counts with a Dict. symdiff(a) = a symdiff(a, b) = union(setdiff(a,b), setdiff(b,a)) symdiff(a, b, rest...) = symdiff(a, symdiff(b, rest...)) _cumsum_type{T<:Number}(v::AbstractArray{T}) = typeof(+zero(T)) _cumsum_type(v) = typeof(v[1]+v[1]) for (f, fp, op) = ((:cumsum, :cumsum_pairwise, :+), (:cumprod, :cumprod_pairwise, :*) ) # in-place cumsum of c = s+v(i1:n), using pairwise summation as for sum @eval function ($fp)(v::AbstractVector, c::AbstractVector, s, i1, n) if n < 128 @inbounds c[i1] = ($op)(s, v[i1]) for i = i1+1:i1+n-1 @inbounds c[i] = $(op)(c[i-1], v[i]) end else n2 = div(n,2) ($fp)(v, c, s, i1, n2) ($fp)(v, c, c[(i1+n2)-1], i1+n2, n-n2) end end @eval function ($f)(v::AbstractVector) n = length(v) c = $(op===:+ ? (:(similar(v,_cumsum_type(v)))) : (:(similar(v)))) if n == 0; return c; end ($fp)(v, c, $(op==:+ ? :(zero(v[1])) : :(one(v[1]))), 1, n) return c end @eval ($f)(A::AbstractArray) = ($f)(A, 1) end for (f, op) = ((:cummin, :min), (:cummax, :max)) @eval function ($f)(v::AbstractVector) n = length(v) cur_val = v[1] res = similar(v, n) res[1] = cur_val for i in 2:n cur_val = ($op)(v[i], cur_val) res[i] = cur_val end return res end @eval function ($f)(A::StridedArray, axis::Integer) dimsA = size(A) ndimsA = ndims(A) axis_size = dimsA[axis] axis_stride = 1 for i = 1:(axis-1) axis_stride *= size(A,i) end if axis_size < 1 return A end B = similar(A) for i = 1:length(A) if div(i-1, axis_stride) % axis_size == 0 B[i] = A[i] else B[i] = ($op)(A[i], B[i-axis_stride]) end end return B end @eval ($f)(A::AbstractArray) = ($f)(A, 1) end
""" Tests for login and logout. """ import datetime from unittest.mock import patch import responses import quilt3 from .utils import QuiltTestCase class TestSession(QuiltTestCase): @patch('quilt3.session.open_url') @patch('quilt3.session.input', return_value='123456') @patch('quilt3.session.login_with_token') def test_login(self, <API key>, mock_input, mock_open_url): quilt3.login() url = quilt3.session.get_registry_url() mock_open_url.assert_called_with(f'{url}/login') <API key>.assert_called_with('123456') @patch('quilt3.session._save_auth') @patch('quilt3.session._save_credentials') def <API key>(self, <API key>, mock_save_auth): url = quilt3.session.get_registry_url() mock_auth = dict( refresh_token='refresh-token', access_token='access-token', expires_at=123456789 ) self.requests_mock.add( responses.POST, f'{url}/api/token', json=mock_auth, status=200 ) self.requests_mock.add( responses.GET, f'{url}/api/auth/get_credentials', json=dict( AccessKeyId='access-key', SecretAccessKey='secret-key', SessionToken='session-token', Expiration="2019-05-28T23:58:07+00:00" ), status=200 ) quilt3.session.login_with_token('123456') mock_save_auth.assert_called_with({url: mock_auth}) <API key>.assert_called_with(dict( access_key='access-key', secret_key='secret-key', token='session-token', expiry_time="2019-05-28T23:58:07+00:00" )) @patch('quilt3.session._save_credentials') @patch('quilt3.session._load_credentials') def <API key>(self, <API key>, <API key>): def format_date(date): return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat() # Test good credentials. future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1) <API key>.return_value = dict( access_key='access-key', secret_key='secret-key', token='session-token', expiry_time=format_date(future_date) ) session = quilt3.session.<API key>() credentials = session.get_credentials() assert credentials.access_key == 'access-key' assert credentials.secret_key == 'secret-key' assert credentials.token == 'session-token' <API key>.assert_not_called() # Test expired credentials. past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5) <API key>.return_value = dict( access_key='access-key', secret_key='secret-key', token='session-token', expiry_time=format_date(past_date) ) url = quilt3.session.get_registry_url() self.requests_mock.add( responses.GET, f'{url}/api/auth/get_credentials', json=dict( AccessKeyId='access-key2', SecretAccessKey='secret-key2', SessionToken='session-token2', Expiration=format_date(future_date) ), status=200 ) session = quilt3.session.<API key>() credentials = session.get_credentials() assert credentials.access_key == 'access-key2' assert credentials.secret_key == 'secret-key2' assert credentials.token == 'session-token2' <API key>.assert_called() def test_logged_in(self): registry_url = quilt3.session.get_registry_url() other_registry_url = registry_url + 'other' mock_auth = dict( refresh_token='refresh-token', access_token='access-token', expires_at=123456789, ) with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth: assert quilt3.logged_in() == 'https://example.com' mocked_load_auth.assert_called_once() with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth: assert quilt3.logged_in() is None mocked_load_auth.assert_called_once()
package io.cattle.platform.configitem.server.model.impl; import java.io.IOException; import io.cattle.platform.configitem.server.model.<API key>; import io.cattle.platform.configitem.server.resource.ResourceRoot; import io.cattle.platform.configitem.version.<API key>; public abstract class <API key> extends AbstractConfigItem implements <API key> { ResourceRoot resourceRoot; public <API key>(String name, <API key> versionManager, ResourceRoot resourceRoot) { super(name, versionManager); this.resourceRoot = resourceRoot; } @Override public String getSourceRevision() { return resourceRoot.getSourceRevision(); } @Override public void refresh() throws IOException { resourceRoot.scan(); } public ResourceRoot getResourceRoot() { return resourceRoot; } }
import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; const BIDDER_CODE = 'gothamads'; const ACCOUNTID_MACROS = '[account_id]'; const URL_ENDPOINT = `https://us-e-node1.gothamads.com/bid?pass=${ACCOUNTID_MACROS}&integration=prebidjs`; const NATIVE_ASSET_IDS = { 0: 'title', 2: 'icon', 3: 'image', 5: 'sponsoredBy', 4: 'body', 1: 'cta' }; const NATIVE_PARAMS = { title: { id: 0, name: 'title' }, icon: { id: 2, type: 1, name: 'img' }, image: { id: 3, type: 3, name: 'img' }, sponsoredBy: { id: 5, name: 'data', type: 1 }, body: { id: 4, name: 'data', type: 2 }, cta: { id: 1, type: 12, name: 'data' } }; const NATIVE_VERSION = '1.2'; export const spec = { code: BIDDER_CODE, supportedMediaTypes: [BANNER, VIDEO, NATIVE], /** * Determines whether or not the given bid request is valid. * * @param {object} bid The bid to validate. * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: (bid) => { return Boolean(bid.params.accountId) && Boolean(bid.params.placementId) }, /** * Make a server request from the list of BidRequests. * * @param {BidRequest[]} validBidRequests A non-empty list of valid bid requests that should be sent to the Server. * @return ServerRequest Info describing the request to the server. */ buildRequests: (validBidRequests, bidderRequest) => { if (validBidRequests && validBidRequests.length === 0) return [] let accuontId = validBidRequests[0].params.accountId; const endpointURL = URL_ENDPOINT.replace(ACCOUNTID_MACROS, accuontId); let winTop = window; let location; try { location = new URL(bidderRequest.refererInfo.referer) winTop = window.top; } catch (e) { location = winTop.location; utils.logMessage(e); }; let bids = []; for (let bidRequest of validBidRequests) { let impObject = prepareImpObject(bidRequest); let data = { id: bidRequest.bidId, test: config.getConfig('debug') ? 1 : 0, cur: ['USD'], device: { w: winTop.screen.width, h: winTop.screen.height, language: (navigator && navigator.language) ? navigator.language.indexOf('-') != -1 ? navigator.language.split('-')[0] : navigator.language : '', }, site: { page: location.pathname, host: location.host }, source: { tid: bidRequest.transactionId }, regs: { coppa: config.getConfig('coppa') === true ? 1 : 0, ext: {} }, tmax: bidRequest.timeout, imp: [impObject], }; if (bidRequest.gdprConsent && bidRequest.gdprConsent.gdprApplies) { utils.deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0); utils.deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString); } if (bidRequest.uspConsent !== undefined) { utils.deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent); } bids.push(data) } return { method: 'POST', url: endpointURL, data: bids }; }, /** * Unpack the response from the server into a list of bids. * * @param {*} serverResponse A successful response from the server. * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: (serverResponse) => { if (!serverResponse || !serverResponse.body) return [] let GothamAdsResponse = serverResponse.body; let bids = []; for (let response of GothamAdsResponse) { let mediaType = response.seatbid[0].bid[0].ext && response.seatbid[0].bid[0].ext.mediaType ? response.seatbid[0].bid[0].ext.mediaType : BANNER; let bid = { requestId: response.id, cpm: response.seatbid[0].bid[0].price, width: response.seatbid[0].bid[0].w, height: response.seatbid[0].bid[0].h, ttl: response.ttl || 1200, currency: response.cur || 'USD', netRevenue: true, creativeId: response.seatbid[0].bid[0].crid, dealId: response.seatbid[0].bid[0].dealid, mediaType: mediaType }; bid.meta = {}; if (response.seatbid[0].bid[0].adomain && response.seatbid[0].bid[0].adomain.length > 0) { bid.meta.advertiserDomains = response.seatbid[0].bid[0].adomain; } switch (mediaType) { case VIDEO: bid.vastXml = response.seatbid[0].bid[0].adm; bid.vastUrl = response.seatbid[0].bid[0].ext.vastUrl; break; case NATIVE: bid.native = parseNative(response.seatbid[0].bid[0].adm); break; default: bid.ad = response.seatbid[0].bid[0].adm; } bids.push(bid); } return bids; }, }; /** * Determine type of request * * @param bidRequest * @param type * @returns {boolean} */ const checkRequestType = (bidRequest, type) => { return (typeof utils.deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined'); } const parseNative = admObject => { const { assets, link, imptrackers, jstracker } = admObject.native; const result = { clickUrl: link.url, clickTrackers: link.clicktrackers || undefined, impressionTrackers: imptrackers || undefined, javascriptTrackers: jstracker ? [jstracker] : undefined }; assets.forEach(asset => { const kind = NATIVE_ASSET_IDS[asset.id]; const content = kind && asset[NATIVE_PARAMS[kind].name]; if (content) { result[kind] = content.text || content.value || { url: content.url, width: content.w, height: content.h }; } }); return result; } const prepareImpObject = (bidRequest) => { let impObject = { id: bidRequest.transactionId, secure: 1, ext: { placementId: bidRequest.params.placementId } }; if (checkRequestType(bidRequest, BANNER)) { impObject.banner = addBannerParameters(bidRequest); } if (checkRequestType(bidRequest, VIDEO)) { impObject.video = addVideoParameters(bidRequest); } if (checkRequestType(bidRequest, NATIVE)) { impObject.native = { ver: NATIVE_VERSION, request: addNativeParameters(bidRequest) }; } return impObject }; const addNativeParameters = bidRequest => { let impObject = { id: bidRequest.transactionId, ver: NATIVE_VERSION, }; const assets = utils._map(bidRequest.mediaTypes.native, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { required: bidParams.required & 1, }; if (props) { asset.id = props.id; let wmin, hmin; let aRatios = bidParams.aspect_ratios; if (aRatios && aRatios[0]) { aRatios = aRatios[0]; wmin = aRatios.min_width || 0; hmin = aRatios.ratio_height * wmin / aRatios.ratio_width | 0; } if (bidParams.sizes) { const sizes = flatten(bidParams.sizes); wmin = sizes[0]; hmin = sizes[1]; } asset[props.name] = {} if (bidParams.len) asset[props.name]['len'] = bidParams.len; if (props.type) asset[props.name]['type'] = props.type; if (wmin) asset[props.name]['wmin'] = wmin; if (hmin) asset[props.name]['hmin'] = hmin; return asset; } }).filter(Boolean); impObject.assets = assets; return impObject } const addBannerParameters = (bidRequest) => { let bannerObject = {}; const size = parseSizes(bidRequest, 'banner'); bannerObject.w = size[0]; bannerObject.h = size[1]; return bannerObject; }; const parseSizes = (bid, mediaType) => { let mediaTypes = bid.mediaTypes; if (mediaType === 'video') { let size = []; if (mediaTypes.video && mediaTypes.video.w && mediaTypes.video.h) { size = [ mediaTypes.video.w, mediaTypes.video.h ]; } else if (Array.isArray(utils.deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { size = bid.mediaTypes.video.playerSize[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0 && Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1) { size = bid.sizes[0]; } return size; } let sizes = []; if (Array.isArray(mediaTypes.banner.sizes)) { sizes = mediaTypes.banner.sizes[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) { sizes = bid.sizes } else { utils.logWarn('no sizes are setup or found'); } return sizes } const addVideoParameters = (bidRequest) => { let videoObj = {}; let supportParamsList = ['mimes', 'minduration', 'maxduration', 'protocols', 'startdelay', 'placement', 'skip', 'skipafter', 'minbitrate', 'maxbitrate', 'delivery', 'playbackmethod', 'api', 'linearity'] for (let param of supportParamsList) { if (bidRequest.mediaTypes.video[param] !== undefined) { videoObj[param] = bidRequest.mediaTypes.video[param]; } } const size = parseSizes(bidRequest, 'video'); videoObj.w = size[0]; videoObj.h = size[1]; return videoObj; } const flatten = arr => { return [].concat(...arr); } registerBidder(spec);
<?php class <API key> extends <API key> implements <API key> { const SESS_PREFIX = 'fastindexer_'; /** * @var <API key> */ protected $_session = null; /** * @return <API key> */ public function getSession() { if (null !== $this->_session) { return $this->_session; } $this->_session = Mage::<API key>('core/session'); return $this->_session; } /** * Lock process without blocking. * This method allow protect multiple process running and fast lock validation. * */ public function lock() { $this->getSession()->write(self::SESS_PREFIX . $this->getIndexerCode(), microtime(true)); } /** * Lock and block process. * If new instance of the process will try validate locking state * script will wait until process will be unlocked * */ public function lockAndBlock() { $this->lock(); } /** * Unlock process * * @return <API key> */ public function unlock() { $this->getSession()->destroy(self::SESS_PREFIX . $this->getIndexerCode()); } /** * Check if process is locked * * @return bool */ public function isLocked() { $startTime = (double)$this->getSession()->read(self::SESS_PREFIX . $this->getIndexerCode()); if ($startTime < 0.0001) { return false; } return $this->_isLockedByTtl($startTime); } }
// immer: immutable data structures for C++ #include "fuzzer_gc_guard.hpp" #include "fuzzer_input.hpp" #include <immer/heap/gc_heap.hpp> #include <immer/refcount/no_refcount_policy.hpp> #include <immer/set.hpp> #include <immer/algorithm.hpp> #include <array> using gc_memory = immer::memory_policy<immer::heap_policy<immer::gc_heap>, immer::no_refcount_policy, immer::default_lock_policy, immer::<API key>, false>; struct colliding_hash_t { std::size_t operator()(std::size_t x) const { return x & ~15; } }; extern "C" int <API key>(const std::uint8_t* data, std::size_t size) { auto guard = fuzzer_gc_guard{}; constexpr auto var_count = 4; using set_t = immer::set<size_t, colliding_hash_t, std::equal_to<>, gc_memory>; auto vars = std::array<set_t, var_count>{}; auto is_valid_var = [&](auto idx) { return idx >= 0 && idx < var_count; }; return fuzzer_input{data, size}.run([&](auto& in) { enum ops { op_insert, op_erase, op_insert_move, op_erase_move, op_iterate }; auto src = read<char>(in, is_valid_var); auto dst = read<char>(in, is_valid_var); switch (read<char>(in)) { case op_insert: { auto value = read<size_t>(in); vars[dst] = vars[src].insert(value); break; } case op_erase: { auto value = read<size_t>(in); vars[dst] = vars[src].erase(value); break; } case op_insert_move: { auto value = read<size_t>(in); vars[dst] = std::move(vars[src]).insert(value); break; } case op_erase_move: { auto value = read<size_t>(in); vars[dst] = std::move(vars[src]).erase(value); break; } case op_iterate: { auto srcv = vars[src]; immer::for_each(srcv, [&](auto&& v) { vars[dst] = std::move(vars[dst]).insert(v); }); break; } default: break; }; return true; }); }
#!/bin/sh curl -fsLO https://raw.githubusercontent.com/scijava/scijava-scripts/master/travis-build.sh bash travis-build.sh $<API key> $<API key> && if [ ! -f release.properties ] then echo echo '== No release.properties; running integration tests ==' # Not a release -- also perform integration tests. mvn -Dinvoker.debug=true -Prun-its fi
package pod import ( "fmt" "strings" lru "github.com/hashicorp/golang-lru" "github.com/rancher/norman/api/access" "github.com/rancher/norman/types" "github.com/rancher/norman/types/values" "github.com/rancher/rancher/pkg/controllers/managementagent/workload" "github.com/rancher/rancher/pkg/ref" schema "github.com/rancher/rancher/pkg/schemas/project.cattle.io/v3" "github.com/sirupsen/logrus" ) var ( ownerCache, _ = lru.New(100000) ) type key struct { SubContext string Namespace string Kind string Name string } type value struct { Kind string Name string } func getOwnerWithKind(apiContext *types.APIContext, namespace, ownerKind, name string) (string, string, error) { subContext := apiContext.SubContext["/v3/schemas/project"] if subContext == "" { subContext = apiContext.SubContext["/v3/schemas/cluster"] } if subContext == "" { logrus.Warnf("failed to find subcontext to lookup replicaSet owner") return "", "", nil } key := key{ SubContext: subContext, Namespace: namespace, Kind: strings.ToLower(ownerKind), Name: name, } val, ok := ownerCache.Get(key) if ok { value, _ := val.(value) return value.Kind, value.Name, nil } data := map[string]interface{}{} if err := access.ByID(apiContext, &schema.Version, ownerKind, ref.FromStrings(namespace, name), &data); err != nil { return "", "", err } kind, name := getOwner(data) if !workload.WorkloadKinds[kind] { kind = "" name = "" } ownerCache.Add(key, value{ Kind: kind, Name: name, }) return kind, name, nil } func getOwner(data map[string]interface{}) (string, string) { ownerReferences, ok := values.GetSlice(data, "ownerReferences") if !ok { return "", "" } for _, ownerReference := range ownerReferences { controller, _ := ownerReference["controller"].(bool) if !controller { continue } kind, _ := ownerReference["kind"].(string) name, _ := ownerReference["name"].(string) return kind, name } return "", "" } func SaveOwner(apiContext *types.APIContext, kind, name string, data map[string]interface{}) { parentKind, parentName := getOwner(data) namespace, _ := data["namespaceId"].(string) subContext := apiContext.SubContext["/v3/schemas/project"] if subContext == "" { subContext = apiContext.SubContext["/v3/schemas/cluster"] } if subContext == "" { return } key := key{ SubContext: subContext, Namespace: namespace, Kind: strings.ToLower(kind), Name: name, } ownerCache.Add(key, value{ Kind: parentKind, Name: parentName, }) } func resolveWorkloadID(apiContext *types.APIContext, data map[string]interface{}) string { kind, name := getOwner(data) if kind == "" || !workload.WorkloadKinds[kind] { return "" } namespace, _ := data["namespaceId"].(string) if ownerKind := strings.ToLower(kind); ownerKind == workload.ReplicaSetType || ownerKind == workload.JobType { k, n, err := getOwnerWithKind(apiContext, namespace, ownerKind, name) if err != nil { return "" } if k != "" { kind, name = k, n } } return strings.ToLower(fmt.Sprintf("%s:%s:%s", kind, namespace, name)) }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (9-Debian) on Thu Sep 28 23:13:23 GMT 2017 --> <title>Uses of Interface dollar.internal.runtime.script.api.HasKeyword (dollar-script 0.4.5195 API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="date" content="2017-09-28"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> <script type="text/javascript" src="../../../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif] <script type="text/javascript" src="../../../../../../jquery/jquery-1.10.2.js"></script> <script type="text/javascript" src="../../../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface dollar.internal.runtime.script.api.HasKeyword (dollar-script 0.4.5195 API)"; } } catch(err) { } var pathtoroot = "../../../../../../";loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="fixedNav"> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?dollar/internal/runtime/script/api/class-use/HasKeyword.html" target="_top">Frames</a></li> <li><a href="HasKeyword.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><span>SEARCH:&nbsp;</span> <input type="text" id="search" value=" " disabled="disabled"> <input type="reset" id="reset" value=" " disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.top"> </a></div> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><! $('.navPadding').css('padding-top', $('.fixedNav').css("height")); </script> <div class="header"> <h2 title="Uses of Interface dollar.internal.runtime.script.api.HasKeyword" class="title">Uses of Interface<br>dollar.internal.runtime.script.api.HasKeyword</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">HasKeyword</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <th class="colFirst" scope="row"><a href="#dollar.internal.runtime.script.parser">dollar.internal.runtime.script.parser</a></th> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="dollar.internal.runtime.script.parser"> </a> <h3>Uses of <a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">HasKeyword</a> in <a href="../../../../../../dollar/internal/runtime/script/parser/package-summary.html">dollar.internal.runtime.script.parser</a></h3> <table class="useSummary" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../dollar/internal/runtime/script/parser/package-summary.html">dollar.internal.runtime.script.parser</a> that implement <a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">HasKeyword</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colSecond" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../../../dollar/internal/runtime/script/parser/KeywordDef.html" title="class in dollar.internal.runtime.script.parser">KeywordDef</a></span></code></th> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../../../dollar/internal/runtime/script/parser/Op.html" title="class in dollar.internal.runtime.script.parser">Op</a></span></code></th> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../dollar/internal/runtime/script/api/HasKeyword.html" title="interface in dollar.internal.runtime.script.api">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?dollar/internal/runtime/script/api/class-use/HasKeyword.html" target="_top">Frames</a></li> <li><a href="HasKeyword.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
import java.io.File; import java.io.FilenameFilter; class A { { new java.io.File("aaa").list(new FilenameFilter() { public boolean accept(File dir, String name) { <selection>return false; //To change body of implemented methods use File | Settings | File Templates.</selection> } }); } }
// YWUserTool.h // YiWobao #import <Foundation/Foundation.h> @class YWUser; @interface YWUserTool : NSObject + (void)saveAccount:(YWUser *)account; + (YWUser *)account; + (void)quit; @end
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_23) on Fri Nov 23 14:03:50 GMT 2012 --> <TITLE> Uses of Class org.apache.nutch.crawl.CrawlDbMerger (apache-nutch 1.6 API) </TITLE> <META NAME="date" CONTENT="2012-11-23"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.nutch.crawl.CrawlDbMerger (apache-nutch 1.6 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/nutch/crawl/CrawlDbMerger.html" title="class in org.apache.nutch.crawl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/nutch/crawl//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CrawlDbMerger.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.nutch.crawl.CrawlDbMerger</B></H2> </CENTER> No usage of org.apache.nutch.crawl.CrawlDbMerger <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/nutch/crawl/CrawlDbMerger.html" title="class in org.apache.nutch.crawl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/nutch/crawl//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CrawlDbMerger.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright &copy; 2012 The Apache Software Foundation </BODY> </HTML>
\begin{ManPage}{\label{<API key>}\Condor{cold\_start}}{1} {install and start Condor on this machine} \Synopsis \SynProg{\Condor{cold\_start}} \Opt{-help} \SynProg{\Condor{cold\_start}} \oOptArg{-basedir}{directory} \oOpt{-force} %\oOpt{-dyn} \oOpt{\Opt{-setuponly} \Bar \Opt{-runonly}} \oOptArg{-arch}{architecture} \oOptArg{-site}{repository} \oOptArg{-localdir}{directory} \oOptArg{-runlocalconfig}{file} \oOptArg{-logarchive}{archive} \oOptArg{-spoolarchive}{archive} \oOptArg{-execarchive}{archive} \oOpt{-filelock} \oOpt{-pid} \oOptArg{-artifact}{filename} \oOpt{-wget} \oOptArg{-globuslocation}{directory} \OptArg{-configfile}{file} \index{Condor commands!condor\_cold\_start} \index{Deployment commands!condor\_cold\_start} \index{condor\_cold\_start} \Description \Condor{cold\_start} installs and starts Condor on this machine, setting up or using a predefined configuration. In addition, it has the functionality to determine the local architecture if one is not specified. Additionally, this program can install pre-made \File{log}, \File{execute}, and/or \File{spool} directories by specifying the archived versions. \begin{Options} \OptItem{\OptArg{-arch}{architecturestr}}{ Use the given \Arg{architecturestr} to fetch the installation package. The string is in the format: \Sinful{condor\_version}-\Sinful{machine\_arch}-\Sinful{os\_name}-\Sinful{os\_version} (for example 6.6.7-i686-Linux-2.4). The portion of this string \Sinful{condor\_version} may be replaced with the string "latest" (for example, latest-i686-Linux-2.4) to substitute the most recent version of Condor. } \OptItem{\OptArg{-artifact}{filename}}{ Use \Arg{filename} for name of the artifact file used to determine whether the \Condor{master} daemon is still alive. } \OptItem{\OptArg{-basedir}{directory}}{ The directory to install or find the Condor executables and libraries. When not specified, the current working directory is assumed. } % \OptItem{\Opt{-dyn}}{ % Use dynamic names for the log, spool, and execute directories, as % well as the binding configuration file. This option can be used % to run multiple instances of condor in the same local directory. % This option cannot be used with \Opt{-*archive} options. The % dynamic names are created by appending the IP address and process % id of the master to the file names. % } \OptItem{\OptArg{-execarchive}{archive}}{ Create the Condor \File{execute} directory from the given \Arg{archive} file. } \OptItem{\Opt{-filelock}}{ Specifies that this program should use a POSIX file lock midwife program to create an artifact of the birth of a \Condor{master} daemon. A file lock undertaker can later be used to determine whether the \Condor{master} daemon has exited. This is the preferred option when the user wants to check the status of the \Condor{master} daemon from another machine that shares a distributed file system that supports POSIX file locking, for example, AFS. } \OptItem{\Opt{-force}}{ Overwrite previously installed files, if necessary. } \OptItem{\OptArg{-globuslocation}{directory}}{ The location of the globus installation on this machine. When not specified \File{/opt/globus} is the directory used. This option is only necessary when other options of the form \Opt{-*archive} are specified. } \OptItem{\Opt{-help}}{ Display brief usage information and exit. } \OptItem{\OptArg{-localdir}{directory}}{ The directory where the Condor \File{log}, \File{spool}, and \File{execute} directories will be installed. Each running instance of Condor must have its own local directory. % or the dynamic naming option must be enabled. } \OptItem{\OptArg{-logarchive}{archive}}{ Create the Condor log directory from the given \Arg{archive} file. } \OptItem{\Opt{-pid}}{ This program is to use a unique process id midwife program to create an artifact of the birth of a \Condor{master} daemon. A unique pid undertaker can later be used to determine whether the \Condor{master} daemon has exited. This is the default option and the preferred method to check the status of the \Condor{master} daemon from the same machine it was started on. } \OptItem{\OptArg{-runlocalconfig}{file}}{ A special local configuration file bound into the Condor configuration at runtime. This file only affects the instance of Condor started by this command. No other Condor instance sharing the same global configuration file will be affected. } \OptItem{\Opt{-runonly}}{ Run Condor from the specified installation directory without installing it. It is possible to run several instantiations of Condor from a single installation. } \OptItem{\Opt{-setuponly}}{ Install Condor without running it. } \OptItem{\OptArg{-site}{repository}}{ The ftp, http, gsiftp, or mounted file system directory where the installation packages can be found (for example, \File{www.cs.example.edu/packages/coldstart}). } \OptItem{\OptArg{-spoolarchive}{archive}}{ Create the Condor spool directory from the given \Arg{archive} file. } \OptItem{\Opt{-wget}}{ Use \Prog{wget} to fetch the \File{log}, \File{spool}, and \File{execute} directories, if other options of the form \Opt{-*archive} are specified. \Prog{wget} must be installed on the machine and in the user's path. } \OptItem{\OptArg{-configfile}{file}}{ A required option to specify the Condor configuration file to use for this installation. This file can be located on an http, ftp, or gsiftp site, or alternatively on a mounted file system. } \end{Options} \ExitStatus \Condor{cold\_start} will exit with a status value of 0 (zero) upon success, and non-zero otherwise. \Examples To start a Condor installation on the current machine, using \texttt{http: site: \footnotesize \begin{verbatim} % condor_cold_start \ -configfile http: -site http: \end{verbatim} \normalsize Optionally if this instance of Condor requires a local configuration file \File{condor\_config.local}: \footnotesize \begin{verbatim} % condor_cold_start \ -configfile http: -site http: -runlocalconfig condor_config.local \end{verbatim} \normalsize \SeeAlso \Condor{cold\_stop} (on page~\pageref{<API key>}), \Prog{filelock\_midwife} (on page~\pageref{<API key>}), \Prog{uniq\_pid\_midwife} (on page~\pageref{<API key>}). \end{ManPage}
title: 'Webapp idea: #nowplaying radio' category: Projects tags: - twitter - programming - Ruby - Ruby on Rails An oppurtunity to learn Ruby on Rails. Use a Twitter library to fetch tweets with the hashtag #nowplaying. Present the user with an interface with exactly one button: Play Parse Twitters results and fetch songs from youtube (embedded player, ajax/iframe) User clicks play, the #nowplaying radio begins. Ideas for later: add features such as result narrowing, sharing etc. I actually coded this during the day and got some insight into Rails. The coding part was actually quite easy, taking into account that I&#039;d never met Ruby before, but the real obstacle was deployment. Heroku is awesome, really, but the beginner - I - failed miserably with dependencies (twitter and youtube gems). Long story short, 2 hours of messing with git, Gemfile and bundle and I gave up. The app works, but only in localhost. Maybe I&#039;ll get help later. ![Screenshot of the now playing app]({{ site.url }}/content/2011/02/nowplaying.png)
'use strict'; /** * @class * Initializes a new instance of the <API key> class. * @constructor * A Data Lake Analytics catalog U-SQL external datasource item list. * */ class <API key> extends Array { constructor() { super(); } /** * Defines the metadata of <API key> * * @returns {object} metadata of <API key> * */ mapper() { return { required: false, serializedName: '<API key>', type: { name: 'Composite', className: '<API key>', modelProperties: { nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } }, value: { required: false, readOnly: true, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: '<API key>', type: { name: 'Composite', className: '<API key>' } } } } } } }; } } module.exports = <API key>;
{base}, Standard as ( SELECT distinct SOURCE_CODE, TARGET_CONCEPT_ID, TARGET_DOMAIN_ID, <API key>, <API key> FROM Source_to_Standard WHERE lower(<API key>) IN ('jnj_tru_p_spclty') AND (<API key> IS NOT NULL or <API key> != '') AND (<API key> IS NULL or <API key> = '') ) select distinct Standard.* from Standard
(function() { function LandingCtrl() { this.heroTitle = "Turn the Music Up!"; } angular .module('blocJams') .controller('LandingCtrl', LandingCtrl); })();
<include file="Index/header" /> <style type="text/css"> </style> <!-- START --> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 " style="padding:20px"> <if condition="$userinfo['wechat_card_num'] - $thisUser['wechat_card_num'] gt 0 " > <a class="btn btn-primary" onclick="location.href='{gr-:U('Index/add')}';"></a> <span class="text-info" >{gr-$userinfo['wechat_card_num'] - $thisUser['wechat_card_num']}</span> <else /> </if> <!-- START--> <div class=" " > <table class="table table-condensed table-bordered table-striped" border="0" cellSpacing="0" cellPadding="0" width="100%"> <thead> <tr> <th></th> <th style="text-align:center"></th> <th></th> <!-- <th>/</th> --> <!-- <th></th> --> <th></th> </tr> </thead> <tbody> <tr></tr> <volist name="info" id="vo"> <tr> <td><p><a href="{gr-:U('Function/index',array('id'=>$vo['id'],'token'=>$vo['token']))}" title=""><img src="{gr-$vo.headerpic}" width="40" height="40"></a></p><p>{gr-$vo.wxname}</p></td> <td align="center">{gr-$thisGroup.name}</td> <td>{gr-$viptime|date="Y-m-d", <td class="norightborder"> <a class="btn btn-lg btn-primary" href="{gr-:U('Function/index',array('id'=>$vo['id'],'token'=>$vo['token']))}" class="btn btn-primary" ></a> <a target="_blank" href="{gr-:U('Home/Index/bind',array('token'=>$vo['token'],'encodingaeskey'=>$vo['encodingaeskey']))}" class="btn btn-primary btn-sm" ></a> <a class="btn btn-warning btn-sm" href="{gr-:U('Index/edit',array('id'=>$vo['id']))}"><i class="<API key>"></i></a> <a href="javascript:drop_confirm('?', '{gr-:U('Index/del',array('id'=>$vo['id']))}');" class="btn btn-danger btn-sm"><i class="mdi-action-delete"></i></a> </td> </tr> </volist> </tbody> </table> </div> <!-- END--> <!-- START --> <div class="pageNavigator right"> <div class="pages"></div> </div> <!-- END--> </div> <include file="Public/footer"/>
#!/bin/bash # This script runs in a loop (configurable with LOOP), checks for updates to the # Hugo docs theme or to the docs on certain branches and rebuilds the public # folder for them. It has be made more generalized, so that we don't have to # hardcode versions. # Warning - Changes should not be made on the server on which this script is running # becauses this script does git checkout and merge. set -e GREEN='\033[32;1m' RESET='\033[0m' HOST="${HOST:-https://dgraph.io/docs/badger}" # Name of output public directory PUBLIC="${PUBLIC:-public}" # LOOP true makes this script run in a loop to check for updates LOOP="${LOOP:-true}" # Binary of hugo command to run. HUGO="${HUGO:-hugo}" # TODO - Maybe get list of released versions from Github API and filter # those which have docs. # Place the latest version at the beginning so that version selector can # append '(latest)' to the version string, followed by the master version, # and then the older versions in descending order, such that the # build script can place the artifact in an appropriate location. VERSIONS_ARRAY=( 'master' ) joinVersions() { versions=$(printf ",%s" "${VERSIONS_ARRAY[@]}") echo "${versions:1}" } function version { echo "$@" | gawk -F. '{ printf("%03d%03d%03d\n", $1,$2,$3); }'; } rebuild() { echo -e "$(date) $GREEN Updating docs for branch: $1.$RESET" # The latest documentation is generated in the root of /public dir # Older documentations are generated in their respective `/public/vx.x.x` dirs dir='' if [[ $2 != "${VERSIONS_ARRAY[0]}" ]]; then dir=$2 fi VERSION_STRING=$(joinVersions) # In Unix environments, env variables should also be exported to be seen by Hugo export CURRENT_BRANCH=${1} export CURRENT_VERSION=${2} export VERSIONS=${VERSION_STRING} HUGO_TITLE="Badger Doc ${2}"\ VERSIONS=${VERSION_STRING}\ CURRENT_BRANCH=${1}\ CURRENT_VERSION=${2} ${HUGO} \ --destination="${PUBLIC}"/"$dir"\ --baseURL="$HOST"/"$dir" 1> /dev/null } branchUpdated() { local branch="$1" git checkout -q "$1" UPSTREAM=$(git rev-parse "@{u}") LOCAL=$(git rev-parse "@") if [ "$LOCAL" != "$UPSTREAM" ] ; then git merge -q origin/"$branch" return 0 else return 1 fi } publicFolder() { dir='' if [[ $1 == "${VERSIONS_ARRAY[0]}" ]]; then echo "${PUBLIC}" else echo "${PUBLIC}/$1" fi } checkAndUpdate() { local version="$1" local branch="" if [[ $version == "master" ]]; then branch="master" else branch="release/$version" fi if branchUpdated "$branch" ; then git merge -q origin/"$branch" rebuild "$branch" "$version" fi folder=$(publicFolder "$version") if [ "$firstRun" = 1 ] || [ "$themeUpdated" = 0 ] || [ ! -d "$folder" ] ; then rebuild "$branch" "$version" fi } firstRun=1 while true; do # Lets move to the docs directory. pushd "$(dirname "$0")/.." > /dev/null currentBranch=$(git rev-parse --abbrev-ref HEAD) # Lets check if the theme was updated. pushd themes/hugo-docs > /dev/null git remote update > /dev/null themeUpdated=1 if branchUpdated "master" ; then echo -e "$(date) $GREEN Theme has been updated. Now will update the docs.$RESET" themeUpdated=0 fi popd > /dev/null # Now lets check the theme. echo -e "$(date) Starting to check branches." git remote update > /dev/null for version in "${VERSIONS_ARRAY[@]}" do checkAndUpdate "$version" done echo -e "$(date) Done checking branches.\n" git checkout -q "$currentBranch" popd > /dev/null firstRun=0 if ! $LOOP; then exit fi sleep 60 done
npm install (cd ./client/ && npm install)
<?php require_once '../autoload.php'; use Qiniu\Auth; $accessKey = 'Access_Key'; $secretKey = 'Secret_Key'; $auth = new Auth($accessKey, $secretKey); $bucket = 'Bucket_Name'; $upToken = $auth->uploadToken($bucket); echo $upToken;
package org.datavec.api.transform.transform.time; import lombok.Data; import lombok.EqualsAndHashCode; import org.datavec.api.transform.ColumnType; import org.datavec.api.transform.Transform; import org.datavec.api.transform.metadata.ColumnMetaData; import org.datavec.api.transform.metadata.IntegerMetaData; import org.datavec.api.transform.metadata.StringMetaData; import org.datavec.api.transform.metadata.TimeMetaData; import org.datavec.api.transform.schema.Schema; import org.datavec.api.util.jackson.<API key>; import org.datavec.api.util.jackson.<API key>; import org.datavec.api.writable.IntWritable; import org.datavec.api.writable.Text; import org.datavec.api.writable.Writable; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.nd4j.shade.jackson.annotation.JsonIgnore; import org.nd4j.shade.jackson.annotation.<API key>; import org.nd4j.shade.jackson.annotation.JsonInclude; import org.nd4j.shade.jackson.annotation.JsonProperty; import org.nd4j.shade.jackson.databind.annotation.JsonDeserialize; import org.nd4j.shade.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Create a number of new columns by deriving their values from a Time column. * Can be used for example to create new columns with the year, month, day, hour, minute, second etc. * * @author Alex Black */ @<API key>({"inputSchema", "insertAfterIdx", "deriveFromIdx"}) @EqualsAndHashCode(exclude = {"inputSchema", "insertAfterIdx", "deriveFromIdx"}) @Data public class <API key> implements Transform { private final String columnName; private final String insertAfter; private DateTimeZone inputTimeZone; private final List<DerivedColumn> derivedColumns; private Schema inputSchema; private int insertAfterIdx = -1; private int deriveFromIdx = -1; private <API key>(Builder builder) { this.derivedColumns = builder.derivedColumns; this.columnName = builder.columnName; this.insertAfter = builder.insertAfter; } public <API key>(@JsonProperty("columnName") String columnName, @JsonProperty("insertAfter") String insertAfter, @JsonProperty("inputTimeZone") DateTimeZone inputTimeZone, @JsonProperty("derivedColumns") List<DerivedColumn> derivedColumns) { this.columnName = columnName; this.insertAfter = insertAfter; this.inputTimeZone = inputTimeZone; this.derivedColumns = derivedColumns; } @Override public Schema transform(Schema inputSchema) { List<ColumnMetaData> oldMeta = inputSchema.getColumnMetaData(); List<ColumnMetaData> newMeta = new ArrayList<>(oldMeta.size() + derivedColumns.size()); List<String> oldNames = inputSchema.getColumnNames(); for (int i = 0; i < oldMeta.size(); i++) { String current = oldNames.get(i); newMeta.add(oldMeta.get(i)); if (insertAfter.equals(current)) { //Insert the derived columns here for (DerivedColumn d : derivedColumns) { switch (d.columnType) { case String: newMeta.add(new StringMetaData(d.columnName)); break; case Integer: newMeta.add(new IntegerMetaData(d.columnName)); //TODO: ranges... if it's a day, we know it must be 1 to 31, etc... break; default: throw new <API key>("Unexpected column type: " + d.columnType); } } } } return inputSchema.newSchema(newMeta); } @Override public void setInputSchema(Schema inputSchema) { insertAfterIdx = inputSchema.getColumnNames().indexOf(insertAfter); if (insertAfterIdx == -1) { throw new <API key>( "Invalid schema/insert after column: input schema does not contain column \"" + insertAfter + "\""); } deriveFromIdx = inputSchema.getColumnNames().indexOf(columnName); if (deriveFromIdx == -1) { throw new <API key>( "Invalid source column: input schema does not contain column \"" + columnName + "\""); } this.inputSchema = inputSchema; if (!(inputSchema.getMetaData(columnName) instanceof TimeMetaData)) throw new <API key>("Invalid state: input column \"" + columnName + "\" is not a time column. Is: " + inputSchema.getMetaData(columnName)); TimeMetaData meta = (TimeMetaData) inputSchema.getMetaData(columnName); inputTimeZone = meta.getTimeZone(); } @Override public Schema getInputSchema() { return inputSchema; } @Override public List<Writable> map(List<Writable> writables) { if (writables.size() != inputSchema.numColumns()) { throw new <API key>("Cannot execute transform: input writables list length (" + writables.size() + ") does not " + "match expected number of elements (schema: " + inputSchema.numColumns() + "). Transform = " + toString()); } int i = 0; Writable source = writables.get(deriveFromIdx); List<Writable> list = new ArrayList<>(writables.size() + derivedColumns.size()); for (Writable w : writables) { list.add(w); if (i++ == insertAfterIdx) { for (DerivedColumn d : derivedColumns) { switch (d.columnType) { case String: list.add(new Text(d.dateTimeFormatter.print(source.toLong()))); break; case Integer: DateTime dt = new DateTime(source.toLong(), inputTimeZone); list.add(new IntWritable(dt.get(d.fieldType))); break; default: throw new <API key>("Unexpected column type: " + d.columnType); } } } } return list; } @Override public List<List<Writable>> mapSequence(List<List<Writable>> sequence) { List<List<Writable>> out = new ArrayList<>(sequence.size()); for (List<Writable> step : sequence) { out.add(map(step)); } return out; } /** * Transform an object * in to another object * * @param input the record to transform * @return the transformed writable */ @Override public Object map(Object input) { List<Object> ret = new ArrayList<>(); Long l = (Long) input; for (DerivedColumn d : derivedColumns) { switch (d.columnType) { case String: ret.add(d.dateTimeFormatter.print(l)); break; case Integer: DateTime dt = new DateTime(l, inputTimeZone); ret.add(dt.get(d.fieldType)); break; default: throw new <API key>("Unexpected column type: " + d.columnType); } } return ret; } /** * Transform a sequence * * @param sequence */ @Override public Object mapSequence(Object sequence) { List<Long> longs = (List<Long>) sequence; List<List<Object>> ret = new ArrayList<>(); for (Long l : longs) ret.add((List<Object>) map(l)); return ret; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("<API key>(timeColumn=\"").append(columnName).append("\",insertAfter=\"") .append(insertAfter).append("\",derivedColumns=("); boolean first = true; for (DerivedColumn d : derivedColumns) { if (!first) sb.append(","); sb.append(d); first = false; } sb.append("))"); return sb.toString(); } /** * The output column name * after the operation has been applied * * @return the output column name */ @Override public String outputColumnName() { return outputColumnNames()[0]; } /** * The output column names * This will often be the same as the input * * @return the output column names */ @Override public String[] outputColumnNames() { String[] ret = new String[derivedColumns.size()]; for (int i = 0; i < ret.length; i++) ret[i] = derivedColumns.get(i).columnName; return ret; } /** * Returns column names * this op is meant to run on * * @return */ @Override public String[] columnNames() { return new String[] {columnName()}; } /** * Returns a singular column name * this op is meant to run on * * @return */ @Override public String columnName() { return columnName; } public static class Builder { private final String columnName; private String insertAfter; private final List<DerivedColumn> derivedColumns = new ArrayList<>(); /** * @param timeColumnName The name of the time column from which to derive the new values */ public Builder(String timeColumnName) { this.columnName = timeColumnName; this.insertAfter = timeColumnName; } /** * Where should the new columns be inserted? * By default, they will be inserted after the source column * * @param columnName Name of the column to insert the derived columns after */ public Builder insertAfter(String columnName) { this.insertAfter = columnName; return this; } public Builder <API key>(String columnName, String format, DateTimeZone timeZone) { derivedColumns.add(new DerivedColumn(columnName, ColumnType.String, format, timeZone, null)); return this; } /** * Add an integer derived column - for example, the hour of day, etc. Uses timezone from the time column metadata * * @param columnName Name of the column * @param type Type of field (for example, DateTimeFieldType.hourOfDay() etc) */ public Builder <API key>(String columnName, DateTimeFieldType type) { derivedColumns.add(new DerivedColumn(columnName, ColumnType.Integer, null, null, type)); return this; } /** * Create the transform instance */ public <API key> build() { return new <API key>(this); } } @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode(exclude = "dateTimeFormatter") @Data @<API key>({"dateTimeFormatter"}) public static class DerivedColumn implements Serializable { private final String columnName; private final ColumnType columnType; private final String format; private final DateTimeZone dateTimeZone; @JsonSerialize(using = <API key>.class) @JsonDeserialize(using = <API key>.class) private final DateTimeFieldType fieldType; private transient DateTimeFormatter dateTimeFormatter; // public DerivedColumn(String columnName, ColumnType columnType, String format, DateTimeZone dateTimeZone, DateTimeFieldType fieldType) { public DerivedColumn(@JsonProperty("columnName") String columnName, @JsonProperty("columnType") ColumnType columnType, @JsonProperty("format") String format, @JsonProperty("dateTimeZone") DateTimeZone dateTimeZone, @JsonProperty("fieldType") DateTimeFieldType fieldType) { this.columnName = columnName; this.columnType = columnType; this.format = format; this.dateTimeZone = dateTimeZone; this.fieldType = fieldType; if (format != null) dateTimeFormatter = DateTimeFormat.forPattern(this.format).withZone(dateTimeZone); } @Override public String toString() { return "(name=" + columnName + ",type=" + columnType + ",derived=" + (format != null ? format : fieldType) + ")"; } //Custom serialization methods, because Joda Time doesn't allow DateTimeFormatter objects to be serialized :( private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, <API key> { in.defaultReadObject(); if (format != null) dateTimeFormatter = DateTimeFormat.forPattern(format).withZone(dateTimeZone); } } }
package com.humbinal.ssm.test; public class User { private long user_Id; private String user_name; private int user_age; public User() { } public long getUser_Id() { return user_Id; } public void setUser_Id(long user_Id) { this.user_Id = user_Id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public int getUser_age() { return user_age; } public void setUser_age(int user_age) { this.user_age = user_age; } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_10) on Mon Feb 26 03:04:16 CET 2007 --> <TITLE> S-Index (REPSI Tool) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="S-Index (REPSI Tool)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-11.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-13.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-12.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-12.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <A HREF="index-1.html">C</A> <A HREF="index-2.html">D</A> <A HREF="index-3.html">E</A> <A HREF="index-4.html">F</A> <A HREF="index-5.html">G</A> <A HREF="index-6.html">I</A> <A HREF="index-7.html">M</A> <A HREF="index-8.html">N</A> <A HREF="index-9.html">O</A> <A HREF="index-10.html">P</A> <A HREF="index-11.html">R</A> <A HREF="index-12.html">S</A> <A HREF="index-13.html">T</A> <HR> <A NAME="_S_"></A><H2> <B>S</B></H2> <DL> <DT><A HREF="../edu/ou/weinmann/repsi/model/util/Global.html#<API key>"><B><API key></B></A> - Static variable in interface edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/Global.html" title="interface in edu.ou.weinmann.repsi.model.util">Global</A> <DD>Separator - comma, space & single quote. <DT><A HREF="../edu/ou/weinmann/repsi/model/util/Global.html#<API key>"><B><API key></B></A> - Static variable in interface edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/Global.html" title="interface in edu.ou.weinmann.repsi.model.util">Global</A> <DD>Separator - single quote, comma, space & single quote. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#setAppliedEndAction(java.util.Date, java.util.Date, long)"><B>setAppliedEndAction(Date, Date, long)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Updates in the database the columns <code><API key></code>, <code>APPLIED_END_TIME</code>, and <code>APPLIED_START_TIME</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#<API key>(java.lang.String)"><B><API key>(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Updates in the database the columns <code><API key></code> and <code>APPLIED_STATUS</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#<API key>(java.lang.String, java.lang.String)"><B><API key>(String, String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Updates in the database the columns <code><API key></code> and <code>APPLIED_STATUS</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html#setComparison(java.lang.String, java.lang.String)"><B>setComparison(String, String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html" title="class in edu.ou.weinmann.repsi.model.mapper">CalibrationMapper</A> <DD>Updates in the database the columns <code>COMPARISON_EQUALS</code> and <code>COMPARISON_MESSAGE</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#setComparison(java.lang.String, java.lang.String)"><B>setComparison(String, String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Updates in the database the columns <code>COMPARISON_EQUALS</code> and <code>COMPARISON_MESSAGE</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html#setDescription(java.lang.String)"><B>setDescription(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html" title="class in edu.ou.weinmann.repsi.model.mapper">CalibrationMapper</A> <DD>Updates in the database the columns <code>DESCRIPTION</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/TrialRunMapper.html#setDescription(java.lang.String)"><B>setDescription(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/TrialRunMapper.html" title="class in edu.ou.weinmann.repsi.model.mapper">TrialRunMapper</A> <DD>Updates in the database the columns <code>DESCRIPTION</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/trial/util/ResultSetComparator.html#setDescription(java.lang.String, int)"><B>setDescription(String, int)</B></A> - Method in class edu.ou.weinmann.repsi.model.trial.util.<A HREF="../edu/ou/weinmann/repsi/model/trial/util/ResultSetComparator.html" title="class in edu.ou.weinmann.repsi.model.trial.util">ResultSetComparator</A> <DD>Sets the description at the required position. <DT><A HREF="../edu/ou/weinmann/repsi/model/util/DatabaseAccessor.html#setFetchSize(int)"><B>setFetchSize(int)</B></A> - Method in class edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/DatabaseAccessor.html" title="class in edu.ou.weinmann.repsi.model.util">DatabaseAccessor</A> <DD>Creates a <code>Statement</code> object associtated with this <code>Connnection</code> object. <DT><A HREF="../edu/ou/weinmann/repsi/model/calibration/Calibration.html#setObject(java.lang.String)"><B>setObject(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.calibration.<A HREF="../edu/ou/weinmann/repsi/model/calibration/Calibration.html" title="class in edu.ou.weinmann.repsi.model.calibration">Calibration</A> <DD>Sets the type of the <code>Calibration</code> object. <DT><A HREF="../edu/ou/weinmann/repsi/model/trial/util/ResultSetComparator.html#setOrderBy(java.lang.String, int)"><B>setOrderBy(String, int)</B></A> - Method in class edu.ou.weinmann.repsi.model.trial.util.<A HREF="../edu/ou/weinmann/repsi/model/trial/util/ResultSetComparator.html" title="class in edu.ou.weinmann.repsi.model.trial.util">ResultSetComparator</A> <DD>Sets the order by clause at the required position. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html#<API key>(java.lang.String)"><B><API key>(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html" title="class in edu.ou.weinmann.repsi.model.mapper">CalibrationMapper</A> <DD>Updates in the database the columns <code><API key></code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/util/Configurator.html#setProperty(java.lang.String, java.lang.String)"><B>setProperty(String, String)</B></A> - Method in class edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/Configurator.html" title="class in edu.ou.weinmann.repsi.model.util">Configurator</A> <DD>sets the value of a given property key. <DT><A HREF="../edu/ou/weinmann/repsi/model/trial/util/ResultSetComparator.html#setSelectStmnt(java.lang.String, int)"><B>setSelectStmnt(String, int)</B></A> - Method in class edu.ou.weinmann.repsi.model.trial.util.<A HREF="../edu/ou/weinmann/repsi/model/trial/util/ResultSetComparator.html" title="class in edu.ou.weinmann.repsi.model.trial.util">ResultSetComparator</A> <DD>Sets the <code>SELECT</code> statement at the required position. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#<API key>(long)"><B><API key>(long)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Sets the current action sequence number. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#<API key>(long)"><B><API key>(long)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Sets the current action sequence number. <DT><A HREF="../edu/ou/weinmann/repsi/model/trial/util/ResultSetComparator.html#setSqlSyntaxCode(java.lang.String)"><B>setSqlSyntaxCode(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.trial.util.<A HREF="../edu/ou/weinmann/repsi/model/trial/util/ResultSetComparator.html" title="class in edu.ou.weinmann.repsi.model.trial.util">ResultSetComparator</A> <DD>Sets the <code>SQL</code> syntax code. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html#setSqlSyntaxCodeTqp(java.lang.String)"><B>setSqlSyntaxCodeTqp(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html" title="class in edu.ou.weinmann.repsi.model.mapper">CalibrationMapper</A> <DD>Updates in the database the columns <code><API key></code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/database/Database.html#setSqlSyntaxSource(java.lang.String)"><B>setSqlSyntaxSource(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.database.<A HREF="../edu/ou/weinmann/repsi/model/database/Database.html" title="class in edu.ou.weinmann.repsi.model.database">Database</A> <DD>Sets the type of the SQL syntax version. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html#setStatus()"><B>setStatus()</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/CalibrationMapper.html" title="class in edu.ou.weinmann.repsi.model.mapper">CalibrationMapper</A> <DD>Updates in the database the columns <code>END_TIME</code> and <code>STATUS_CODE</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/TrialRunMapper.html#setStatus(java.lang.String)"><B>setStatus(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/TrialRunMapper.html" title="class in edu.ou.weinmann.repsi.model.mapper">TrialRunMapper</A> <DD>Updates in the database the columns <code>END_TIME</code> and <code>STATUS_CODE</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#setTableName(java.lang.String)"><B>setTableName(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Updates in the database the column <code>TABLE_NAME</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#<API key>(java.util.Date, java.util.Date, long)"><B><API key>(Date, Date, long)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Updates in the database the columns <code><API key></code>, <code>UNAPPLIED_END_TIME</code>, and <code><API key></code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#<API key>(java.lang.String)"><B><API key>(String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Updates in the database the columns <code><API key></code> and <code>UNAPPLIED_STATUS</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html#<API key>(java.lang.String, java.lang.String)"><B><API key>(String, String)</B></A> - Method in class edu.ou.weinmann.repsi.model.mapper.<A HREF="../edu/ou/weinmann/repsi/model/mapper/<API key>.html" title="class in edu.ou.weinmann.repsi.model.mapper"><API key></A> <DD>Updates in the database the columns <code><API key></code> and <code>UNAPPLIED_STATUS</code>. <DT><A HREF="../edu/ou/weinmann/repsi/model/trial/metadata/Columns.html#sizeColumns()"><B>sizeColumns()</B></A> - Method in class edu.ou.weinmann.repsi.model.trial.metadata.<A HREF="../edu/ou/weinmann/repsi/model/trial/metadata/Columns.html" title="class in edu.ou.weinmann.repsi.model.trial.metadata">Columns</A> <DD>Returns the number of columns in this database table. <DT><A HREF="../edu/ou/weinmann/repsi/model/util/Global.html#<API key>"><B><API key></B></A> - Static variable in interface edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/Global.html" title="interface in edu.ou.weinmann.repsi.model.util">Global</A> <DD>SQL column type - CHAR. <DT><A HREF="../edu/ou/weinmann/repsi/model/util/Global.html#<API key>"><B><API key></B></A> - Static variable in interface edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/Global.html" title="interface in edu.ou.weinmann.repsi.model.util">Global</A> <DD>SQL column type - VARCHAR2. <DT><A HREF="../edu/ou/weinmann/repsi/model/util/Global.html#<API key>"><B><API key></B></A> - Static variable in interface edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/Global.html" title="interface in edu.ou.weinmann.repsi.model.util">Global</A> <DD>SQL syntax code - Oracle 10g Release 2. <DT><A HREF="../edu/ou/weinmann/repsi/model/util/Global.html#<API key>"><B><API key></B></A> - Static variable in interface edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/Global.html" title="interface in edu.ou.weinmann.repsi.model.util">Global</A> <DD>SQL syntax code - standard SQL:1999. <DT><A HREF="../edu/ou/weinmann/repsi/model/util/SQLRewriter.html" title="class in edu.ou.weinmann.repsi.model.util"><B>SQLRewriter</B></A> - Class in <A HREF="../edu/ou/weinmann/repsi/model/util/package-summary.html">edu.ou.weinmann.repsi.model.util</A><DD>Adapts the syntactical variations of different SQL versions by rewriting the SQL statements.<DT><A HREF="../edu/ou/weinmann/repsi/model/util/SQLRewriter.html#SQLRewriter()"><B>SQLRewriter()</B></A> - Constructor for class edu.ou.weinmann.repsi.model.util.<A HREF="../edu/ou/weinmann/repsi/model/util/SQLRewriter.html" title="class in edu.ou.weinmann.repsi.model.util">SQLRewriter</A> <DD>Constructs a <code>SQLRewriter</code> object. <DT><A HREF="../edu/ou/weinmann/repsi/model/database/Database.html#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)"><B>startElement(String, String, String, Attributes)</B></A> - Method in class edu.ou.weinmann.repsi.model.database.<A HREF="../edu/ou/weinmann/repsi/model/database/Database.html" title="class in edu.ou.weinmann.repsi.model.database">Database</A> <DD>Receive notification of the start of an element. </DL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-11.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-13.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-12.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-12.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <A HREF="index-1.html">C</A> <A HREF="index-2.html">D</A> <A HREF="index-3.html">E</A> <A HREF="index-4.html">F</A> <A HREF="index-5.html">G</A> <A HREF="index-6.html">I</A> <A HREF="index-7.html">M</A> <A HREF="index-8.html">N</A> <A HREF="index-9.html">O</A> <A HREF="index-10.html">P</A> <A HREF="index-11.html">R</A> <A HREF="index-12.html">S</A> <A HREF="index-13.html">T</A> <HR> </BODY> </HTML>
require("../base/extension_registry.js"); require("./event.js"); require("./object_snapshot.js"); require("../base/range.js"); require("../base/sorted_array_utils.js"); 'use strict'; /** * @fileoverview Provides the ObjectSnapshot and ObjectHistory classes. */ global.tr.exportTo('tr.model', function() { var ObjectSnapshot = tr.model.ObjectSnapshot; /** * An object with a specific id, whose state has been snapshotted several * times. * * @constructor */ function ObjectInstance( parent, id, category, name, creationTs, opt_baseTypeName) { tr.model.Event.call(this); this.parent = parent; this.id = id; this.category = category; this.baseTypeName = opt_baseTypeName ? opt_baseTypeName : name; this.name = name; this.creationTs = creationTs; this.<API key> = false; this.deletionTs = Number.MAX_VALUE; this.<API key> = false; this.colorId = 0; this.bounds = new tr.b.Range(); this.snapshots = []; this.<API key> = false; } ObjectInstance.prototype = { __proto__: tr.model.Event.prototype, get typeName() { return this.name; }, addBoundsToRange: function(range) { range.addRange(this.bounds); }, addSnapshot: function(ts, args, opt_name, opt_baseTypeName) { if (ts < this.creationTs) throw new Error('Snapshots must be >= instance.creationTs'); if (ts >= this.deletionTs) throw new Error('Snapshots cannot be added after ' + 'an objects deletion timestamp.'); var lastSnapshot; if (this.snapshots.length > 0) { lastSnapshot = this.snapshots[this.snapshots.length - 1]; if (lastSnapshot.ts == ts) throw new Error('Snapshots already exists at this time!'); if (ts < lastSnapshot.ts) { throw new Error( 'Snapshots must be added in increasing timestamp order'); } } // Update baseTypeName if needed. if (opt_name && (this.name != opt_name)) { if (!opt_baseTypeName) throw new Error('Must provide base type name for name update'); if (this.baseTypeName != opt_baseTypeName) throw new Error('Cannot update type name: base types dont match'); this.name = opt_name; } var snapshotConstructor = tr.model.ObjectSnapshot.getConstructor( this.category, this.name); var snapshot = new snapshotConstructor(this, ts, args); this.snapshots.push(snapshot); return snapshot; }, wasDeleted: function(ts) { var lastSnapshot; if (this.snapshots.length > 0) { lastSnapshot = this.snapshots[this.snapshots.length - 1]; if (lastSnapshot.ts > ts) throw new Error( 'Instance cannot be deleted at ts=' + ts + '. A snapshot exists that is older.'); } this.deletionTs = ts; this.<API key> = true; }, /** * See ObjectSnapshot constructor notes on object initialization. */ preInitialize: function() { for (var i = 0; i < this.snapshots.length; i++) this.snapshots[i].preInitialize(); }, /** * See ObjectSnapshot constructor notes on object initialization. */ initialize: function() { for (var i = 0; i < this.snapshots.length; i++) this.snapshots[i].initialize(); }, getSnapshotAt: function(ts) { if (ts < this.creationTs) { if (this.<API key>) throw new Error('ts must be within lifetime of this instance'); return this.snapshots[0]; } if (ts > this.deletionTs) throw new Error('ts must be within lifetime of this instance'); var snapshots = this.snapshots; var i = tr.b.<API key>( snapshots, function(snapshot) { return snapshot.ts; }, function(snapshot, i) { if (i == snapshots.length - 1) return snapshots[i].objectInstance.deletionTs; return snapshots[i + 1].ts - snapshots[i].ts; }, ts); if (i < 0) { // Note, this is a little bit sketchy: this lets early ts point at the // first snapshot, even before it is taken. We do this because raster // tasks usually post before their tile snapshots are dumped. This may // be a good line of code to re-visit if we start seeing strange and // confusing object references showing up in the traces. return this.snapshots[0]; } if (i >= this.snapshots.length) return this.snapshots[this.snapshots.length - 1]; return this.snapshots[i]; }, updateBounds: function() { this.bounds.reset(); this.bounds.addValue(this.creationTs); if (this.deletionTs != Number.MAX_VALUE) this.bounds.addValue(this.deletionTs); else if (this.snapshots.length > 0) this.bounds.addValue(this.snapshots[this.snapshots.length - 1].ts); }, <API key>: function(amount) { this.creationTs += amount; if (this.deletionTs != Number.MAX_VALUE) this.deletionTs += amount; this.snapshots.forEach(function(snapshot) { snapshot.ts += amount; }); }, get userFriendlyName() { return this.typeName + ' object ' + this.id; } }; tr.model.EventRegistry.register( ObjectInstance, { name: 'objectInstance', pluralName: 'objectInstances', <API key>: '<API key>', <API key>: '<API key>' }); var options = new tr.b.<API key>( tr.b.<API key>); options.mandatoryBaseClass = ObjectInstance; options.defaultConstructor = ObjectInstance; tr.b.<API key>(ObjectInstance, options); return { ObjectInstance: ObjectInstance }; });
package org.sakaiproject.scorm.ui.player.behaviors; import org.adl.api.ecmascript.SCORM13APIInterface; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.scorm.model.api.ScoBean; import org.sakaiproject.scorm.model.api.SessionBean; import org.sakaiproject.scorm.navigation.INavigable; import org.sakaiproject.scorm.navigation.INavigationEvent; import org.sakaiproject.scorm.service.api.<API key>; import org.sakaiproject.scorm.service.api.<API key>; public abstract class SCORM13API implements SCORM13APIInterface { private static Log log = LogFactory.getLog(SCORM13API.class); // String value of FALSE for JavaScript returns. protected static final String STRING_FALSE = "false"; // String value of TRUE for JavaScript returns. protected static final String STRING_TRUE = "true"; public abstract SessionBean getSessionBean(); public abstract <API key> <API key>(); public abstract <API key> <API key>(); public abstract ScoBean getScoBean(); public abstract INavigable getAgent(); public abstract Object getTarget(); // Implementation of SCORM13APIInterface public String Commit(String parameter) { // TODO: Disable UI controls -- or throttle them on server -- don't mess with js // Assume failure String result = STRING_FALSE; if (null == getSessionBean()) { log.error("Null run state!"); } if (<API key>().commit(parameter, getSessionBean(), getScoBean())) result = STRING_TRUE; // TODO: Enable UI controls return result; } public String GetDiagnostic(String errorCode) { return <API key>().getDiagnostic(errorCode, getSessionBean()); } public String GetErrorString(String errorCode) { return <API key>().getErrorString(errorCode, getSessionBean()); } public String GetLastError() { return <API key>().getLastError(getSessionBean()); } public String GetValue(String parameter) { return <API key>().getValue(parameter, getSessionBean(), getScoBean()); } public String Initialize(String parameter) { // Assume failure String result = STRING_FALSE; if (<API key>().initialize(parameter, getSessionBean(), getScoBean())) result = STRING_TRUE; return result; } public String SetValue(String dataModelElement, String value) { // Assume failure String result = STRING_FALSE; if (<API key>().setValue(dataModelElement, value, getSessionBean(), getScoBean())) { result = STRING_TRUE; } return result; } public String Terminate(String parameter) { // Assume failure String result = STRING_FALSE; if (null == getSessionBean()) { log.error("Null run state!"); return result; } INavigationEvent navigationEvent = <API key>().newNavigationEvent(); boolean isSuccessful = <API key>().terminate(parameter, navigationEvent, getSessionBean(), getScoBean()); if (isSuccessful) { result = STRING_TRUE; if (navigationEvent.isChoiceEvent()) { <API key>().navigate(navigationEvent.getChoiceEvent(), getSessionBean(), getAgent(), getTarget()); } else { <API key>().navigate(navigationEvent.getEvent(), getSessionBean(), getAgent(), getTarget()); } } return result; } }
import logging import re import socket from mopidy.config import validators from mopidy.internal import log, path def decode(value): if isinstance(value, bytes): value = value.decode(errors="surrogateescape") for char in ("\\", "\n", "\t"): value = value.replace( char.encode(encoding="unicode-escape").decode(), char ) return value def encode(value): if isinstance(value, bytes): value = value.decode(errors="surrogateescape") for char in ("\\", "\n", "\t"): value = value.replace( char, char.encode(encoding="unicode-escape").decode() ) return value class DeprecatedValue: pass class ConfigValue: """Represents a config key's value and how to handle it. Normally you will only be interacting with sub-classes for config values that encode either deserialization behavior and/or validation. Each config value should be used for the following actions: 1. Deserializing from a raw string and validating, raising ValueError on failure. 2. Serializing a value back to a string that can be stored in a config. 3. Formatting a value to a printable form (useful for masking secrets). :class:`None` values should not be deserialized, serialized or formatted, the code interacting with the config should simply skip None config values. """ def deserialize(self, value): """Cast raw string to appropriate type.""" return decode(value) def serialize(self, value, display=False): """Convert value back to string for saving.""" if value is None: return "" return str(value) class Deprecated(ConfigValue): """Deprecated value. Used for ignoring old config values that are no longer in use, but should not cause the config parser to crash. """ def deserialize(self, value): return DeprecatedValue() def serialize(self, value, display=False): return DeprecatedValue() class String(ConfigValue): """String value. Is decoded as utf-8 and \\n \\t escapes should work and be preserved. """ def __init__(self, optional=False, choices=None): self._required = not optional self._choices = choices def deserialize(self, value): value = decode(value).strip() validators.validate_required(value, self._required) if not value: return None validators.validate_choice(value, self._choices) return value def serialize(self, value, display=False): if value is None: return "" return encode(value) class Secret(String): """Secret string value. Is decoded as utf-8 and \\n \\t escapes should work and be preserved. Should be used for passwords, auth tokens etc. Will mask value when being displayed. """ def __init__(self, optional=False, choices=None): self._required = not optional self._choices = None # Choices doesn't make sense for secrets def serialize(self, value, display=False): if value is not None and display: return "********" return super().serialize(value, display) class Integer(ConfigValue): """Integer value.""" def __init__( self, minimum=None, maximum=None, choices=None, optional=False ): self._required = not optional self._minimum = minimum self._maximum = maximum self._choices = choices def deserialize(self, value): value = decode(value) validators.validate_required(value, self._required) if not value: return None value = int(value) validators.validate_choice(value, self._choices) validators.validate_minimum(value, self._minimum) validators.validate_maximum(value, self._maximum) return value class Boolean(ConfigValue): """Boolean value. Accepts ``1``, ``yes``, ``true``, and ``on`` with any casing as :class:`True`. Accepts ``0``, ``no``, ``false``, and ``off`` with any casing as :class:`False`. """ true_values = ("1", "yes", "true", "on") false_values = ("0", "no", "false", "off") def __init__(self, optional=False): self._required = not optional def deserialize(self, value): value = decode(value) validators.validate_required(value, self._required) if not value: return None if value.lower() in self.true_values: return True elif value.lower() in self.false_values: return False raise ValueError(f"invalid value for boolean: {value!r}") def serialize(self, value, display=False): if value is True: return "true" elif value in (False, None): return "false" else: raise ValueError(f"{value!r} is not a boolean") class List(ConfigValue): """List value. Supports elements split by commas or newlines. Newlines take presedence and empty list items will be filtered out. """ def __init__(self, optional=False): self._required = not optional def deserialize(self, value): value = decode(value) if "\n" in value: values = re.split(r"\s*\n\s*", value) else: values = re.split(r"\s*,\s*", value) values = tuple(v.strip() for v in values if v.strip()) validators.validate_required(values, self._required) return tuple(values) def serialize(self, value, display=False): if not value: return "" return "\n " + "\n ".join(encode(v) for v in value if v) class LogColor(ConfigValue): def deserialize(self, value): value = decode(value) validators.validate_choice(value.lower(), log.COLORS) return value.lower() def serialize(self, value, display=False): if value.lower() in log.COLORS: return encode(value.lower()) return "" class LogLevel(ConfigValue): """Log level value. Expects one of ``critical``, ``error``, ``warning``, ``info``, ``debug``, ``trace``, or ``all``, with any casing. """ levels = { "critical": logging.CRITICAL, "error": logging.ERROR, "warning": logging.WARNING, "info": logging.INFO, "debug": logging.DEBUG, "trace": log.TRACE_LOG_LEVEL, "all": logging.NOTSET, } def deserialize(self, value): value = decode(value) validators.validate_choice(value.lower(), self.levels.keys()) return self.levels.get(value.lower()) def serialize(self, value, display=False): lookup = {v: k for k, v in self.levels.items()} if value in lookup: return encode(lookup[value]) return "" class Hostname(ConfigValue): """Network hostname value.""" def __init__(self, optional=False): self._required = not optional def deserialize(self, value, display=False): value = decode(value).strip() validators.validate_required(value, self._required) if not value: return None socket_path = path.<API key>(value) if socket_path is not None: path_str = Path(not self._required).deserialize(socket_path) return f"unix:{path_str}" try: socket.getaddrinfo(value, None) except OSError: raise ValueError("must be a resolveable hostname or valid IP") return value class Port(Integer): """Network port value. Expects integer in the range 0-65535, zero tells the kernel to simply allocate a port for us. """ def __init__(self, choices=None, optional=False): super().__init__( minimum=0, maximum=2 ** 16 - 1, choices=choices, optional=optional ) class _ExpandedPath(str): def __new__(cls, original, expanded): return super().__new__(cls, expanded) def __init__(self, original, expanded): self.original = original class Path(ConfigValue): """File system path. The following expansions of the path will be done: - ``~`` to the current user's home directory - ``$XDG_CACHE_DIR`` according to the XDG spec - ``$XDG_CONFIG_DIR`` according to the XDG spec - ``$XDG_DATA_DIR`` according to the XDG spec - ``$XDG_MUSIC_DIR`` according to the XDG spec """ def __init__(self, optional=False): self._required = not optional def deserialize(self, value): value = decode(value).strip() expanded = path.expand_path(value) validators.validate_required(value, self._required) validators.validate_required(expanded, self._required) if not value or expanded is None: return None return _ExpandedPath(value, expanded) def serialize(self, value, display=False): if isinstance(value, _ExpandedPath): value = value.original if isinstance(value, bytes): value = value.decode(errors="surrogateescape") return value
// <API key>.h : header file #if !defined(AFX_ANYCHATCALLCENTERSERVERDLG_H__69ADA4B7_BCD7_435B_A14D_20271C905BA1__INCLUDED_) #define AFX_ANYCHATCALLCENTERSERVERDLG_H__69ADA4B7_BCD7_435B_A14D_20271C905BA1__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <list> class <API key> : public CDialog { // Construction public: <API key>(CWnd* pParent = NULL); // standard constructor public: CString m_strLogInfo; void AppendLogString(CString logstr); void InitAnyChatQueue(void); // Dialog Data //{{AFX_DATA(<API key>) enum { IDD = <API key> }; CEdit m_ctrlEditLog; CComboBox m_ComboStyle; int m_iTargetId; BOOL m_bShowUserLog; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(<API key>) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(<API key>) virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnDestroy(); afx_msg void OnButtonSendbuf(); afx_msg void OnButtonTransFile(); afx_msg void <API key>(); afx_msg void OnButtonTransBuffer(); afx_msg void OnButtonStartRecord(); afx_msg void OnButtonStopRecord(); afx_msg void OnCheckShowLog(); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnButtonKickOut(); afx_msg void OnButtonHangUp(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ANYCHATCALLCENTERSERVERDLG_H__69ADA4B7_BCD7_435B_A14D_20271C905BA1__INCLUDED_)
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_09-icedtea) on Sat Mar 30 09:57:52 CET 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>org.togglz.core.proxy (Togglz 1.1.1.Final API)</title> <meta name="date" content="2013-03-30"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../org/togglz/core/proxy/package-summary.html" target="classFrame">org.togglz.core.proxy</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="<API key>.html" title="class in org.togglz.core.proxy" target="classFrame"><API key></a></li> </ul> </div> </body> </html>
using System; using NUnit.Framework; namespace Akka.TestKit.NUnit { <summary> Assertions for NUnit </summary> public class NUnitAssertions : ITestKitAssertions { public void Fail(string format = "", params object[] args) { Assert.Fail(format, args); } public void AssertTrue(bool condition, string format = "", params object[] args) { Assert.IsTrue(condition, format, args); } public void AssertFalse(bool condition, string format = "", params object[] args) { Assert.IsFalse(condition, format, args); } public void AssertEqual<T>(T expected, T actual, string format = "", params object[] args) { Assert.AreEqual(expected, actual, format, args); } public void AssertEqual<T>(T expected, T actual, Func<T, T, bool> comparer, string format = "", params object[] args) { if (!comparer(expected, actual)) throw new AssertionException(string.Format("Assert.AreEqual failed. Expected [{0}]. Actual [{1}]. {2}", FormatValue(expected), FormatValue(actual), string.Format(format, args))); } private static string FormatValue<T>(T expected) { return ReferenceEquals(expected, null) ? "null" : expected.ToString(); } } }
#!/bin/bash set -e readonly url=http://localhost:8080 readonly tmp_file=gerrit wget --retry-connrefused --waitretry=5 --timeout=10 --tries=20 -O "/tmp/$tmp_file" "$url" head -n 4 "/tmp/$tmp_file"
#pragma once #include <aws/eks/EKS_EXPORTS.h> #include <aws/eks/model/Cluster.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class <API key>; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace EKS { namespace Model { class AWS_EKS_API <API key> { public: <API key>(); <API key>(const Aws::<API key><Aws::Utils::Json::JsonValue>& result); <API key>& operator=(const Aws::<API key><Aws::Utils::Json::JsonValue>& result); inline const Cluster& GetCluster() const{ return m_cluster; } inline void SetCluster(const Cluster& value) { m_cluster = value; } inline void SetCluster(Cluster&& value) { m_cluster = std::move(value); } inline <API key>& WithCluster(const Cluster& value) { SetCluster(value); return *this;} inline <API key>& WithCluster(Cluster&& value) { SetCluster(std::move(value)); return *this;} private: Cluster m_cluster; }; } // namespace Model } // namespace EKS } // namespace Aws
form.style { clear: both; } form.style label { width:100px; display:block; float:left; padding-top:4px; font-size:14px; color:#FFF; text-align:right; padding-right:30px; } form.style label.long { width: auto; display: inline; float:none; padding: 0; } form.style input, form.style textarea { padding:3px 6px 3px 6px; font-size:14px; background-color:#EEE; border:2px solid #999; font-family:"Trebuchet MS"; color:#0099FF; width:200px; } form.style textarea { width: 300px} form.style input.radio {width: 30px;} form.style input:focus, form.style textarea:focus { border-color:#00A8FF } form.style input.submit { color:#FFF; background-color:#0F414F; border-color:#000000; width:100px; } form.style fieldset { border:0 } form.style h2 { margin-bottom:25px; margin-top:10px; width: 60%; border-bottom: 1px dashed #00A8FF; padding-bottom: 7px; padding-left:10px; font-size:20px } .contact_l { margin-left:80px !important; margin-left: 50px; width: 250px; float:left } .contact_l img { vertical-align: middle;} .contact_d { width: 500px; float:left }
# AUTOGENERATED FILE FROM balenalib/nitrogen6x-debian:stretch-run # A few reasons for installing <API key> OpenJDK: # 1. Oracle. Licensing prevents us from redistributing the official JDK. # 2. Compiling OpenJDK also requires the JDK to be installed, and it gets # really hairy. # For some sample build times, see Debian's buildd logs: RUN apt-get update && apt-get install -y --<API key> \ bzip2 \ unzip \ xz-utils \
var header = Vue.extend({ template: '#header' }); Vue.component('my-header', header); var footer = Vue.extend({ template: '#footer' }); Vue.component('my-footer', footer); var index = Vue.extend({ template: '#index' }); var App = Vue.extend({}); var router = new VueRouter(); router.map({ '/': { component: index }, '/bar': { component: footer } }); // Now we can start the app! // The router will create an instance of App and mount to // the element matching the selector #app. router.start(App, '#app');
<data name="commentPage" th:currentPage="${param.currentPage}" th:moduleType="${param.moduleType}" th:moduleId="${param.moduleId}" th:mode="${param.mode}" th:asc="${param.asc}"/> <fragment name="" />
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web.UI.WebControls; using System.Xml; namespace OpenRiaServices.DomainServices.Server { <summary> Represents a domain operation method within a DomainService </summary> public abstract class <API key> { private DomainOperation _operation; private ReadOnlyCollection<<API key>> <API key>; private bool <API key>; private string _methodName; private Attribute _operationAttribute; private AttributeCollection _attributes; private Type _associatedType; private Type _actualReturnType; private Type _returnType; private Type _domainServiceType; private bool? _requiresValidation; private bool? <API key>; private Func<object, object> <API key>; <summary> Initializes a new instance of the <API key> class </summary> <param name="domainServiceType">The <see cref="DomainService"/> Type this operation is a member of.</param> <param name="name">The name of the operation</param> <param name="operation">The <see cref="DomainOperation"/></param> <param name="returnType">The return Type of the operation</param> <param name="parameters">The parameter definitions for the operation</param> <param name="attributes">The method level attributes for the operation</param> protected <API key>(Type domainServiceType, string name, DomainOperation operation, Type returnType, IEnumerable<<API key>> parameters, AttributeCollection attributes) { if (string.IsNullOrEmpty(name)) { throw new <API key>("name"); } if (returnType == null) { throw new <API key>("returnType"); } if (parameters == null) { throw new <API key>("parameters"); } if (attributes == null) { throw new <API key>("attributes"); } if (domainServiceType == null) { throw new <API key>("domainServiceType"); } if (operation == DomainOperation.None) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resource.<API key>, Enum.GetName(typeof(DomainOperation), operation))); } bool isTaskType = TypeUtility.IsTaskType(returnType); this._methodName = isTaskType ? RemoveAsyncFromName(name) : name; this._actualReturnType = returnType; this._returnType = isTaskType ? TypeUtility.GetTaskReturnType(returnType) : returnType; this._attributes = attributes; this._operation = operation; this._domainServiceType = domainServiceType; List<<API key>> effectiveParameters = parameters.ToList(); int paramCount = effectiveParameters.Count; if (paramCount > 0) { <API key> lastParameter = effectiveParameters[paramCount - 1]; if (lastParameter.IsOut && lastParameter.ParameterType.HasElementType && lastParameter.ParameterType.GetElementType() == typeof(int)) { this.<API key> = true; effectiveParameters = effectiveParameters.Take(paramCount - 1).ToList(); } } this.<API key> = effectiveParameters.AsReadOnly(); } <summary> Removes any trailing "Async" from the specific name. </summary> <param name="name">A name.</param> <returns>name, but without "Async" at the end</returns> private static string RemoveAsyncFromName(string name) { const string async = "Async"; if (name.EndsWith(async) && name.Length > async.Length) return name.Substring(0, name.Length - async.Length); else return name; } <summary> Gets a string value indicating the logical operation type corresponding to the current <see cref="Operation"/> value. </summary> <value> The value returned by this property is used in <see cref="System.ComponentModel.DataAnnotations.<API key>.OperationType"/> to describe the category of operation being authorized. <para>This helper property exists to avoid the overhead of <see cref="Enum.GetName"/> and to map"Custom" into "Update". These strings are not localized because they are meant to be used in authorization rules that work independent of culture. </para> </value> internal string OperationType { get { switch (this.Operation) { case DomainOperation.Query: return "Query"; case DomainOperation.Insert: return "Insert"; case DomainOperation.Update: case DomainOperation.Custom: return "Update"; case DomainOperation.Delete: return "Delete"; case DomainOperation.Invoke: return "Invoke"; default: System.Diagnostics.Debug.Fail("Unknown DomainOperation type"); return "Unknown"; } } } <summary> Gets the <see cref="DomainService"/> Type this operation is a member of. </summary> public Type DomainServiceType { get { return this._domainServiceType; } } <summary> Gets the name of the operation </summary> public string Name { get { return this._methodName; } } <summary> Gets the attribute that contains metadata about the operation. </summary> public Attribute OperationAttribute { get { this.<API key>(); return this._operationAttribute; } } <summary> Gets a value indicating whether this operation requires validation. </summary> internal bool RequiresValidation { get { if (!this._requiresValidation.HasValue) { // Determine whether this operation requires validation. this._requiresValidation = this._attributes[typeof(ValidationAttribute)] != null; if (!this._requiresValidation.Value) { this._requiresValidation = this.Parameters.Any(p => p.Attributes[typeof(ValidationAttribute)] != null); } if (!this._requiresValidation.Value) { this._requiresValidation = this.Parameters.Any(p => { // Complex parameters need to be validated if validation occurs on the // type itself. if (TypeUtility.<API key>(p.ParameterType)) { Type complexType = TypeUtility.GetElementType(p.ParameterType); MetaType metaType = MetaType.GetMetaType(complexType); return metaType.RequiresValidation; } return false; }); } } return this._requiresValidation.Value; } } <summary> Gets a value indicating whether this operation requires authorization. </summary> internal bool <API key> { get { if (!this.<API key>.HasValue) { // Determine whether this operation requires authorization. <API key> may appear on // the DomainService type as well as the <API key> method. this.<API key> = this._attributes[typeof(<API key>)] != null; if (!this.<API key>.Value) { this.<API key> = <API key>.GetDescription(this._domainServiceType).Attributes[typeof(<API key>)] != null; } } return this.<API key>.Value; } } <summary> Based on the operation type specified, create the default corresponding attribute if it hasn't been specified explicitly, and add it to the attributes collection. </summary> private void <API key>() { if (this._operationAttribute != null) { return; } bool attributeCreated = false; switch (this._operation) { case DomainOperation.Query: this._operationAttribute = this._attributes[typeof(QueryAttribute)]; if (this._operationAttribute == null) { QueryAttribute qa = new QueryAttribute(); // singleton returning query methods aren't composable qa.IsComposable = TypeUtility.FindIEnumerable(this.ReturnType) != null; this._operationAttribute = qa; attributeCreated = true; } break; case DomainOperation.Insert: this._operationAttribute = this._attributes[typeof(InsertAttribute)]; if (this._operationAttribute == null) { this._operationAttribute = new InsertAttribute(); attributeCreated = true; } break; case DomainOperation.Update: this._operationAttribute = this._attributes[typeof(UpdateAttribute)]; if (this._operationAttribute == null) { this._operationAttribute = new UpdateAttribute(); attributeCreated = true; } break; case DomainOperation.Delete: this._operationAttribute = this._attributes[typeof(DeleteAttribute)]; if (this._operationAttribute == null) { this._operationAttribute = new DeleteAttribute(); attributeCreated = true; } break; case DomainOperation.Invoke: this._operationAttribute = this._attributes[typeof(InvokeAttribute)]; if (this._operationAttribute == null) { this._operationAttribute = new InvokeAttribute(); attributeCreated = true; } break; case DomainOperation.Custom: this._operationAttribute = this._attributes[typeof(<API key>)]; if (this._operationAttribute == null) { this._operationAttribute = new <API key>(); attributeCreated = true; } break; default: break; } if (attributeCreated) { if (this._attributes == null) { this._attributes = new AttributeCollection(this._operationAttribute); } else { this._attributes = AttributeCollection.FromExisting(this._attributes, this._operationAttribute); } } } <summary> Gets the attributes for the operation </summary> public AttributeCollection Attributes { get { this.<API key>(); return this._attributes; } internal set { this._attributes = value; // need to reset computed flags that are based // on operation attributes so they will be recomputed this._requiresValidation = null; this.<API key> = null; } } <summary> Gets the return Type of the operation </summary> public Type ReturnType { get { return this._returnType; } } <summary> Gets a value indicating whether the actual return type is a Task or Task{T}. </summary> public bool IsTaskAsync { get { return TypeUtility.IsTaskType(this._actualReturnType); } } <summary> Gets the parameters of the operation </summary> public ReadOnlyCollection<<API key>> Parameters { get { return this.<API key>; } } <summary> Invokes this <see cref="<API key>" />. </summary> <param name="domainService">The <see cref="DomainService"/> instance the operation is being invoked on.</param> <param name="parameters">The parameters to pass to the method.</param> <returns>The return value of the invoked method.</returns> public abstract object Invoke(DomainService domainService, object[] parameters); <summary> Gets the type of domain operation implemented by the method. </summary> public DomainOperation Operation { get { return this._operation; } internal set { this._operation = value; } } <summary> Returns the associated Type this DomainOperation operates on. For query methods this will be the element type of the return type (or the singleton return Type), and for all other methods this will be the Type of the first method parameter. </summary> public Type AssociatedType { get { if (this._associatedType == null) { if (this.Operation == DomainOperation.Query) { Type entityType = TypeUtility.FindIEnumerable(this.ReturnType); if (entityType != null) { entityType = entityType.GetGenericArguments()[0]; } else { entityType = this.ReturnType; } this._associatedType = entityType; } else { if (this.Parameters.Count > 0) { this._associatedType = this.Parameters[0].ParameterType; } } } return this._associatedType; } } private bool <API key> { get { return this.<API key>; } } <summary> Invokes this <see cref="<API key>" />. </summary> <param name="domainService">The <see cref="DomainService"/> instance the operation is being invoked on.</param> <param name="parameters">The parameters to pass to the method.</param> <param name="totalCount">The total number of rows for the input query without any paging applied to it.</param> <returns>The return value of the invoked method.</returns> internal object Invoke(DomainService domainService, object[] parameters, out int totalCount) { if (this.<API key>) { object[] parametersWithCount = new object[parameters.Length + 1]; parameters.CopyTo(parametersWithCount, 0); parametersWithCount[parameters.Length] = 0; object result = this.Invoke(domainService, parametersWithCount); totalCount = (int)parametersWithCount[parameters.Length]; return result; } else { totalCount = DomainService.TotalCountUndefined; return this.Invoke(domainService, parameters); } } internal object UnwrapTaskResult(object result) { if (!IsTaskAsync) return result; if (<API key> == null) { if (ReturnType == typeof (void)) <API key> = UnwrapVoidResult; else { <API key> = (Func<object, object>)Delegate.CreateDelegate(typeof(Func<object, object>), typeof(<API key>).GetMethod("UnwrapGenericResult", BindingFlags.Static | BindingFlags.NonPublic) .MakeGenericMethod(this.ReturnType)); } } return <API key>(result); } private static object UnwrapVoidResult(object result) { if(result == null) throw new <API key>("Task method returned null"); ((Task) result).Wait(); return null; } private static object UnwrapGenericResult<T>(object result) { if(result == null) throw new <API key>("Task method returned null"); return ((Task<T>) result).Result; } <summary> Returns a textual description of the <see cref="<API key>"/>. </summary> <returns>A string representation of the <see cref="<API key>"/>.</returns> public override string ToString() { StringBuilder output = new StringBuilder(); output.AppendFormat(CultureInfo.InvariantCulture, "{0} {1}(", this.ReturnType, this.Name); for (int i = 0; i < this.Parameters.Count; i++) { if (i > 0) { output.Append(", "); } output.Append(this.Parameters[i].ToString()); } output.Append(')'); return output.ToString(); } } }
#ifndef <API key> #include "misc_api_kernel_2.h" #endif
package migrations import "github.com/BurntSushi/migration" func <API key>(tx migration.LimitedTx) error { _, err := tx.Exec(` ALTER TABLE containers DROP COLUMN step_location; `) if err != nil { return err } _, err = tx.Exec(` ALTER TABLE containers ADD COLUMN plan_id text; `) return err }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et cindent: */ #ifndef <API key> #define <API key> #include "BaseFilter.h" #include "MediaType.h" #include "dshow.h" #include "strmif.h" #include <string> namespace mozilla { namespace media { <API key>(IPin, __uuidof(IPin)); // Base class for DirectShow filter pins. // Implements: // * IPin // * IQualityControl // * IUnknown class DECLSPEC_UUID("<API key>") BasePin : public IPin , public IQualityControl { public: BasePin(BaseFilter* aFilter, CriticalSection* aLock, const wchar_t* aName, PIN_DIRECTION aDirection); virtual ~BasePin() {} // Reference count of the pin is actually stored on the owning filter. // So don't AddRef() the filter from the pin, else you'll create a cycle. STDMETHODIMP QueryInterface(REFIID aIId, void **aInterface); STDMETHODIMP_(ULONG) AddRef() { return mFilter->AddRef(); } STDMETHODIMP_(ULONG) Release() { return mFilter->Release(); } // IPin overrides. // Connects the pin to another pin. The pmt parameter can be NULL or a // partial media type. STDMETHODIMP Connect(IPin* aReceivePin, const AM_MEDIA_TYPE* aMediaType); //Accepts a connection from another pin. STDMETHODIMP ReceiveConnection(IPin* aConnector, const AM_MEDIA_TYPE* aMediaType); // Breaks the current pin connection. STDMETHODIMP Disconnect(); // Retrieves the pin connected to this pin. STDMETHODIMP ConnectedTo(IPin** aPin); // Retrieves the media type for the current pin connection. STDMETHODIMP ConnectionMediaType(AM_MEDIA_TYPE* aMediaType); // Retrieves information about the pin, such as the name, the owning filter, // and the direction. STDMETHODIMP QueryPinInfo(PIN_INFO* aInfo); // Retrieves the direction of the pin (input or output). STDMETHODIMP QueryDirection(PIN_DIRECTION* aDirection); // Retrieves the pin identifier. STDMETHODIMP QueryId(LPWSTR* Id); // Determines whether the pin accepts a specified media type. STDMETHODIMP QueryAccept(const AM_MEDIA_TYPE* aMediaType); // Enumerates the pin's preferred media types. STDMETHODIMP EnumMediaTypes(IEnumMediaTypes** aEnum); // Retrieves the pins that are connected internally to this pin // (within the filter). STDMETHODIMP <API key>(IPin** apPin, ULONG* aPin); // Notifies the pin that no additional data is expected. STDMETHODIMP EndOfStream(void); // IPin::BeginFlush() and IPin::EndFlush() are still pure virtual, // and must be implemented in a subclass. // Notifies the pin that media samples received after this call // are grouped as a segment. STDMETHODIMP NewSegment( REFERENCE_TIME aStartTime, REFERENCE_TIME aStopTime, double aRate); // IQualityControl overrides. // Notifies the recipient that a quality change is requested. STDMETHODIMP Notify(IBaseFilter * aSender, Quality aQuality); // Sets the IQualityControl object that will receive quality messages. STDMETHODIMP SetSink(IQualityControl* aQualitySink); // Other methods. // Sets the media type of the connection. virtual HRESULT SetMediaType(const MediaType *aMediaType); // check if the pin can support this specific proposed type and format virtual HRESULT CheckMediaType(const MediaType *) = 0; // This is called to release any resources needed for a connection. virtual HRESULT BreakConnect(); // Called when we've made a connection to another pin. Returning failure // triggers the caller to break the connection. Subclasses may want to // override this. virtual HRESULT CompleteConnect(IPin *pReceivePin); // Checks if this pin can connect to |aPin|. We expect sub classes to // override this method to support their own needs. Default implementation // simply checks that the directions of the pins do not match. virtual HRESULT CheckConnect(IPin *); // Check if our filter is currently stopped BOOL IsStopped() { return mFilter->mState == State_Stopped; }; // Moves pin to active state (running or paused). Subclasses will // override to prepare to handle data. virtual HRESULT Active(void); // Moves pin into inactive state (stopped). Releases resources associated // with handling data. Subclasses should override this. virtual HRESULT Inactive(void); // Called when Run() is called on the parent filter. Subclasses may want to // override this. virtual HRESULT Run(REFERENCE_TIME aStartTime); // Gets the supported media types for this pin. virtual HRESULT GetMediaType(int aIndex, MediaType *aMediaType); // Access name. const std::wstring& Name() { return mName; }; bool IsConnected() { return mConnectedPin != NULL; } IPin* GetConnected() { return mConnectedPin; } protected: // The pin's name, as returned by QueryPinInfo(). std::wstring mName; // Event sink for quality messages. IQualityControl *mQualitySink; // The pin which this one is connected to. IPinPtr mConnectedPin; // Direction of data flow through this pin. PIN_DIRECTION mDirection; // Media type of the pin's connection. MediaType mMediaType; // Our state lock. All state should be accessed while this is locked. mozilla::CriticalSection *mLock; // Our owning filter. BaseFilter *mFilter; // This pin attempts to connect to |aPin| with media type |aMediaType|. // If |aMediaType| is fully specified, we must attempt to connect with // that, else we just enumerate our types, then the other pin's type and // try them, filtering them using |aMediaType| if it's paritally // specificed. Used by Connect(). HRESULT AttemptConnection(IPin* aPin, const MediaType* aMediaType); // Tries to form a connection using all media types in the enumeration. HRESULT TryMediaTypes(IPin *aPin, const MediaType *aMediaType, IEnumMediaTypes *aEnum); }; <API key>(BasePin, __uuidof(BasePin)); } } #endif
'use strict'; /* global describe, it */ var fs = require('fs'); var expect = require('chai').expect; var bigrig = require('../'); describe('Big Rig', function () { it ('throws if no processes are found', function () { expect(function () { bigrig.analyze(null); }).to.throw('Zero processes (tabs) found.'); }); it ('throws if given invalid input data is given', function () { expect(function () { bigrig.analyze('wobble'); }).to.throw('Invalid trace contents; not JSON'); }); it ('throws if given a trace with extensions and strict mode is enabled', function (done) { fs.readFile('./test/data/load-extensions.json', 'utf8', function (err, data) { if (err) { throw err; } var error = 'Extensions running during capture; ' + 'see http://bit.ly/bigrig-extensions'; expect(function () { bigrig.analyze(data, { strict: true }); }).to.throw(error); done(); }); }); // TODO(paullewis) Add multiprocess test. it ('returns JSON for a file with a single process', function (done) { fs.readFile('./test/data/load.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect(jsonData).to.be.an('array'); expect(jsonData[0]).to.be.an('object'); done(); }); }); it ('generates valid JSON', function (done) { fs.readFile('./test/data/load.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); jsonData = JSON.parse(JSON.stringify(jsonData)); expect(jsonData).to.be.an('array'); done(); }); }); it ('supports timed ranges', function (done) { fs.readFile('./test/data/animation.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect(jsonData[0]).to.be.an('object'); expect(jsonData[0].title).to.equal('sideNavAnimation'); expect(jsonData[0].start).to.be.above(0); expect(jsonData[0].end).to.be.within(1179, 1180); done(); }); }); it ('correctly applies RAIL type when time range is specified', function (done) { fs.readFile('./test/data/animation.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data, { types: { 'sideNavAnimation': bigrig.ANIMATION } }); expect(jsonData[0].type).to.equal(bigrig.ANIMATION); done(); }); }); it ('correctly infers RAIL Load when time range not specified', function (done) { fs.readFile('./test/data/load.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect(jsonData[0].type).to.equal(bigrig.LOAD); expect(jsonData[0].title).to.equal('Load'); done(); }); }); it ('correctly infers RAIL Response when time range not specified', function (done) { fs.readFile('./test/data/response.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect(jsonData[0].type).to.equal(bigrig.RESPONSE); expect(jsonData[0].title).to.equal('sideNavResponse'); done(); }); }); it ('correctly infers RAIL Animation when time range not specified', function (done) { fs.readFile('./test/data/animation.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect(jsonData[0].type).to.equal(bigrig.ANIMATION); expect(jsonData[0].title).to.equal('sideNavAnimation'); done(); }); }); it ('correctly infers multiple RAIL regions', function (done) { fs.readFile('./test/data/response-animation.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect(jsonData.length).to.equal(2); expect(jsonData[0].type).to.equal(bigrig.RESPONSE); expect(jsonData[0].title).to.equal('sideNavResponse'); expect(jsonData[1].type).to.equal(bigrig.ANIMATION); expect(jsonData[1].title).to.equal('sideNavAnimation'); done(); }); }); it ('returns the correct fps for animations', function (done) { fs.readFile('./test/data/animation.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect(jsonData[0].fps).to.be.within(59, 61); done(); }); }); it ('returns the correct JS breakdown', function (done) { fs.readFile('./test/data/load.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect( jsonData[0].extendedInfo.javaScript['localhost:11080'] ).to.be.within(245, 246); expect( jsonData[0].extendedInfo.javaScript['www.google-analytics.com'] ).to.be.within(59, 60); done(); }); }); it ('correctly captures forced layouts and recalcs', function (done) { fs.readFile('./test/data/<API key>.json', 'utf8', function (err, data) { if (err) { throw err; } var jsonData = bigrig.analyze(data); expect( jsonData[0].extendedInfo.forcedRecalcs ).to.equal(1); expect( jsonData[0].extendedInfo.forcedLayouts ).to.equal(1); done(); }); }); });
package io.katharsis.jpa.meta; import java.io.Serializable; import java.util.UUID; import org.junit.Assert; import org.junit.Test; import io.katharsis.meta.model.MetaPrimitiveType; public class <API key> { @Test public void testString() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(String.class); } @Test public void testInteger() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(Integer.class); } @Test public void testShort() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(Short.class); } @Test public void testLong() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(Long.class); } @Test public void testFloat() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(Float.class); } @Test public void testDouble() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(Double.class); } @Test public void testBoolean() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(Boolean.class); } @Test public void testByte() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(Byte.class); } @Test public void testUUID() { UUID uuid = UUID.randomUUID(); MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(UUID.class); } enum TestEnum { A } @Test public void testEnum() { MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(TestEnum.class); } public static class TestObjectWithParse { int value; public static TestObjectWithParse parse(String value) { TestObjectWithParse parser = new TestObjectWithParse(); parser.value = Integer.parseInt(value); return parser; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestObjectWithParse other = (TestObjectWithParse) obj; if (value != other.value) return false; return true; } } public static class <API key> implements Serializable { int value; public <API key>() { } public <API key>(String value) { this.value = Integer.parseInt(value); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; <API key> other = (<API key>) obj; if (value != other.value) return false; return true; } } @Test public void testParse() { TestObjectWithParse value = new TestObjectWithParse(); value.value = 12; MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(TestObjectWithParse.class); } @Test public void testOther() { <API key> value = new <API key>(); value.value = 12; MetaPrimitiveType type = new MetaPrimitiveType(); type.<API key>(<API key>.class); } }
function TorneoGolfWindow(Window) { window1 = Titanium.UI.createWindow({ tabBarHidden : true, backgroundColor : "white", width : '100%', height : '100%', layout : 'vertical' }); table = Ti.UI.createTableView({ width : '90%', height : '100%' }); scrollView_1 = Titanium.UI.createView({ id : "scrollView_1", backgroundImage : '/images/background.png', height : '100%', width : '100%', layout : 'vertical' }); scrollView_1.add(table); imageViewBar = Titanium.UI.createView({ id : "imageViewBar", backgroundColor : Ti.App.Properties.getString('viewcolor'), height : 80, left : 0, top : 0, width : '100%', layout : 'horizontal' }); imageView = Titanium.UI.createImageView({ id : "imageView", image : "/images/icongolf.png", width : 60, height : 60, top : 7, right : 3 }); imageViewBar.add(imageView); labelTitulo = Titanium.UI.createLabel({ id : "labelTitulo", height : 'auto', width : '70%', text : L('golf'), font : { fontSize : '22dp' }, color : 'white', textAlign : Ti.UI.<API key> }); imageViewBar.add(labelTitulo); buttonClose = Titanium.UI.createImageView({ id : "buttonClose", image : "/images/close.png", width : 30, height : 30, top : 25 }); imageViewBar.add(buttonClose); window1.add(imageViewBar); window1.add(scrollView_1); function populateTable() { var data = []; var row = Titanium.UI.createTableViewRow({ id : 2, title : 'Horarios', leftImage : '/images/horarios.png', isparent : true, opened : false, hasChild : false, font : { fontSize : '22dp' }, color : 'black' }); data.push(row); var row = Titanium.UI.createTableViewRow({ id : 3, title : 'Mapa', leftImage : '/images/mapa.png', isparent : true, opened : false, hasChild : false, font : { fontSize : '22dp' }, color : 'black' }); data.push(row); table.setData(data); } populateTable(); table.addEventListener('click', function(e) { if (e.rowData.id == 2) { var Window; var mainWindow = require("ui/handheld/golf/HorariosWindow"); new mainWindow(Window).open(); } else if (e.rowData.id == 3) { var Window; var mainWindow = require("ui/handheld/mapa/MapaWindow"); new mainWindow(Window).open(); } }); buttonClose.addEventListener('click', function(e) { Ti.Media.vibrate(); var Window; var mainWindow = require("ui/handheld/MainWindow"); new mainWindow(Window).open(); }); window1.addEventListener('android:back', function(e) { Ti.Media.vibrate(); var Window; var mainWindow = require("ui/handheld/MainWindow"); new mainWindow(Window).open(); }); return window1; } module.exports = TorneoGolfWindow;
#ifndef CP_NETWORK_H #define CP_NETWORK_H #ifdef __cplusplus extern "C" { #endif #define <API key> 4096 #define CP_MAX_EVENT 1024 #define CP_BUFFER_SIZE (1024*1024) #define CP_MAX_UINT 4294967295 #define EPOLL_CLOSE 10 #define CP_CLIENT_EOF_STR "\r\n^CON^eof\r\n" #define CP_TOO_MANY_CON "not enough con" #define CP_TOO_MANY_CON_ERR "ERROR!not enough con" #define <API key> "ERROR!the connection object create in parent process and use in multi process,please create in every process" #define CP_CLIENT_EOF_LEN strlen(CP_CLIENT_EOF_STR) #define <API key> "CON_SUCCESS!" #define CP_HEADER_ERROR "ERROR!" #define CP_PDO_HEADER_STATE "PDOStatement!" #define CP_RELEASE_HEADER "r" #define <API key> 1 typedef int (*epoll_wait_handle)(int fd); int cpEpoll_add(int epfd, int fd, int fdtype); int cpEpoll_set(int fd, int fdtype); int cpEpoll_del(int epfd, int fd); int cpEpoll_wait(epoll_wait_handle*, struct timeval *timeo, int epfd); void cpEpoll_free(); CPINLINE int cpEpoll_event_set(int fdtype); #ifdef __cplusplus } #endif #endif /* NETWORK_H */
<div id="<API key>" style="width:711px"> <h1 class="<API key>">Confirm Node Fail Over for {{<API key>.node.hostname}}</h1> <div> <div mn-spinner="<API key>.viewLoading"> <div class="pas_20"> <div class="failover_warning pat_20"> <div ng-show="!<API key>.status.down && !<API key>.status.dataless"> <h2>Fail Over Options</h2> <label> <input type="radio" name="failOver" ng-model="<API key>.status.failOver" value="<API key>" ng-disabled="!<API key>.status.<API key>"> <span>Graceful Fail Over (default).</span> </label> <label> <input type="radio" name="failOver" ng-model="<API key>.status.failOver" value="failOver"> <span>Hard Fail Over - If you use hard failover option on a functioning node it may result in data loss. This is because failover will immediately remove the node from the cluster and any data that has not yet been replicated to other nodes may be permanently lost if it had not been persisted to disk.</span> </label> <div class="warning <API key>" style="margin-bottom: 15px;" ng-if="!<API key>.status.<API key>"> <strong>Attention</strong> – Graceful fail over option is not available either because node is unreachable or replica vbucket cannot be activated gracefully. </div> <div class="warning js_warning" style="margin-top: 15px;" ng-show="<API key>.status.backfill && (<API key>.status.failOver === 'failOver')"> <strong>Attention</strong> – A significant amount of data stored on this node does not yet have replica (backup) copies! Failing over the node now will irrecoverably lose that data when the incomplete replica is activated and this node is removed from the cluster. It is recommended to select "Remove Server" and rebalance to safely remove the node without any data loss. <label> <input type="checkbox" name="confirmation" ng-model="<API key>.status.confirmation"> Please confirm Failover. </label> </div> <div class="warning js_warning" style="margin-top: 15px;" ng-show="!<API key>.status.backfill && (<API key>.status.failOver === 'failOver')"> <strong>Warning</strong> – Failing over the node will remove it from the cluster and activate a replica. Operations currently in flight and not yet replicated, will be lost. Rebalancing will be required to add the node back into the cluster. Consider using "Remove from Cluster" and rebalancing instead of Failover, to avoid any loss of data. Please confirm Failover. </div> </div> <div ng-show="<API key>.status.down && !<API key>.status.dataless"> <div class="warning" ng-show="<API key>.status.backfill"> <strong>Attention</strong> – There are not replica (backup) copies of all data on this node! Failing over the node now will irrecoverably lose that data when the incomplete replica is activated and this node is removed from the cluster. If the node might come back online, it is recommended to wait. Check this box if you want to failover the node, despite the resulting data loss <label> <input type="checkbox" name="confirmation" ng-model="<API key>.status.confirmation"> Please confirm Failover.</label> </div> <div class="warning" ng-show="!<API key>.status.backfill"> <strong>Warning</strong> – Failing over the node will remove it from the cluster and activate a replica. Operations not replicated before the node became unresponsive, will be lost. Rebalancing will be required to add the node back into the cluster. Please confirm Failover. </div> </div> <div class="failover_warning pat_20" ng-if="<API key>.status.dataless"> <div class="warning"> <strong>Note</strong> – Failing over this node (which has no data) will remove it from the cluster. Rebalancing will be required to add the node back into the cluster. Please confirm Failover. </div> </div> </div> </div> <div class="right save_cancel"> <button type="submit" class="save_button float_right" ng-click="<API key>.onSubmit()" ng-model="button" ng-disabled="<API key>.<API key>()">Fail Over</button> <a class="close <API key> cancel_button float_right" ng-click="$dismiss()">Cancel</a> </div> </div> </div> </div>
package eu.atos.sla.dao.jpa; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.<API key>; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import eu.atos.sla.dao.ITemplateDAO; import eu.atos.sla.datamodel.ITemplate; import eu.atos.sla.datamodel.bean.Template; @Repository("TemplateRepository") public class TemplateDAOJpa implements ITemplateDAO { private static Logger logger = LoggerFactory.getLogger(TemplateDAOJpa.class); private EntityManager entityManager; @PersistenceContext(unitName = "slarepositoryDB") public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } public EntityManager getEntityManager() { return entityManager; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public Template getById(Long id) { return entityManager.find(Template.class, id); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public Template getByUuid(String uuid) { try { Query query = entityManager .createNamedQuery(Template.QUERY_FIND_BY_UUID); query.setParameter("uuid", uuid); Template template = null; template = (Template) query.getSingleResult(); return template; } catch (NoResultException e) { logger.debug("No Result found: " + e); return null; } } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public List<ITemplate> search(String providerId, String []serviceIds) { TypedQuery<ITemplate> query = entityManager.createNamedQuery( Template.QUERY_SEARCH, ITemplate.class); query.setParameter("providerId", providerId); query.setParameter("serviceIds", (serviceIds!=null)?Arrays.asList(serviceIds):null); query.setParameter("flagServiceIds", (serviceIds!=null)?"flag":null); logger.debug("providerId:{} - serviceIds:{}" , providerId, (serviceIds!=null)?Arrays.asList(serviceIds):null); List<ITemplate> templates = new ArrayList<ITemplate>(); templates = (List<ITemplate>) query.getResultList(); if (templates != null) { logger.debug("Number of templates:" + templates.size()); } else { logger.debug("No Result found."); } return templates; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public List<ITemplate> getByAgreement(String agreement) { TypedQuery<ITemplate> query = entityManager.createNamedQuery( Template.<API key>, ITemplate.class); query.setParameter("agreement", agreement); List<ITemplate> templates = new ArrayList<ITemplate>(); templates = (List<ITemplate>) query.getResultList(); if (templates != null) { logger.debug("Number of templates:" + templates.size()); } else { logger.debug("No Result found."); } return templates; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public List<ITemplate> getAll() { TypedQuery<ITemplate> query = entityManager.createNamedQuery( Template.QUERY_FIND_ALL, ITemplate.class); List<ITemplate> templates = new ArrayList<ITemplate>(); templates = (List<ITemplate>) query.getResultList(); if (templates != null) { logger.debug("Number of templates:" + templates.size()); } else { logger.debug("No Result found."); } return templates; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public ITemplate save(ITemplate template) { logger.info("template.getUuid() "+template.getUuid()); entityManager.persist(template); entityManager.flush(); return template; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public boolean update(String uuid, ITemplate template) { Template templateDB = null; try { Query query = entityManager.createNamedQuery(Template.QUERY_FIND_BY_UUID); query.setParameter("uuid", uuid); templateDB = (Template)query.getSingleResult(); } catch (NoResultException e) { logger.debug("No Result found: " + e); } if (templateDB!=null){ template.setId(templateDB.getId()); logger.info("template to update with id"+template.getId()); entityManager.merge(template); entityManager.flush(); }else return false; return true; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public boolean delete(ITemplate template) { try { Template templateDeleted = entityManager.getReference(Template.class, template.getId()); entityManager.remove(templateDeleted); entityManager.flush(); return true; } catch (<API key> e) { logger.debug("Template[{}] not found", template.getId()); return false; } } }
(function (root, undefined) { // ReadOnly Function var Functions = { Identity: function (x) { return x; }, True: function () { return true; }, Blank: function () { } }; // const Type var Types = { Boolean: typeof true, Number: typeof 0, String: typeof "", Object: typeof {}, Undefined: typeof undefined, Function: typeof function () { } }; // private utility methods var Utils = { // Create anonymous function from lambda expression string createLambda: function (expression) { if (expression == null) return Functions.Identity; if (typeof expression == Types.String) { if (expression == "") { return Functions.Identity; } else if (expression.indexOf("=>") == -1) { var regexp = new RegExp("[$]+", "g"); var maxLength = 0; var match; while (match = regexp.exec(expression)) { var paramNumber = match[0].length; if (paramNumber > maxLength) { maxLength = paramNumber; } } var argArray = []; for (var i = 1; i <= maxLength; i++) { var dollar = ""; for (var j = 0; j < i; j++) { dollar += "$"; } argArray.push(dollar); } var args = Array.prototype.join.call(argArray, ","); return new Function(args, "return " + expression); } else { var expr = expression.match(/^[(\s]*([^()]*?)[)\s]*=>(.*)/); return new Function(expr[1], "return " + expr[2]); } } return expression; }, isIEnumerable: function (obj) { if (typeof Enumerator !== Types.Undefined) { try { new Enumerator(obj); // check JScript(IE)'s Enumerator return true; } catch (e) { } } return false; }, // IE8's defineProperty is defined but cannot use, therefore check defineProperties defineProperty: (Object.defineProperties != null) ? function (target, methodName, value) { Object.defineProperty(target, methodName, { enumerable: false, configurable: true, writable: true, value: value }) } : function (target, methodName, value) { target[methodName] = value; }, compare: function (a, b) { return (a === b) ? 0 : (a > b) ? 1 : -1; }, dispose: function (obj) { if (obj != null) obj.dispose(); } }; // IEnumerator State var State = { Before: 0, Running: 1, After: 2 }; // "Enumerator" is conflict JScript's "Enumerator" var IEnumerator = function (initialize, tryGetNext, dispose) { var yielder = new Yielder(); var state = State.Before; this.current = yielder.current; this.moveNext = function () { try { switch (state) { case State.Before: state = State.Running; initialize(); // fall through case State.Running: if (tryGetNext.apply(yielder)) { return true; } else { this.dispose(); return false; } case State.After: return false; } } catch (e) { this.dispose(); throw e; } }; this.dispose = function () { if (state != State.Running) return; try { dispose(); } finally { state = State.After; } }; }; // for tryGetNext var Yielder = function () { var current = null; this.current = function () { return current; }; this.yieldReturn = function (value) { current = value; return true; }; this.yieldBreak = function () { return false; }; }; // Enumerable constuctor var Enumerable = function (getEnumerator) { this.getEnumerator = getEnumerator; }; // Utility Enumerable.Utils = {}; // container Enumerable.Utils.createLambda = function (expression) { return Utils.createLambda(expression); }; Enumerable.Utils.createEnumerable = function (getEnumerator) { return new Enumerable(getEnumerator); }; Enumerable.Utils.createEnumerator = function (initialize, tryGetNext, dispose) { return new IEnumerator(initialize, tryGetNext, dispose); }; Enumerable.Utils.extendTo = function (type) { var typeProto = type.prototype; var enumerableProto; if (type === Array) { enumerableProto = ArrayEnumerable.prototype; Utils.defineProperty(typeProto, "getSource", function () { return this; }); } else { enumerableProto = Enumerable.prototype; Utils.defineProperty(typeProto, "getEnumerator", function () { return Enumerable.from(this).getEnumerator(); }); } for (var methodName in enumerableProto) { var func = enumerableProto[methodName]; // already extended if (typeProto[methodName] == func) continue; // already defined(example Array#reverse/join/forEach...) if (typeProto[methodName] != null) { methodName = methodName + "ByLinq"; if (typeProto[methodName] == func) continue; // recheck } if (func instanceof Function) { Utils.defineProperty(typeProto, methodName, func); } } }; // Generator Enumerable.choice = function () // variable argument { var args = arguments; return new Enumerable(function () { return new IEnumerator( function () { args = (args[0] instanceof Array) ? args[0] : (args[0].getEnumerator != null) ? args[0].toArray() : args; }, function () { return this.yieldReturn(args[Math.floor(Math.random() * args.length)]); }, Functions.Blank); }); }; Enumerable.cycle = function () // variable argument { var args = arguments; return new Enumerable(function () { var index = 0; return new IEnumerator( function () { args = (args[0] instanceof Array) ? args[0] : (args[0].getEnumerator != null) ? args[0].toArray() : args; }, function () { if (index >= args.length) index = 0; return this.yieldReturn(args[index++]); }, Functions.Blank); }); }; Enumerable.empty = function () { return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return false; }, Functions.Blank); }); }; Enumerable.from = function (obj) { if (obj == null) { return Enumerable.empty(); } if (obj instanceof Enumerable) { return obj; } if (typeof obj == Types.Number || typeof obj == Types.Boolean) { return Enumerable.repeat(obj, 1); } if (typeof obj == Types.String) { return new Enumerable(function () { var index = 0; return new IEnumerator( Functions.Blank, function () { return (index < obj.length) ? this.yieldReturn(obj.charAt(index++)) : false; }, Functions.Blank); }); } if (typeof obj != Types.Function) { // array or array like object if (typeof obj.length == Types.Number) { return new ArrayEnumerable(obj); } // JScript's IEnumerable if (!(obj instanceof Object) && Utils.isIEnumerable(obj)) { return new Enumerable(function () { var isFirst = true; var enumerator; return new IEnumerator( function () { enumerator = new Enumerator(obj); }, function () { if (isFirst) isFirst = false; else enumerator.moveNext(); return (enumerator.atEnd()) ? false : this.yieldReturn(enumerator.item()); }, Functions.Blank); }); } // WinMD IIterable<T> if (typeof Windows === Types.Object && typeof obj.first === Types.Function) { return new Enumerable(function () { var isFirst = true; var enumerator; return new IEnumerator( function () { enumerator = obj.first(); }, function () { if (isFirst) isFirst = false; else enumerator.moveNext(); return (enumerator.hasCurrent) ? this.yieldReturn(enumerator.current) : this.yieldBreak(); }, Functions.Blank); }); } } // case function/object : Create keyValuePair[] return new Enumerable(function () { var array = []; var index = 0; return new IEnumerator( function () { for (var key in obj) { var value = obj[key]; if (!(value instanceof Function) && Object.prototype.hasOwnProperty.call(obj, key)) { array.push({ key: key, value: value }); } } }, function () { return (index < array.length) ? this.yieldReturn(array[index++]) : false; }, Functions.Blank); }); }, Enumerable.make = function (element) { return Enumerable.repeat(element, 1); }; // Overload:function(input, pattern) // Overload:function(input, pattern, flags) Enumerable.matches = function (input, pattern, flags) { if (flags == null) flags = ""; if (pattern instanceof RegExp) { flags += (pattern.ignoreCase) ? "i" : ""; flags += (pattern.multiline) ? "m" : ""; pattern = pattern.source; } if (flags.indexOf("g") === -1) flags += "g"; return new Enumerable(function () { var regex; return new IEnumerator( function () { regex = new RegExp(pattern, flags); }, function () { var match = regex.exec(input); return (match) ? this.yieldReturn(match) : false; }, Functions.Blank); }); }; // Overload:function(start, count) // Overload:function(start, count, step) Enumerable.range = function (start, count, step) { if (step == null) step = 1; return new Enumerable(function () { var value; var index = 0; return new IEnumerator( function () { value = start - step; }, function () { return (index++ < count) ? this.yieldReturn(value += step) : this.yieldBreak(); }, Functions.Blank); }); }; // Overload:function(start, count) // Overload:function(start, count, step) Enumerable.rangeDown = function (start, count, step) { if (step == null) step = 1; return new Enumerable(function () { var value; var index = 0; return new IEnumerator( function () { value = start + step; }, function () { return (index++ < count) ? this.yieldReturn(value -= step) : this.yieldBreak(); }, Functions.Blank); }); }; // Overload:function(start, to) // Overload:function(start, to, step) Enumerable.rangeTo = function (start, to, step) { if (step == null) step = 1; if (start < to) { return new Enumerable(function () { var value; return new IEnumerator( function () { value = start - step; }, function () { var next = value += step; return (next <= to) ? this.yieldReturn(next) : this.yieldBreak(); }, Functions.Blank); }); } else { return new Enumerable(function () { var value; return new IEnumerator( function () { value = start + step; }, function () { var next = value -= step; return (next >= to) ? this.yieldReturn(next) : this.yieldBreak(); }, Functions.Blank); }); } }; // Overload:function(element) // Overload:function(element, count) Enumerable.repeat = function (element, count) { if (count != null) return Enumerable.repeat(element).take(count); return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return this.yieldReturn(element); }, Functions.Blank); }); }; Enumerable.repeatWithFinalize = function (initializer, finalizer) { initializer = Utils.createLambda(initializer); finalizer = Utils.createLambda(finalizer); return new Enumerable(function () { var element; return new IEnumerator( function () { element = initializer(); }, function () { return this.yieldReturn(element); }, function () { if (element != null) { finalizer(element); element = null; } }); }); }; // Overload:function(func) // Overload:function(func, count) Enumerable.generate = function (func, count) { if (count != null) return Enumerable.generate(func).take(count); func = Utils.createLambda(func); return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return this.yieldReturn(func()); }, Functions.Blank); }); }; // Overload:function() // Overload:function(start) // Overload:function(start, step) Enumerable.toInfinity = function (start, step) { if (start == null) start = 0; if (step == null) step = 1; return new Enumerable(function () { var value; return new IEnumerator( function () { value = start - step; }, function () { return this.yieldReturn(value += step); }, Functions.Blank); }); }; // Overload:function() // Overload:function(start) // Overload:function(start, step) Enumerable.toNegativeInfinity = function (start, step) { if (start == null) start = 0; if (step == null) step = 1; return new Enumerable(function () { var value; return new IEnumerator( function () { value = start + step; }, function () { return this.yieldReturn(value -= step); }, Functions.Blank); }); }; Enumerable.unfold = function (seed, func) { func = Utils.createLambda(func); return new Enumerable(function () { var isFirst = true; var value; return new IEnumerator( Functions.Blank, function () { if (isFirst) { isFirst = false; value = seed; return this.yieldReturn(value); } value = func(value); return this.yieldReturn(value); }, Functions.Blank); }); }; Enumerable.defer = function (enumerableFactory) { return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = Enumerable.from(enumerableFactory()).getEnumerator(); }, function () { return (enumerator.moveNext()) ? this.yieldReturn(enumerator.current()) : this.yieldBreak(); }, function () { Utils.dispose(enumerator); }); }); }; // Extension Methods /* Projection and Filtering Methods */ // Overload:function(func) // Overload:function(func, resultSelector<element>) // Overload:function(func, resultSelector<element, nestLevel>) Enumerable.prototype.<API key> = function (func, resultSelector) { var source = this; func = Utils.createLambda(func); resultSelector = Utils.createLambda(resultSelector); return new Enumerable(function () { var enumerator; var nestLevel = 0; var buffer = []; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (true) { if (enumerator.moveNext()) { buffer.push(enumerator.current()); return this.yieldReturn(resultSelector(enumerator.current(), nestLevel)); } var next = Enumerable.from(buffer).selectMany(function (x) { return func(x); }); if (!next.any()) { return false; } else { nestLevel++; buffer = []; Utils.dispose(enumerator); enumerator = next.getEnumerator(); } } }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(func) // Overload:function(func, resultSelector<element>) // Overload:function(func, resultSelector<element, nestLevel>) Enumerable.prototype.traverseDepthFirst = function (func, resultSelector) { var source = this; func = Utils.createLambda(func); resultSelector = Utils.createLambda(resultSelector); return new Enumerable(function () { var enumeratorStack = []; var enumerator; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (true) { if (enumerator.moveNext()) { var value = resultSelector(enumerator.current(), enumeratorStack.length); enumeratorStack.push(enumerator); enumerator = Enumerable.from(func(enumerator.current())).getEnumerator(); return this.yieldReturn(value); } if (enumeratorStack.length <= 0) return false; Utils.dispose(enumerator); enumerator = enumeratorStack.pop(); } }, function () { try { Utils.dispose(enumerator); } finally { Enumerable.from(enumeratorStack).forEach(function (s) { s.dispose(); }); } }); }); }; Enumerable.prototype.flatten = function () { var source = this; return new Enumerable(function () { var enumerator; var middleEnumerator = null; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (true) { if (middleEnumerator != null) { if (middleEnumerator.moveNext()) { return this.yieldReturn(middleEnumerator.current()); } else { middleEnumerator = null; } } if (enumerator.moveNext()) { if (enumerator.current() instanceof Array) { Utils.dispose(middleEnumerator); middleEnumerator = Enumerable.from(enumerator.current()) .selectMany(Functions.Identity) .flatten() .getEnumerator(); continue; } else { return this.yieldReturn(enumerator.current()); } } return false; } }, function () { try { Utils.dispose(enumerator); } finally { Utils.dispose(middleEnumerator); } }); }); }; Enumerable.prototype.pairwise = function (selector) { var source = this; selector = Utils.createLambda(selector); return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.getEnumerator(); enumerator.moveNext(); }, function () { var prev = enumerator.current(); return (enumerator.moveNext()) ? this.yieldReturn(selector(prev, enumerator.current())) : false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(func) // Overload:function(seed,func<value,element>) Enumerable.prototype.scan = function (seed, func) { var isUseSeed; if (func == null) { func = Utils.createLambda(seed); // arguments[0] isUseSeed = false; } else { func = Utils.createLambda(func); isUseSeed = true; } var source = this; return new Enumerable(function () { var enumerator; var value; var isFirst = true; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { if (isFirst) { isFirst = false; if (!isUseSeed) { if (enumerator.moveNext()) { return this.yieldReturn(value = enumerator.current()); } } else { return this.yieldReturn(value = seed); } } return (enumerator.moveNext()) ? this.yieldReturn(value = func(value, enumerator.current())) : false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(selector<element>) // Overload:function(selector<element,index>) Enumerable.prototype.select = function (selector) { selector = Utils.createLambda(selector); if (selector.length <= 1) { return new <API key>(this, null, selector); } else { var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { return (enumerator.moveNext()) ? this.yieldReturn(selector(enumerator.current(), index++)) : false; }, function () { Utils.dispose(enumerator); }); }); } }; // Overload:function(collectionSelector<element>) // Overload:function(collectionSelector<element,index>) // Overload:function(collectionSelector<element>,resultSelector) // Overload:function(collectionSelector<element,index>,resultSelector) Enumerable.prototype.selectMany = function (collectionSelector, resultSelector) { var source = this; collectionSelector = Utils.createLambda(collectionSelector); if (resultSelector == null) resultSelector = function (a, b) { return b; }; resultSelector = Utils.createLambda(resultSelector); return new Enumerable(function () { var enumerator; var middleEnumerator = undefined; var index = 0; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { if (middleEnumerator === undefined) { if (!enumerator.moveNext()) return false; } do { if (middleEnumerator == null) { var middleSeq = collectionSelector(enumerator.current(), index++); middleEnumerator = Enumerable.from(middleSeq).getEnumerator(); } if (middleEnumerator.moveNext()) { return this.yieldReturn(resultSelector(enumerator.current(), middleEnumerator.current())); } Utils.dispose(middleEnumerator); middleEnumerator = null; } while (enumerator.moveNext()); return false; }, function () { try { Utils.dispose(enumerator); } finally { Utils.dispose(middleEnumerator); } }); }); }; // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) Enumerable.prototype.where = function (predicate) { predicate = Utils.createLambda(predicate); if (predicate.length <= 1) { return new WhereEnumerable(this, predicate); } else { var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (enumerator.moveNext()) { if (predicate(enumerator.current(), index++)) { return this.yieldReturn(enumerator.current()); } } return false; }, function () { Utils.dispose(enumerator); }); }); } }; // Overload:function(selector<element>) // Overload:function(selector<element,index>) Enumerable.prototype.choose = function (selector) { selector = Utils.createLambda(selector); var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (enumerator.moveNext()) { var result = selector(enumerator.current(), index++); if (result != null) { return this.yieldReturn(result); } } return this.yieldBreak(); }, function () { Utils.dispose(enumerator); }); }); }; Enumerable.prototype.ofType = function (type) { var typeName; switch (type) { case Number: typeName = Types.Number; break; case String: typeName = Types.String; break; case Boolean: typeName = Types.Boolean; break; case Function: typeName = Types.Function; break; default: typeName = null; break; } return (typeName === null) ? this.where(function (x) { return x instanceof type; }) : this.where(function (x) { return typeof x === typeName; }); }; // mutiple arguments, last one is selector, others are enumerable Enumerable.prototype.zip = function () { var args = arguments; var selector = Utils.createLambda(arguments[arguments.length - 1]); var source = this; // optimized case:argument is 2 if (arguments.length == 2) { var second = arguments[0]; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var index = 0; return new IEnumerator( function () { firstEnumerator = source.getEnumerator(); secondEnumerator = Enumerable.from(second).getEnumerator(); }, function () { if (firstEnumerator.moveNext() && secondEnumerator.moveNext()) { return this.yieldReturn(selector(firstEnumerator.current(), secondEnumerator.current(), index++)); } return false; }, function () { try { Utils.dispose(firstEnumerator); } finally { Utils.dispose(secondEnumerator); } }); }); } else { return new Enumerable(function () { var enumerators; var index = 0; return new IEnumerator( function () { var array = Enumerable.make(source) .concat(Enumerable.from(args).takeExceptLast().select(Enumerable.from)) .select(function (x) { return x.getEnumerator() }) .toArray(); enumerators = Enumerable.from(array); }, function () { if (enumerators.all(function (x) { return x.moveNext() })) { var array = enumerators .select(function (x) { return x.current() }) .toArray(); array.push(index++); return this.yieldReturn(selector.apply(null, array)); } else { return this.yieldBreak(); } }, function () { Enumerable.from(enumerators).forEach(Utils.dispose); }); }); } }; // mutiple arguments Enumerable.prototype.merge = function () { var args = arguments; var source = this; return new Enumerable(function () { var enumerators; var index = -1; return new IEnumerator( function () { enumerators = Enumerable.make(source) .concat(Enumerable.from(args).select(Enumerable.from)) .select(function (x) { return x.getEnumerator() }) .toArray(); }, function () { while (enumerators.length > 0) { index = (index >= enumerators.length - 1) ? 0 : index + 1; var enumerator = enumerators[index]; if (enumerator.moveNext()) { return this.yieldReturn(enumerator.current()); } else { enumerator.dispose(); enumerators.splice(index } } return this.yieldBreak(); }, function () { Enumerable.from(enumerators).forEach(Utils.dispose); }); }); }; /* Join Methods */ // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector) // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) Enumerable.prototype.join = function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { outerKeySelector = Utils.createLambda(outerKeySelector); innerKeySelector = Utils.createLambda(innerKeySelector); resultSelector = Utils.createLambda(resultSelector); compareSelector = Utils.createLambda(compareSelector); var source = this; return new Enumerable(function () { var outerEnumerator; var lookup; var innerElements = null; var innerCount = 0; return new IEnumerator( function () { outerEnumerator = source.getEnumerator(); lookup = Enumerable.from(inner).toLookup(innerKeySelector, Functions.Identity, compareSelector); }, function () { while (true) { if (innerElements != null) { var innerElement = innerElements[innerCount++]; if (innerElement !== undefined) { return this.yieldReturn(resultSelector(outerEnumerator.current(), innerElement)); } innerElement = null; innerCount = 0; } if (outerEnumerator.moveNext()) { var key = outerKeySelector(outerEnumerator.current()); innerElements = lookup.get(key).toArray(); } else { return false; } } }, function () { Utils.dispose(outerEnumerator); }); }); }; // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector) // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) Enumerable.prototype.groupJoin = function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { outerKeySelector = Utils.createLambda(outerKeySelector); innerKeySelector = Utils.createLambda(innerKeySelector); resultSelector = Utils.createLambda(resultSelector); compareSelector = Utils.createLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator = source.getEnumerator(); var lookup = null; return new IEnumerator( function () { enumerator = source.getEnumerator(); lookup = Enumerable.from(inner).toLookup(innerKeySelector, Functions.Identity, compareSelector); }, function () { if (enumerator.moveNext()) { var innerElement = lookup.get(outerKeySelector(enumerator.current())); return this.yieldReturn(resultSelector(enumerator.current(), innerElement)); } return false; }, function () { Utils.dispose(enumerator); }); }); }; /* Set Methods */ Enumerable.prototype.all = function (predicate) { predicate = Utils.createLambda(predicate); var result = true; this.forEach(function (x) { if (!predicate(x)) { result = false; return false; // break } }); return result; }; // Overload:function() // Overload:function(predicate) Enumerable.prototype.any = function (predicate) { predicate = Utils.createLambda(predicate); var enumerator = this.getEnumerator(); try { if (arguments.length == 0) return enumerator.moveNext(); // case:function() while (enumerator.moveNext()) // case:function(predicate) { if (predicate(enumerator.current())) return true; } return false; } finally { Utils.dispose(enumerator); } }; Enumerable.prototype.isEmpty = function () { return !this.any(); }; // multiple arguments Enumerable.prototype.concat = function () { var source = this; if (arguments.length == 1) { var second = arguments[0]; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; return new IEnumerator( function () { firstEnumerator = source.getEnumerator(); }, function () { if (secondEnumerator == null) { if (firstEnumerator.moveNext()) return this.yieldReturn(firstEnumerator.current()); secondEnumerator = Enumerable.from(second).getEnumerator(); } if (secondEnumerator.moveNext()) return this.yieldReturn(secondEnumerator.current()); return false; }, function () { try { Utils.dispose(firstEnumerator); } finally { Utils.dispose(secondEnumerator); } }); }); } else { var args = arguments; return new Enumerable(function () { var enumerators; return new IEnumerator( function () { enumerators = Enumerable.make(source) .concat(Enumerable.from(args).select(Enumerable.from)) .select(function (x) { return x.getEnumerator() }) .toArray(); }, function () { while (enumerators.length > 0) { var enumerator = enumerators[0]; if (enumerator.moveNext()) { return this.yieldReturn(enumerator.current()); } else { enumerator.dispose(); enumerators.splice(0, 1); } } return this.yieldBreak(); }, function () { Enumerable.from(enumerators).forEach(Utils.dispose); }); }); } }; Enumerable.prototype.insert = function (index, second) { var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var count = 0; var isEnumerated = false; return new IEnumerator( function () { firstEnumerator = source.getEnumerator(); secondEnumerator = Enumerable.from(second).getEnumerator(); }, function () { if (count == index && secondEnumerator.moveNext()) { isEnumerated = true; return this.yieldReturn(secondEnumerator.current()); } if (firstEnumerator.moveNext()) { count++; return this.yieldReturn(firstEnumerator.current()); } if (!isEnumerated && secondEnumerator.moveNext()) { return this.yieldReturn(secondEnumerator.current()); } return false; }, function () { try { Utils.dispose(firstEnumerator); } finally { Utils.dispose(secondEnumerator); } }); }); }; Enumerable.prototype.alternate = function (<API key>) { var source = this; return new Enumerable(function () { var buffer; var enumerator; var alternateSequence; var alternateEnumerator; return new IEnumerator( function () { if (<API key> instanceof Array || <API key>.getEnumerator != null) { alternateSequence = Enumerable.from(Enumerable.from(<API key>).toArray()); // freeze } else { alternateSequence = Enumerable.make(<API key>); } enumerator = source.getEnumerator(); if (enumerator.moveNext()) buffer = enumerator.current(); }, function () { while (true) { if (alternateEnumerator != null) { if (alternateEnumerator.moveNext()) { return this.yieldReturn(alternateEnumerator.current()); } else { alternateEnumerator = null; } } if (buffer == null && enumerator.moveNext()) { buffer = enumerator.current(); // hasNext alternateEnumerator = alternateSequence.getEnumerator(); continue; // GOTO } else if (buffer != null) { var retVal = buffer; buffer = null; return this.yieldReturn(retVal); } return this.yieldBreak(); } }, function () { try { Utils.dispose(enumerator); } finally { Utils.dispose(alternateEnumerator); } }); }); }; // Overload:function(value) // Overload:function(value, compareSelector) Enumerable.prototype.contains = function (value, compareSelector) { compareSelector = Utils.createLambda(compareSelector); var enumerator = this.getEnumerator(); try { while (enumerator.moveNext()) { if (compareSelector(enumerator.current()) === value) return true; } return false; } finally { Utils.dispose(enumerator); } }; Enumerable.prototype.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) defaultValue = null; return new Enumerable(function () { var enumerator; var isFirst = true; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { if (enumerator.moveNext()) { isFirst = false; return this.yieldReturn(enumerator.current()); } else if (isFirst) { isFirst = false; return this.yieldReturn(defaultValue); } return false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function() // Overload:function(compareSelector) Enumerable.prototype.distinct = function (compareSelector) { return this.except(Enumerable.empty(), compareSelector); }; Enumerable.prototype.<API key> = function (compareSelector) { compareSelector = Utils.createLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator; var compareKey; var initial; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (enumerator.moveNext()) { var key = compareSelector(enumerator.current()); if (initial) { initial = false; compareKey = key; return this.yieldReturn(enumerator.current()); } if (compareKey === key) { continue; } compareKey = key; return this.yieldReturn(enumerator.current()); } return this.yieldBreak(); }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(second) // Overload:function(second, compareSelector) Enumerable.prototype.except = function (second, compareSelector) { compareSelector = Utils.createLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator; var keys; return new IEnumerator( function () { enumerator = source.getEnumerator(); keys = new Dictionary(compareSelector); Enumerable.from(second).forEach(function (key) { keys.add(key); }); }, function () { while (enumerator.moveNext()) { var current = enumerator.current(); if (!keys.contains(current)) { keys.add(current); return this.yieldReturn(current); } } return false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(second) // Overload:function(second, compareSelector) Enumerable.prototype.intersect = function (second, compareSelector) { compareSelector = Utils.createLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator; var keys; var outs; return new IEnumerator( function () { enumerator = source.getEnumerator(); keys = new Dictionary(compareSelector); Enumerable.from(second).forEach(function (key) { keys.add(key); }); outs = new Dictionary(compareSelector); }, function () { while (enumerator.moveNext()) { var current = enumerator.current(); if (!outs.contains(current) && keys.contains(current)) { outs.add(current); return this.yieldReturn(current); } } return false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(second) // Overload:function(second, compareSelector) Enumerable.prototype.sequenceEqual = function (second, compareSelector) { compareSelector = Utils.createLambda(compareSelector); var firstEnumerator = this.getEnumerator(); try { var secondEnumerator = Enumerable.from(second).getEnumerator(); try { while (firstEnumerator.moveNext()) { if (!secondEnumerator.moveNext() || compareSelector(firstEnumerator.current()) !== compareSelector(secondEnumerator.current())) { return false; } } if (secondEnumerator.moveNext()) return false; return true; } finally { Utils.dispose(secondEnumerator); } } finally { Utils.dispose(firstEnumerator); } }; Enumerable.prototype.union = function (second, compareSelector) { compareSelector = Utils.createLambda(compareSelector); var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var keys; return new IEnumerator( function () { firstEnumerator = source.getEnumerator(); keys = new Dictionary(compareSelector); }, function () { var current; if (secondEnumerator === undefined) { while (firstEnumerator.moveNext()) { current = firstEnumerator.current(); if (!keys.contains(current)) { keys.add(current); return this.yieldReturn(current); } } secondEnumerator = Enumerable.from(second).getEnumerator(); } while (secondEnumerator.moveNext()) { current = secondEnumerator.current(); if (!keys.contains(current)) { keys.add(current); return this.yieldReturn(current); } } return false; }, function () { try { Utils.dispose(firstEnumerator); } finally { Utils.dispose(secondEnumerator); } }); }); }; /* Ordering Methods */ Enumerable.prototype.orderBy = function (keySelector) { return new OrderedEnumerable(this, keySelector, false); }; Enumerable.prototype.orderByDescending = function (keySelector) { return new OrderedEnumerable(this, keySelector, true); }; Enumerable.prototype.reverse = function () { var source = this; return new Enumerable(function () { var buffer; var index; return new IEnumerator( function () { buffer = source.toArray(); index = buffer.length; }, function () { return (index > 0) ? this.yieldReturn(buffer[--index]) : false; }, Functions.Blank); }); }; Enumerable.prototype.shuffle = function () { var source = this; return new Enumerable(function () { var buffer; return new IEnumerator( function () { buffer = source.toArray(); }, function () { if (buffer.length > 0) { var i = Math.floor(Math.random() * buffer.length); return this.yieldReturn(buffer.splice(i, 1)[0]); } return false; }, Functions.Blank); }); }; Enumerable.prototype.weightedSample = function (weightSelector) { weightSelector = Utils.createLambda(weightSelector); var source = this; return new Enumerable(function () { var sortedByBound; var totalWeight = 0; return new IEnumerator( function () { sortedByBound = source .choose(function (x) { var weight = weightSelector(x); if (weight <= 0) return null; // ignore 0 totalWeight += weight; return { value: x, bound: totalWeight }; }) .toArray(); }, function () { if (sortedByBound.length > 0) { var draw = Math.floor(Math.random() * totalWeight) + 1; var lower = -1; var upper = sortedByBound.length; while (upper - lower > 1) { var index = Math.floor((lower + upper) / 2); if (sortedByBound[index].bound >= draw) { upper = index; } else { lower = index; } } return this.yieldReturn(sortedByBound[upper].value); } return this.yieldBreak(); }, Functions.Blank); }); }; /* Grouping Methods */ // Overload:function(keySelector) // Overload:function(keySelector,elementSelector) // Overload:function(keySelector,elementSelector,resultSelector) // Overload:function(keySelector,elementSelector,resultSelector,compareSelector) Enumerable.prototype.groupBy = function (keySelector, elementSelector, resultSelector, compareSelector) { var source = this; keySelector = Utils.createLambda(keySelector); elementSelector = Utils.createLambda(elementSelector); if (resultSelector != null) resultSelector = Utils.createLambda(resultSelector); compareSelector = Utils.createLambda(compareSelector); return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.toLookup(keySelector, elementSelector, compareSelector) .toEnumerable() .getEnumerator(); }, function () { while (enumerator.moveNext()) { return (resultSelector == null) ? this.yieldReturn(enumerator.current()) : this.yieldReturn(resultSelector(enumerator.current().key(), enumerator.current())); } return false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(keySelector) // Overload:function(keySelector,elementSelector) // Overload:function(keySelector,elementSelector,resultSelector) // Overload:function(keySelector,elementSelector,resultSelector,compareSelector) Enumerable.prototype.partitionBy = function (keySelector, elementSelector, resultSelector, compareSelector) { var source = this; keySelector = Utils.createLambda(keySelector); elementSelector = Utils.createLambda(elementSelector); compareSelector = Utils.createLambda(compareSelector); var hasResultSelector; if (resultSelector == null) { hasResultSelector = false; resultSelector = function (key, group) { return new Grouping(key, group); }; } else { hasResultSelector = true; resultSelector = Utils.createLambda(resultSelector); } return new Enumerable(function () { var enumerator; var key; var compareKey; var group = []; return new IEnumerator( function () { enumerator = source.getEnumerator(); if (enumerator.moveNext()) { key = keySelector(enumerator.current()); compareKey = compareSelector(key); group.push(elementSelector(enumerator.current())); } }, function () { var hasNext; while ((hasNext = enumerator.moveNext()) == true) { if (compareKey === compareSelector(keySelector(enumerator.current()))) { group.push(elementSelector(enumerator.current())); } else break; } if (group.length > 0) { var result = (hasResultSelector) ? resultSelector(key, Enumerable.from(group)) : resultSelector(key, group); if (hasNext) { key = keySelector(enumerator.current()); compareKey = compareSelector(key); group = [elementSelector(enumerator.current())]; } else group = []; return this.yieldReturn(result); } return false; }, function () { Utils.dispose(enumerator); }); }); }; Enumerable.prototype.buffer = function (count) { var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { var array = []; var index = 0; while (enumerator.moveNext()) { array.push(enumerator.current()); if (++index >= count) return this.yieldReturn(array); } if (array.length > 0) return this.yieldReturn(array); return false; }, function () { Utils.dispose(enumerator); }); }); }; /* Aggregate Methods */ // Overload:function(func) // Overload:function(seed,func) // Overload:function(seed,func,resultSelector) Enumerable.prototype.aggregate = function (seed, func, resultSelector) { resultSelector = Utils.createLambda(resultSelector); return resultSelector(this.scan(seed, func, resultSelector).last()); }; // Overload:function() // Overload:function(selector) Enumerable.prototype.average = function (selector) { selector = Utils.createLambda(selector); var sum = 0; var count = 0; this.forEach(function (x) { sum += selector(x); ++count; }); return sum / count; }; // Overload:function() // Overload:function(predicate) Enumerable.prototype.count = function (predicate) { predicate = (predicate == null) ? Functions.True : Utils.createLambda(predicate); var count = 0; this.forEach(function (x, i) { if (predicate(x, i))++count; }); return count; }; // Overload:function() // Overload:function(selector) Enumerable.prototype.max = function (selector) { if (selector == null) selector = Functions.Identity; return this.select(selector).aggregate(function (a, b) { return (a > b) ? a : b; }); }; // Overload:function() // Overload:function(selector) Enumerable.prototype.min = function (selector) { if (selector == null) selector = Functions.Identity; return this.select(selector).aggregate(function (a, b) { return (a < b) ? a : b; }); }; Enumerable.prototype.maxBy = function (keySelector) { keySelector = Utils.createLambda(keySelector); return this.aggregate(function (a, b) { return (keySelector(a) > keySelector(b)) ? a : b; }); }; Enumerable.prototype.minBy = function (keySelector) { keySelector = Utils.createLambda(keySelector); return this.aggregate(function (a, b) { return (keySelector(a) < keySelector(b)) ? a : b; }); }; // Overload:function() // Overload:function(selector) Enumerable.prototype.sum = function (selector) { if (selector == null) selector = Functions.Identity; return this.select(selector).aggregate(0, function (a, b) { return a + b; }); }; /* Paging Methods */ Enumerable.prototype.elementAt = function (index) { var value; var found = false; this.forEach(function (x, i) { if (i == index) { value = x; found = true; return false; } }); if (!found) throw new Error("index is less than 0 or greater than or equal to the number of elements in source."); return value; }; Enumerable.prototype.elementAtOrDefault = function (index, defaultValue) { if (defaultValue === undefined) defaultValue = null; var value; var found = false; this.forEach(function (x, i) { if (i == index) { value = x; found = true; return false; } }); return (!found) ? defaultValue : value; }; // Overload:function() // Overload:function(predicate) Enumerable.prototype.first = function (predicate) { if (predicate != null) return this.where(predicate).first(); var value; var found = false; this.forEach(function (x) { value = x; found = true; return false; }); if (!found) throw new Error("first:No element satisfies the condition."); return value; }; Enumerable.prototype.firstOrDefault = function (predicate, defaultValue) { if (defaultValue === undefined) defaultValue = null; if (predicate != null) return this.where(predicate).firstOrDefault(null, defaultValue); var value; var found = false; this.forEach(function (x) { value = x; found = true; return false; }); return (!found) ? defaultValue : value; }; // Overload:function() // Overload:function(predicate) Enumerable.prototype.last = function (predicate) { if (predicate != null) return this.where(predicate).last(); var value; var found = false; this.forEach(function (x) { found = true; value = x; }); if (!found) throw new Error("last:No element satisfies the condition."); return value; }; // Overload:function(defaultValue) // Overload:function(defaultValue,predicate) Enumerable.prototype.lastOrDefault = function (predicate, defaultValue) { if (defaultValue === undefined) defaultValue = null; if (predicate != null) return this.where(predicate).lastOrDefault(null, defaultValue); var value; var found = false; this.forEach(function (x) { found = true; value = x; }); return (!found) ? defaultValue : value; }; // Overload:function() // Overload:function(predicate) Enumerable.prototype.single = function (predicate) { if (predicate != null) return this.where(predicate).single(); var value; var found = false; this.forEach(function (x) { if (!found) { found = true; value = x; } else throw new Error("single:sequence contains more than one element."); }); if (!found) throw new Error("single:No element satisfies the condition."); return value; }; // Overload:function(defaultValue) // Overload:function(defaultValue,predicate) Enumerable.prototype.singleOrDefault = function (predicate, defaultValue) { if (defaultValue === undefined) defaultValue = null; if (predicate != null) return this.where(predicate).singleOrDefault(null, defaultValue); var value; var found = false; this.forEach(function (x) { if (!found) { found = true; value = x; } else throw new Error("single:sequence contains more than one element."); }); return (!found) ? defaultValue : value; }; Enumerable.prototype.skip = function (count) { var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.getEnumerator(); while (index++ < count && enumerator.moveNext()) { } ; }, function () { return (enumerator.moveNext()) ? this.yieldReturn(enumerator.current()) : false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) Enumerable.prototype.skipWhile = function (predicate) { predicate = Utils.createLambda(predicate); var source = this; return new Enumerable(function () { var enumerator; var index = 0; var isSkipEnd = false; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (!isSkipEnd) { if (enumerator.moveNext()) { if (!predicate(enumerator.current(), index++)) { isSkipEnd = true; return this.yieldReturn(enumerator.current()); } continue; } else return false; } return (enumerator.moveNext()) ? this.yieldReturn(enumerator.current()) : false; }, function () { Utils.dispose(enumerator); }); }); }; Enumerable.prototype.take = function (count) { var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { return (index++ < count && enumerator.moveNext()) ? this.yieldReturn(enumerator.current()) : false; }, function () { Utils.dispose(enumerator); } ); }); }; // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) Enumerable.prototype.takeWhile = function (predicate) { predicate = Utils.createLambda(predicate); var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { return (enumerator.moveNext() && predicate(enumerator.current(), index++)) ? this.yieldReturn(enumerator.current()) : false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function() // Overload:function(count) Enumerable.prototype.takeExceptLast = function (count) { if (count == null) count = 1; var source = this; return new Enumerable(function () { if (count <= 0) return source.getEnumerator(); // do nothing var enumerator; var q = []; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (enumerator.moveNext()) { if (q.length == count) { q.push(enumerator.current()); return this.yieldReturn(q.shift()); } q.push(enumerator.current()); } return false; }, function () { Utils.dispose(enumerator); }); }); }; Enumerable.prototype.takeFromLast = function (count) { if (count <= 0 || count == null) return Enumerable.empty(); var source = this; return new Enumerable(function () { var sourceEnumerator; var enumerator; var q = []; return new IEnumerator( function () { sourceEnumerator = source.getEnumerator(); }, function () { while (sourceEnumerator.moveNext()) { if (q.length == count) q.shift(); q.push(sourceEnumerator.current()); } if (enumerator == null) { enumerator = Enumerable.from(q).getEnumerator(); } return (enumerator.moveNext()) ? this.yieldReturn(enumerator.current()) : false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(item) // Overload:function(predicate) Enumerable.prototype.indexOf = function (item) { var found = null; // item as predicate if (typeof (item) === Types.Function) { this.forEach(function (x, i) { if (item(x, i)) { found = i; return false; } }); } else { this.forEach(function (x, i) { if (x === item) { found = i; return false; } }); } return (found !== null) ? found : -1; }; // Overload:function(item) // Overload:function(predicate) Enumerable.prototype.lastIndexOf = function (item) { var result = -1; // item as predicate if (typeof (item) === Types.Function) { this.forEach(function (x, i) { if (item(x, i)) result = i; }); } else { this.forEach(function (x, i) { if (x === item) result = i; }); } return result; }; /* Convert Methods */ Enumerable.prototype.asEnumerable = function () { return Enumerable.from(this); }; Enumerable.prototype.toArray = function () { var array = []; this.forEach(function (x) { array.push(x); }); return array; }; // Overload:function(keySelector) // Overload:function(keySelector, elementSelector) // Overload:function(keySelector, elementSelector, compareSelector) Enumerable.prototype.toLookup = function (keySelector, elementSelector, compareSelector) { keySelector = Utils.createLambda(keySelector); elementSelector = Utils.createLambda(elementSelector); compareSelector = Utils.createLambda(compareSelector); var dict = new Dictionary(compareSelector); this.forEach(function (x) { var key = keySelector(x); var element = elementSelector(x); var array = dict.get(key); if (array !== undefined) array.push(element); else dict.add(key, [element]); }); return new Lookup(dict); }; Enumerable.prototype.toObject = function (keySelector, elementSelector) { keySelector = Utils.createLambda(keySelector); elementSelector = Utils.createLambda(elementSelector); var obj = {}; this.forEach(function (x) { obj[keySelector(x)] = elementSelector(x); }); return obj; }; // Overload:function(keySelector, elementSelector) // Overload:function(keySelector, elementSelector, compareSelector) Enumerable.prototype.toDictionary = function (keySelector, elementSelector, compareSelector) { keySelector = Utils.createLambda(keySelector); elementSelector = Utils.createLambda(elementSelector); compareSelector = Utils.createLambda(compareSelector); var dict = new Dictionary(compareSelector); this.forEach(function (x) { dict.add(keySelector(x), elementSelector(x)); }); return dict; }; // Overload:function() // Overload:function(replacer) // Overload:function(replacer, space) Enumerable.prototype.toJSONString = function (replacer, space) { if (typeof JSON === Types.Undefined || JSON.stringify == null) { throw new Error("toJSONString can't find JSON.stringify. This works native JSON support Browser or include json2.js"); } return JSON.stringify(this.toArray(), replacer, space); }; // Overload:function() // Overload:function(separator) // Overload:function(separator,selector) Enumerable.prototype.toJoinedString = function (separator, selector) { if (separator == null) separator = ""; if (selector == null) selector = Functions.Identity; return this.select(selector).toArray().join(separator); }; /* Action Methods */ // Overload:function(action<element>) // Overload:function(action<element,index>) Enumerable.prototype.doAction = function (action) { var source = this; action = Utils.createLambda(action); return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { if (enumerator.moveNext()) { action(enumerator.current(), index++); return this.yieldReturn(enumerator.current()); } return false; }, function () { Utils.dispose(enumerator); }); }); }; // Overload:function(action<element>) // Overload:function(action<element,index>) // Overload:function(func<element,bool>) // Overload:function(func<element,index,bool>) Enumerable.prototype.forEach = function (action) { action = Utils.createLambda(action); var index = 0; var enumerator = this.getEnumerator(); try { while (enumerator.moveNext()) { if (action(enumerator.current(), index++) === false) break; } } finally { Utils.dispose(enumerator); } }; // Overload:function() // Overload:function(separator) // Overload:function(separator,selector) Enumerable.prototype.write = function (separator, selector) { if (separator == null) separator = ""; selector = Utils.createLambda(selector); var isFirst = true; this.forEach(function (item) { if (isFirst) isFirst = false; else document.write(separator); document.write(selector(item)); }); }; // Overload:function() // Overload:function(selector) Enumerable.prototype.writeLine = function (selector) { selector = Utils.createLambda(selector); this.forEach(function (item) { document.writeln(selector(item) + "<br />"); }); }; Enumerable.prototype.force = function () { var enumerator = this.getEnumerator(); try { while (enumerator.moveNext()) { } } finally { Utils.dispose(enumerator); } }; /* Functional Methods */ Enumerable.prototype.letBind = function (func) { func = Utils.createLambda(func); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = Enumerable.from(func(source)).getEnumerator(); }, function () { return (enumerator.moveNext()) ? this.yieldReturn(enumerator.current()) : false; }, function () { Utils.dispose(enumerator); }); }); }; Enumerable.prototype.share = function () { var source = this; var sharedEnumerator; var disposed = false; return new <API key>(function () { return new IEnumerator( function () { if (sharedEnumerator == null) { sharedEnumerator = source.getEnumerator(); } }, function () { if (disposed) throw new Error("enumerator is disposed"); return (sharedEnumerator.moveNext()) ? this.yieldReturn(sharedEnumerator.current()) : false; }, Functions.Blank ); }, function () { disposed = true; Utils.dispose(sharedEnumerator); }); }; Enumerable.prototype.memoize = function () { var source = this; var cache; var enumerator; var disposed = false; return new <API key>(function () { var index = -1; return new IEnumerator( function () { if (enumerator == null) { enumerator = source.getEnumerator(); cache = []; } }, function () { if (disposed) throw new Error("enumerator is disposed"); index++; if (cache.length <= index) { return (enumerator.moveNext()) ? this.yieldReturn(cache[index] = enumerator.current()) : false; } return this.yieldReturn(cache[index]); }, Functions.Blank ); }, function () { disposed = true; Utils.dispose(enumerator); cache = null; }); }; /* Error Handling Methods */ Enumerable.prototype.catchError = function (handler) { handler = Utils.createLambda(handler); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { try { return (enumerator.moveNext()) ? this.yieldReturn(enumerator.current()) : false; } catch (e) { handler(e); return false; } }, function () { Utils.dispose(enumerator); }); }); }; Enumerable.prototype.finallyAction = function (finallyAction) { finallyAction = Utils.createLambda(finallyAction); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { return (enumerator.moveNext()) ? this.yieldReturn(enumerator.current()) : false; }, function () { try { Utils.dispose(enumerator); } finally { finallyAction(); } }); }); }; /* For Debug Methods */ // Overload:function() // Overload:function(selector) Enumerable.prototype.log = function (selector) { selector = Utils.createLambda(selector); return this.doAction(function (item) { if (typeof console !== Types.Undefined) { console.log(selector(item)); } }); }; // Overload:function() // Overload:function(message) // Overload:function(message,selector) Enumerable.prototype.trace = function (message, selector) { if (message == null) message = "Trace"; selector = Utils.createLambda(selector); return this.doAction(function (item) { if (typeof console !== Types.Undefined) { console.log(message, selector(item)); } }); }; // private var OrderedEnumerable = function (source, keySelector, descending, parent) { this.source = source; this.keySelector = Utils.createLambda(keySelector); this.descending = descending; this.parent = parent; }; OrderedEnumerable.prototype = new Enumerable(); OrderedEnumerable.prototype.<API key> = function (keySelector, descending) { return new OrderedEnumerable(this.source, keySelector, descending, this); }; OrderedEnumerable.prototype.thenBy = function (keySelector) { return this.<API key>(keySelector, false); }; OrderedEnumerable.prototype.thenByDescending = function (keySelector) { return this.<API key>(keySelector, true); }; OrderedEnumerable.prototype.getEnumerator = function () { var self = this; var buffer; var indexes; var index = 0; return new IEnumerator( function () { buffer = []; indexes = []; self.source.forEach(function (item, index) { buffer.push(item); indexes.push(index); }); var sortContext = SortContext.create(self, null); sortContext.GenerateKeys(buffer); indexes.sort(function (a, b) { return sortContext.compare(a, b); }); }, function () { return (index < indexes.length) ? this.yieldReturn(buffer[indexes[index++]]) : false; }, Functions.Blank ); }; var SortContext = function (keySelector, descending, child) { this.keySelector = keySelector; this.descending = descending; this.child = child; this.keys = null; }; SortContext.create = function (orderedEnumerable, currentContext) { var context = new SortContext(orderedEnumerable.keySelector, orderedEnumerable.descending, currentContext); if (orderedEnumerable.parent != null) return SortContext.create(orderedEnumerable.parent, context); return context; }; SortContext.prototype.GenerateKeys = function (source) { var len = source.length; var keySelector = this.keySelector; var keys = new Array(len); for (var i = 0; i < len; i++) keys[i] = keySelector(source[i]); this.keys = keys; if (this.child != null) this.child.GenerateKeys(source); }; SortContext.prototype.compare = function (index1, index2) { var comparison = Utils.compare(this.keys[index1], this.keys[index2]); if (comparison == 0) { if (this.child != null) return this.child.compare(index1, index2); return Utils.compare(index1, index2); } return (this.descending) ? -comparison : comparison; }; var <API key> = function (getEnumerator, dispose) { this.dispose = dispose; Enumerable.call(this, getEnumerator); }; <API key>.prototype = new Enumerable(); // optimize array or arraylike object var ArrayEnumerable = function (source) { this.getSource = function () { return source; }; }; ArrayEnumerable.prototype = new Enumerable(); ArrayEnumerable.prototype.any = function (predicate) { return (predicate == null) ? (this.getSource().length > 0) : Enumerable.prototype.any.apply(this, arguments); }; ArrayEnumerable.prototype.count = function (predicate) { return (predicate == null) ? this.getSource().length : Enumerable.prototype.count.apply(this, arguments); }; ArrayEnumerable.prototype.elementAt = function (index) { var source = this.getSource(); return (0 <= index && index < source.length) ? source[index] : Enumerable.prototype.elementAt.apply(this, arguments); }; ArrayEnumerable.prototype.elementAtOrDefault = function (index, defaultValue) { if (defaultValue === undefined) defaultValue = null; var source = this.getSource(); return (0 <= index && index < source.length) ? source[index] : defaultValue; }; ArrayEnumerable.prototype.first = function (predicate) { var source = this.getSource(); return (predicate == null && source.length > 0) ? source[0] : Enumerable.prototype.first.apply(this, arguments); }; ArrayEnumerable.prototype.firstOrDefault = function (predicate, defaultValue) { if (defaultValue === undefined) defaultValue = null; if (predicate != null) { return Enumerable.prototype.firstOrDefault.apply(this, arguments); } var source = this.getSource(); return source.length > 0 ? source[0] : defaultValue; }; ArrayEnumerable.prototype.last = function (predicate) { var source = this.getSource(); return (predicate == null && source.length > 0) ? source[source.length - 1] : Enumerable.prototype.last.apply(this, arguments); }; ArrayEnumerable.prototype.lastOrDefault = function (predicate, defaultValue) { if (defaultValue === undefined) defaultValue = null; if (predicate != null) { return Enumerable.prototype.lastOrDefault.apply(this, arguments); } var source = this.getSource(); return source.length > 0 ? source[source.length - 1] : defaultValue; }; ArrayEnumerable.prototype.skip = function (count) { var source = this.getSource(); return new Enumerable(function () { var index; return new IEnumerator( function () { index = (count < 0) ? 0 : count; }, function () { return (index < source.length) ? this.yieldReturn(source[index++]) : false; }, Functions.Blank); }); }; ArrayEnumerable.prototype.takeExceptLast = function (count) { if (count == null) count = 1; return this.take(this.getSource().length - count); }; ArrayEnumerable.prototype.takeFromLast = function (count) { return this.skip(this.getSource().length - count); }; ArrayEnumerable.prototype.reverse = function () { var source = this.getSource(); return new Enumerable(function () { var index; return new IEnumerator( function () { index = source.length; }, function () { return (index > 0) ? this.yieldReturn(source[--index]) : false; }, Functions.Blank); }); }; ArrayEnumerable.prototype.sequenceEqual = function (second, compareSelector) { if ((second instanceof ArrayEnumerable || second instanceof Array) && compareSelector == null && Enumerable.from(second).count() != this.count()) { return false; } return Enumerable.prototype.sequenceEqual.apply(this, arguments); }; ArrayEnumerable.prototype.toJoinedString = function (separator, selector) { var source = this.getSource(); if (selector != null || !(source instanceof Array)) { return Enumerable.prototype.toJoinedString.apply(this, arguments); } if (separator == null) separator = ""; return source.join(separator); }; ArrayEnumerable.prototype.getEnumerator = function () { var source = this.getSource(); var index = -1; // fast and simple enumerator return { current: function () { return source[index]; }, moveNext: function () { return ++index < source.length; }, dispose: Functions.Blank }; }; // optimization for multiple where and multiple select and whereselect var WhereEnumerable = function (source, predicate) { this.prevSource = source; this.prevPredicate = predicate; // predicate.length always <= 1 }; WhereEnumerable.prototype = new Enumerable(); WhereEnumerable.prototype.where = function (predicate) { predicate = Utils.createLambda(predicate); if (predicate.length <= 1) { var prevPredicate = this.prevPredicate; var composedPredicate = function (x) { return prevPredicate(x) && predicate(x); }; return new WhereEnumerable(this.prevSource, composedPredicate); } else { // if predicate use index, can't compose return Enumerable.prototype.where.call(this, predicate); } }; WhereEnumerable.prototype.select = function (selector) { selector = Utils.createLambda(selector); return (selector.length <= 1) ? new <API key>(this.prevSource, this.prevPredicate, selector) : Enumerable.prototype.select.call(this, selector); }; WhereEnumerable.prototype.getEnumerator = function () { var predicate = this.prevPredicate; var source = this.prevSource; var enumerator; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (enumerator.moveNext()) { if (predicate(enumerator.current())) { return this.yieldReturn(enumerator.current()); } } return false; }, function () { Utils.dispose(enumerator); }); }; var <API key> = function (source, predicate, selector) { this.prevSource = source; this.prevPredicate = predicate; // predicate.length always <= 1 or null this.prevSelector = selector; // selector.length always <= 1 }; <API key>.prototype = new Enumerable(); <API key>.prototype.where = function (predicate) { predicate = Utils.createLambda(predicate); return (predicate.length <= 1) ? new WhereEnumerable(this, predicate) : Enumerable.prototype.where.call(this, predicate); }; <API key>.prototype.select = function (selector) { selector = Utils.createLambda(selector); if (selector.length <= 1) { var prevSelector = this.prevSelector; var composedSelector = function (x) { return selector(prevSelector(x)); }; return new <API key>(this.prevSource, this.prevPredicate, composedSelector); } else { // if selector use index, can't compose return Enumerable.prototype.select.call(this, selector); } }; <API key>.prototype.getEnumerator = function () { var predicate = this.prevPredicate; var selector = this.prevSelector; var source = this.prevSource; var enumerator; return new IEnumerator( function () { enumerator = source.getEnumerator(); }, function () { while (enumerator.moveNext()) { if (predicate == null || predicate(enumerator.current())) { return this.yieldReturn(selector(enumerator.current())); } } return false; }, function () { Utils.dispose(enumerator); }); }; // Collections var Dictionary = (function () { // static utility methods var callHasOwnProperty = function (target, key) { return Object.prototype.hasOwnProperty.call(target, key); }; var computeHashCode = function (obj) { if (obj === null) return "null"; if (obj === undefined) return "undefined"; return (typeof obj.toString === Types.Function) ? obj.toString() : Object.prototype.toString.call(obj); }; // LinkedList for Dictionary var HashEntry = function (key, value) { this.key = key; this.value = value; this.prev = null; this.next = null; }; var EntryList = function () { this.first = null; this.last = null; }; EntryList.prototype = { addLast: function (entry) { if (this.last != null) { this.last.next = entry; entry.prev = this.last; this.last = entry; } else this.first = this.last = entry; }, replace: function (entry, newEntry) { if (entry.prev != null) { entry.prev.next = newEntry; newEntry.prev = entry.prev; } else this.first = newEntry; if (entry.next != null) { entry.next.prev = newEntry; newEntry.next = entry.next; } else this.last = newEntry; }, remove: function (entry) { if (entry.prev != null) entry.prev.next = entry.next; else this.first = entry.next; if (entry.next != null) entry.next.prev = entry.prev; else this.last = entry.prev; } }; // Overload:function() // Overload:function(compareSelector) var Dictionary = function (compareSelector) { this.countField = 0; this.entryList = new EntryList(); this.buckets = {}; // as Dictionary<string,List<object>> this.compareSelector = (compareSelector == null) ? Functions.Identity : compareSelector; }; Dictionary.prototype = { add: function (key, value) { var compareKey = this.compareSelector(key); var hash = computeHashCode(compareKey); var entry = new HashEntry(key, value); if (callHasOwnProperty(this.buckets, hash)) { var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].key) === compareKey) { this.entryList.replace(array[i], entry); array[i] = entry; return; } } array.push(entry); } else { this.buckets[hash] = [entry]; } this.countField++; this.entryList.addLast(entry); }, get: function (key) { var compareKey = this.compareSelector(key); var hash = computeHashCode(compareKey); if (!callHasOwnProperty(this.buckets, hash)) return undefined; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { var entry = array[i]; if (this.compareSelector(entry.key) === compareKey) return entry.value; } return undefined; }, set: function (key, value) { var compareKey = this.compareSelector(key); var hash = computeHashCode(compareKey); if (callHasOwnProperty(this.buckets, hash)) { var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].key) === compareKey) { var newEntry = new HashEntry(key, value); this.entryList.replace(array[i], newEntry); array[i] = newEntry; return true; } } } return false; }, contains: function (key) { var compareKey = this.compareSelector(key); var hash = computeHashCode(compareKey); if (!callHasOwnProperty(this.buckets, hash)) return false; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].key) === compareKey) return true; } return false; }, clear: function () { this.countField = 0; this.buckets = {}; this.entryList = new EntryList(); }, remove: function (key) { var compareKey = this.compareSelector(key); var hash = computeHashCode(compareKey); if (!callHasOwnProperty(this.buckets, hash)) return; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].key) === compareKey) { this.entryList.remove(array[i]); array.splice(i, 1); if (array.length == 0) delete this.buckets[hash]; this.countField return; } } }, count: function () { return this.countField; }, toEnumerable: function () { var self = this; return new Enumerable(function () { var currentEntry; return new IEnumerator( function () { currentEntry = self.entryList.first; }, function () { if (currentEntry != null) { var result = { key: currentEntry.key, value: currentEntry.value }; currentEntry = currentEntry.next; return this.yieldReturn(result); } return false; }, Functions.Blank); }); } }; return Dictionary; })(); // dictionary = Dictionary<TKey, TValue[]> var Lookup = function (dictionary) { this.count = function () { return dictionary.count(); }; this.get = function (key) { return Enumerable.from(dictionary.get(key)); }; this.contains = function (key) { return dictionary.contains(key); }; this.toEnumerable = function () { return dictionary.toEnumerable().select(function (kvp) { return new Grouping(kvp.key, kvp.value); }); }; }; var Grouping = function (groupKey, elements) { this.key = function () { return groupKey; }; ArrayEnumerable.call(this, elements); }; Grouping.prototype = new ArrayEnumerable(); // module export if (typeof define === Types.Function && define.amd) { // AMD define("linqjs", [], function () { return Enumerable; }); } else if (typeof module !== Types.Undefined && module.exports) { // Node module.exports = Enumerable; } else { root.Enumerable = Enumerable; } })(this);
// Module : movement_manager.h // Created : 02.10.2001 // Modified : 12.11.2003 // Author : Dmitriy Iassenev // Description : Movement manager #pragma once #include "ai_monster_space.h" #include "graph_engine_space.h" #include "game_graph_space.h" namespace MovementManager { enum EPathType; }; namespace DetailPathManager { enum EDetailPathType; }; template < typename _Graph, typename _VertexEvaluator, typename _vertex_id_type > class <API key>; template < typename _Graph, typename _VertexEvaluator, typename _vertex_id_type, typename _index_type > class CBasePathManager; template < typename _dist_type, typename _index_type, typename _iteration_type > struct SVertexType; template < typename _dist_type, typename _index_type, typename _iteration_type > struct SBaseParameters; template < typename _dist_type, typename _index_type, typename _iteration_type > struct SGameVertex; class <API key>; class CPatrolPathManager; class CDetailPathManager; class CPHMovementControl; class CGameGraph; class CLevelGraph; class CRestrictedObject; class CLocationManager; class CCustomMonster; namespace DetailPathManager { struct STravelPathPoint; }; class CLevelPathBuilder; class CDetailPathBuilder; class CMovementManager { private: friend class CLevelPathBuilder; friend class CDetailPathBuilder; protected: typedef MonsterSpace::SBoneRotation CBoneRotation; typedef MovementManager::EPathType EPathType; typedef DetailPathManager::STravelPathPoint CTravelPathPoint; typedef GraphEngineSpace::CBaseParameters CBaseParameters; typedef GraphEngineSpace::CGameVertexParams CGameVertexParams; typedef <API key>< CGameGraph, SGameVertex< float, u32, u32 >, u32 > <API key>; typedef CBasePathManager< CGameGraph, SGameVertex< float, u32, u32 >, u32, u32 > CGamePathManager; typedef CBasePathManager< CLevelGraph, SBaseParameters< float, u32, u32 >, u32, u32 > CLevelPathManager; private: enum EPathState { <API key> = u32(0), <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, ePathStateTeleport, ePathStateDummy = u32(-1), }; protected: typedef xr_vector<CObject*> NEAREST_OBJECTS; protected: NEAREST_OBJECTS m_nearest_objects; protected: float m_speed; public: CBoneRotation m_body; protected: bool m_path_actuality; private: EPathState m_path_state; EPathType m_path_type; bool m_enabled; Fvector <API key>; float <API key>; bool m_extrapolate_path; bool m_build_at_once; bool <API key>; public: CGameVertexParams *<API key>; CBaseParameters *<API key>; <API key> *<API key>; CGamePathManager *m_game_path_manager; CLevelPathManager *<API key>; CDetailPathManager *<API key>; CPatrolPathManager *<API key>; CRestrictedObject *m_restricted_object; CLocationManager *m_location_manager; CLevelPathBuilder *<API key>; CDetailPathBuilder *<API key>; CCustomMonster *m_object; private: void process_game_path (); void process_level_path (); void process_patrol_path (); #ifdef <API key> void verify_detail_path (); #endif // <API key> void apply_collision_hit (CPHMovementControl *movement_control); protected: virtual void teleport (u32 game_vertex_id); public: CMovementManager (CCustomMonster *object); virtual ~CMovementManager (); virtual void Load (LPCSTR caSection); virtual void reinit (); virtual void reload (LPCSTR caSection); virtual BOOL net_Spawn (CSE_Abstract* data); virtual void net_Destroy (); virtual void on_frame (CPHMovementControl *movement_control, Fvector &dest_position); IC bool actual () const; bool actual_all () const; IC void set_path_type (EPathType path_type); void <API key> (const GameGraph::_GRAPH_ID &game_vertex_id); void <API key> (const u32 level_vertex_id); IC void <API key> (); void enable_movement (bool enabled); EPathType path_type () const; GameGraph::_GRAPH_ID game_dest_vertex_id () const; u32 <API key> () const; IC bool enabled () const; IC bool path_completed () const; IC float old_desirable_speed () const; IC void set_desirable_speed (float speed); const xr_vector<CTravelPathPoint> &path () const; IC void <API key> (const MonsterSpace::SBoneRotation &orientation); IC const CBoneRotation &body_orientation() const; void update_path (); virtual void move_along_path (CPHMovementControl *movement_control, Fvector &dest_position, float time_delta); IC float speed () const; float speed (CPHMovementControl *movement_control) const; virtual void <API key> (const u32 &<API key>); virtual void on_build_path () {} template <typename T> IC bool accessible (T <API key>, float radius = EPS_L) const; IC void extrapolate_path (bool value); IC bool extrapolate_path () const; bool <API key> (const float &distance_to_check) const; IC bool <API key> () const; virtual bool <API key> (u32 option) const; void clear_path (); public: IC CGameVertexParams *base_game_params () const; IC CBaseParameters *base_level_params () const; IC <API key> &game_selector () const; IC CGamePathManager &game_path () const; IC CLevelPathManager &level_path () const; IC CDetailPathManager &detail () const; IC CPatrolPathManager &patrol () const; IC CRestrictedObject &restrictions () const; IC CLocationManager &locations () const; IC CCustomMonster &object () const; IC CLevelPathBuilder &level_path_builder () const; IC CDetailPathBuilder &detail_path_builder () const; public: virtual void <API key> (); }; #include "<API key>.h"
import sbt._ object Version { val logbackVer = "1.2.3" val mUnitVer = "0.7.25" val scalaVersion = "3.0.0-RC3" } object Dependencies { private val logbackDeps = Seq ( "ch.qos.logback" % "logback-classic", ).map (_ % Version.logbackVer) private val munitDeps = Seq( "org.scalameta" %% "munit" % Version.mUnitVer % Test ) val dependencies: Seq[ModuleID] = logbackDeps ++ munitDeps val crossDependencies: Seq[ModuleID] = Seq.empty }
package org.apereo.cas.ticket.code; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.ticket.ExpirationPolicy; import org.apereo.cas.ticket.Ticket; import org.apereo.cas.ticket.TicketFactory; import org.apereo.cas.ticket.<API key>; import org.apereo.cas.util.<API key>; /** * Default OAuth code factory. * * @author Jerome Leleu * @since 5.0.0 */ public class <API key> implements OAuthCodeFactory { /** Default instance for the ticket id generator. */ protected final <API key> <API key>; /** ExpirationPolicy for refresh tokens. */ protected final ExpirationPolicy expirationPolicy; public <API key>(final ExpirationPolicy expirationPolicy) { this(new <API key>(), expirationPolicy); } public <API key>(final <API key> <API key>, final ExpirationPolicy expirationPolicy) { this.<API key> = <API key>; this.expirationPolicy = expirationPolicy; } @Override public OAuthCode create(final Service service, final Authentication authentication) { final String codeId = this.<API key>.getNewTicketId(OAuthCode.PREFIX); return new OAuthCodeImpl(codeId, service, authentication, this.expirationPolicy); } @Override public <T extends TicketFactory> T get(final Class<? extends Ticket> clazz) { return (T) this; } }
package com.intellij.codeInsight.daemon.impl; import com.intellij.codeHighlighting.<API key>; import com.intellij.codeHighlighting.HighlightingPass; import com.intellij.codeHighlighting.<API key>; import com.intellij.codeHighlighting.<API key>; import com.intellij.concurrency.Job; import com.intellij.concurrency.JobLauncher; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.ex.<API key>; import com.intellij.openapi.application.ex.ApplicationUtil; import com.intellij.openapi.application.impl.ApplicationImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.progress.<API key>; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.Functions; import com.intellij.util.containers.CollectionFactory; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashingStrategy; import com.intellij.util.ui.UIUtil; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.<API key>; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; final class PassExecutorService implements Disposable { static final Logger LOG = Logger.getInstance(PassExecutorService.class); private static final boolean CHECK_CONSISTENCY = ApplicationManager.getApplication().isUnitTestMode(); private final Map<ScheduledPass, Job<Void>> mySubmittedPasses = new ConcurrentHashMap<>(); private final Project myProject; private volatile boolean isDisposed; private final AtomicInteger nextAvailablePassId; // used to assign random id to a pass if not set PassExecutorService(@NotNull Project project) { myProject = project; nextAvailablePassId = ((<API key>)<API key>.getInstance(myProject)).getNextAvailableId(); } @Override public void dispose() { cancelAll(true); // some workers could, although idle, still retain some thread references for some time causing leak hunter to frown ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.SECONDS); isDisposed = true; } void cancelAll(boolean waitForTermination) { for (Map.Entry<ScheduledPass, Job<Void>> entry : mySubmittedPasses.entrySet()) { Job<Void> job = entry.getValue(); ScheduledPass pass = entry.getKey(); pass.myUpdateProgress.cancel(); job.cancel(); } try { if (waitForTermination) { while (!waitFor(50)) { int i = 0; } } } catch (<API key> ignored) { } catch (Error | RuntimeException e) { throw e; } catch (Throwable throwable) { LOG.error(throwable); } finally { mySubmittedPasses.clear(); } } void submitPasses(@NotNull Map<FileEditor, HighlightingPass[]> passesMap, // a list of opened FileEditors for each Document. The first FileEditor in the list is the preferred one @NotNull Map<Document, List<FileEditor>> documentToEditors, @NotNull <API key> updateProgress) { if (isDisposed()) return; Map<FileEditor, List<<API key>>> documentBoundPasses = new HashMap<>(); Map<FileEditor, List<<API key>>> editorBoundPasses = new HashMap<>(); Map<FileEditor, Int2ObjectMap<<API key>>> id2Pass = new HashMap<>(); List<ScheduledPass> freePasses = new ArrayList<>(documentToEditors.size() * 5); AtomicInteger <API key> = new AtomicInteger(0); for (Map.Entry<FileEditor, HighlightingPass[]> entry : passesMap.entrySet()) { FileEditor fileEditor = entry.getKey(); HighlightingPass[] passes = entry.getValue(); for (HighlightingPass pass : passes) { Int2ObjectMap<<API key>> thisEditorId2Pass = id2Pass.computeIfAbsent(fileEditor, __ -> new <API key><>(30)); if (pass instanceof <API key>) { <API key> editorPass = (<API key>)pass; // have to make ids unique for this document assignUniqueId(editorPass, thisEditorId2Pass); editorBoundPasses.computeIfAbsent(fileEditor, __->new ArrayList<>()).add(editorPass); } else if (pass instanceof <API key>) { <API key> tePass = (<API key>)pass; assignUniqueId(tePass, thisEditorId2Pass); documentBoundPasses.computeIfAbsent(fileEditor, __->new ArrayList<>()).add(tePass); } else { // generic HighlightingPass, run all of them concurrently freePasses.add(new ScheduledPass(fileEditor, pass, updateProgress, <API key>)); } } } List<ScheduledPass> dependentPasses = new ArrayList<>(documentToEditors.size() * 10); // fileEditor-> (passId -> created pass) Map<FileEditor, Int2ObjectMap<ScheduledPass>> toBeSubmitted = new HashMap<>(passesMap.size()); for (Map.Entry<Document, List<FileEditor>> entry : documentToEditors.entrySet()) { List<FileEditor> fileEditors = entry.getValue(); FileEditor preferredFileEditor = fileEditors.get(0); // assumption: the preferred fileEditor is stored first List<<API key>> passes = documentBoundPasses.get(preferredFileEditor); if (passes == null || passes.isEmpty()) { continue; } sortById(passes); for (<API key> pass : passes) { createScheduledPass(preferredFileEditor, pass, toBeSubmitted, id2Pass, freePasses, dependentPasses, updateProgress, <API key>); } } for (Map.Entry<FileEditor, List<<API key>>> entry : editorBoundPasses.entrySet()) { FileEditor fileEditor = entry.getKey(); Collection<<API key>> <API key> = entry.getValue(); for (<API key> pass : <API key>) { createScheduledPass(fileEditor, pass, toBeSubmitted, id2Pass, freePasses, dependentPasses, updateProgress, <API key>); } } if (CHECK_CONSISTENCY && !<API key>.isInStressTest()) { assertConsistency(freePasses, toBeSubmitted, <API key>); } if (LOG.isDebugEnabled()) { Set<VirtualFile> vFiles = ContainerUtil.map2Set(passesMap.keySet(), FileEditor::getFile); log(updateProgress, null, vFiles + " } for (ScheduledPass dependentPass : dependentPasses) { mySubmittedPasses.put(dependentPass, Job.nullJob()); } for (ScheduledPass freePass : freePasses) { submit(freePass); } } private void assignUniqueId(@NotNull <API key> pass, @NotNull Int2ObjectMap<<API key>> id2Pass) { int id = pass.getId(); if (id == -1 || id == 0) { id = nextAvailablePassId.incrementAndGet(); pass.setId(id); } <API key> prevPass = id2Pass.put(id, pass); if (prevPass != null) { LOG.error("Duplicate pass id found: "+id+". Both passes returned the same getId(): "+prevPass+" ("+prevPass.getClass() +") and "+pass+" ("+pass.getClass()+")"); } } private void assertConsistency(@NotNull List<ScheduledPass> freePasses, @NotNull Map<FileEditor, Int2ObjectMap<ScheduledPass>> toBeSubmitted, @NotNull AtomicInteger <API key>) { assert <API key>.get() == toBeSubmitted.values().stream().mapToInt(m->m.size()).sum(); Map<ScheduledPass, Pair<ScheduledPass, Integer>> id2Visits = CollectionFactory.<API key>(new HashingStrategy<>() { @Override public int hashCode(@Nullable PassExecutorService.ScheduledPass sp) { if (sp == null) return 0; return ((<API key>)sp.myPass).getId() * 31 + sp.myFileEditor.hashCode(); } @Override public boolean equals(@Nullable PassExecutorService.ScheduledPass sp1, @Nullable PassExecutorService.ScheduledPass sp2) { if (sp1 == null || sp2 == null) return sp1 == sp2; int id1 = ((<API key>)sp1.myPass).getId(); int id2 = ((<API key>)sp2.myPass).getId(); return id1 == id2 && sp1.myFileEditor == sp2.myFileEditor; } }); for (ScheduledPass freePass : freePasses) { HighlightingPass pass = freePass.myPass; if (pass instanceof <API key>) { id2Visits.put(freePass, Pair.create(freePass, 0)); checkConsistency(freePass, id2Visits); } } for (Map.Entry<ScheduledPass, Pair<ScheduledPass, Integer>> entry : id2Visits.entrySet()) { int count = entry.getValue().second; assert count == 0 : entry.getKey(); } assert id2Visits.size() == <API key>.get() : "Expected "+<API key>+" but got "+id2Visits.size()+": "+id2Visits; } private void checkConsistency(@NotNull ScheduledPass pass, Map<ScheduledPass, Pair<ScheduledPass, Integer>> id2Visits) { for (ScheduledPass succ : ContainerUtil.concat(pass.<API key>, pass.<API key>)) { Pair<ScheduledPass, Integer> succPair = id2Visits.get(succ); if (succPair == null) { succPair = Pair.create(succ, succ.<API key>.get()); id2Visits.put(succ, succPair); } int newPred = succPair.second - 1; id2Visits.put(succ, Pair.create(succ, newPred)); assert newPred >= 0; if (newPred == 0) { checkConsistency(succ, id2Visits); } } } @NotNull private ScheduledPass createScheduledPass(@NotNull FileEditor fileEditor, @NotNull <API key> pass, @NotNull Map<FileEditor, Int2ObjectMap<ScheduledPass>> toBeSubmitted, @NotNull Map<FileEditor, Int2ObjectMap<<API key>>> id2Pass, @NotNull List<ScheduledPass> freePasses, @NotNull List<ScheduledPass> dependentPasses, @NotNull <API key> updateProgress, @NotNull AtomicInteger <API key>) { Int2ObjectMap<ScheduledPass> <API key> = toBeSubmitted.computeIfAbsent(fileEditor, __ -> new <API key><>(20)); Int2ObjectMap<<API key>> thisEditorId2Pass = id2Pass.computeIfAbsent(fileEditor, __ -> new <API key><>(20)); int passId = pass.getId(); ScheduledPass scheduledPass = <API key>.get(passId); if (scheduledPass != null) return scheduledPass; scheduledPass = new ScheduledPass(fileEditor, pass, updateProgress, <API key>); <API key>.incrementAndGet(); <API key>.put(passId, scheduledPass); for (int predecessorId : pass.<API key>()) { ScheduledPass predecessor = <API key>(fileEditor, toBeSubmitted, id2Pass, freePasses, dependentPasses, updateProgress, <API key>, predecessorId, <API key>, thisEditorId2Pass); if (predecessor != null) { predecessor.<API key>(scheduledPass); } } for (int predecessorId : pass.<API key>()) { ScheduledPass predecessor = <API key>(fileEditor, toBeSubmitted, id2Pass, freePasses, dependentPasses, updateProgress, <API key>, predecessorId, <API key>, thisEditorId2Pass); if (predecessor != null) { predecessor.<API key>(scheduledPass); } } if (scheduledPass.<API key>.get() == 0 && !freePasses.contains(scheduledPass)) { freePasses.add(scheduledPass); } else if (!dependentPasses.contains(scheduledPass)) { dependentPasses.add(scheduledPass); } if (pass.<API key>() && fileEditor instanceof TextEditor) { Editor editor = ((TextEditor)fileEditor).getEditor(); VirtualFile virtualFile = fileEditor.getFile(); PsiFile psiFile = virtualFile == null ? null : ReadAction.compute(() -> PsiManager.getInstance(myProject).findFile(virtualFile)); if (psiFile != null) { ShowIntentionsPass ip = new ShowIntentionsPass(psiFile, editor, false); assignUniqueId(ip, thisEditorId2Pass); ip.<API key>(new int[]{passId}); createScheduledPass(fileEditor, ip, toBeSubmitted, id2Pass, freePasses, dependentPasses, updateProgress, <API key>); } } return scheduledPass; } private ScheduledPass <API key>(@NotNull FileEditor fileEditor, @NotNull Map<FileEditor, Int2ObjectMap<ScheduledPass>> toBeSubmitted, @NotNull Map<FileEditor, Int2ObjectMap<<API key>>> id2Pass, @NotNull List<ScheduledPass> freePasses, @NotNull List<ScheduledPass> dependentPasses, @NotNull <API key> updateProgress, @NotNull AtomicInteger <API key>, int predecessorId, @NotNull Int2ObjectMap<ScheduledPass> <API key>, @NotNull Int2ObjectMap<? extends <API key>> thisEditorId2Pass) { ScheduledPass predecessor = <API key>.get(predecessorId); if (predecessor == null) { <API key> textEditorPass = thisEditorId2Pass.get(predecessorId); predecessor = textEditorPass == null ? null : createScheduledPass(fileEditor, textEditorPass, toBeSubmitted, id2Pass, freePasses, dependentPasses, updateProgress, <API key>); } return predecessor; } private void submit(@NotNull ScheduledPass pass) { if (!pass.myUpdateProgress.isCanceled()) { Job<Void> job = JobLauncher.getInstance().submitToJobThread(pass, future -> { try { if (!future.isCancelled()) { // for canceled task .get() generates <API key> which is expensive future.get(); } } catch (<API key> | <API key> ignored) { } catch (ExecutionException e) { LOG.error(e.getCause()); } }); mySubmittedPasses.put(pass, job); } } private final class ScheduledPass implements Runnable { private final FileEditor myFileEditor; private final HighlightingPass myPass; private final AtomicInteger <API key>; private final AtomicInteger <API key> = new AtomicInteger(0); private final List<ScheduledPass> <API key> = new ArrayList<>(); private final List<ScheduledPass> <API key> = new ArrayList<>(); @NotNull private final <API key> myUpdateProgress; private ScheduledPass(@NotNull FileEditor fileEditor, @NotNull HighlightingPass pass, @NotNull <API key> progressIndicator, @NotNull AtomicInteger <API key>) { myFileEditor = fileEditor; myPass = pass; <API key> = <API key>; myUpdateProgress = progressIndicator; } @Override public void run() { ((ApplicationImpl)ApplicationManager.getApplication()).<API key>(() -> { try { doRun(); } catch (ApplicationUtil.<API key> e) { myUpdateProgress.cancel(); } catch (RuntimeException | Error e) { saveException(e, myUpdateProgress); throw e; } }); } private void doRun() { if (myUpdateProgress.isCanceled()) return; log(myUpdateProgress, myPass, "Started. "); for (ScheduledPass successor : <API key>) { int predecessorsToRun = successor.<API key>.decrementAndGet(); if (predecessorsToRun == 0) { submit(successor); } } ProgressManager.getInstance().<API key>(() -> { boolean success = <API key>.getApplicationEx().tryRunReadAction(() -> { try { if (DumbService.getInstance(myProject).isDumb() && !DumbService.isDumbAware(myPass)) { return; } if (!myUpdateProgress.isCanceled() && !myProject.isDisposed()) { myPass.collectInformation(myUpdateProgress); } } catch (<API key> e) { log(myUpdateProgress, myPass, "Canceled "); if (!myUpdateProgress.isCanceled()) { myUpdateProgress.cancel(e); //in case when some smart asses throw PCE just for fun } } catch (RuntimeException | Error e) { myUpdateProgress.cancel(e); LOG.error(e); throw e; } }); if (!success) { myUpdateProgress.cancel(); } }, myUpdateProgress); log(myUpdateProgress, myPass, "Finished. "); if (!myUpdateProgress.isCanceled()) { <API key>(myFileEditor, myPass, myUpdateProgress, <API key>, ()->{ for (ScheduledPass successor : <API key>) { int predecessorsToRun = successor.<API key>.decrementAndGet(); if (predecessorsToRun == 0) { submit(successor); } } }); } } @NonNls @Override public String toString() { return "SP: " + myPass; } private void <API key>(@NotNull ScheduledPass successor) { <API key>.add(successor); successor.<API key>.incrementAndGet(); } private void <API key>(@NotNull ScheduledPass successor) { <API key>.add(successor); successor.<API key>.incrementAndGet(); } } private void <API key>(@NotNull FileEditor fileEditor, @NotNull HighlightingPass pass, @NotNull <API key> updateProgress, @NotNull AtomicInteger <API key>, @NotNull Runnable callbackOnApplied) { ApplicationManager.getApplication().invokeLater(() -> { if (isDisposed() || !fileEditor.isValid()) { updateProgress.cancel(); } if (updateProgress.isCanceled()) { log(updateProgress, pass, " is canceled during apply, sorry"); return; } try { if (UIUtil.isShowing(fileEditor.getComponent())) { pass.<API key>(); <API key>(fileEditor); if (pass instanceof <API key>) { FileStatusMap fileStatusMap = <API key>.getInstanceEx(myProject).getFileStatusMap(); Document document = ((<API key>)pass).getDocument(); int passId = ((<API key>)pass).getId(); fileStatusMap.markFileUpToDate(document, passId); } log(updateProgress, pass, " Applied"); } } catch (<API key> e) { log(updateProgress, pass, "Error " + e); throw e; } catch (RuntimeException e) { VirtualFile file = fileEditor.getFile(); FileType fileType = file == null ? null : file.getFileType(); String message = "Exception while applying information to " + fileEditor + "("+fileType+")"; log(updateProgress, pass, message + e); throw new RuntimeException(message, e); } if (<API key>.decrementAndGet() == 0) { <API key>.<API key>(updateProgress); log(updateProgress, pass, "Stopping "); updateProgress.stopIfRunning(); clearStaleEntries(); } else { log(updateProgress, pass, "Finished but there are passes in the queue: " + <API key>.get()); } callbackOnApplied.run(); }, updateProgress.getModalityState(), pass.getExpiredCondition()); } private void clearStaleEntries() { mySubmittedPasses.keySet().removeIf(pass -> pass.myUpdateProgress.isCanceled()); } private void <API key>(@NotNull FileEditor fileEditor) { if (fileEditor instanceof TextEditor) { <API key>.<API key>(((TextEditor)fileEditor).getEditor(), myProject); } } private boolean isDisposed() { return isDisposed || myProject.isDisposed(); } @NotNull List<HighlightingPass> <API key>() { List<HighlightingPass> result = new ArrayList<>(mySubmittedPasses.size()); for (ScheduledPass scheduledPass : mySubmittedPasses.keySet()) { if (!scheduledPass.myUpdateProgress.isCanceled()) { result.add(scheduledPass.myPass); } } return result; } private static void sortById(@NotNull List<? extends <API key>> result) { ContainerUtil.quickSort(result, Comparator.comparingInt(<API key>::getId)); } private static int getThreadNum() { Matcher matcher = Pattern.compile("JobScheduler FJ pool (\\d*)/(\\d*)").matcher(Thread.currentThread().getName()); String num = matcher.matches() ? matcher.group(1) : null; return StringUtil.parseInt(num, 0); } static void log(ProgressIndicator progressIndicator, HighlightingPass pass, @NonNls Object @NotNull ... info) { if (LOG.isDebugEnabled()) { Document document = pass instanceof <API key> ? ((<API key>)pass).getDocument() : null; CharSequence docText = document == null ? "" : ": '" + StringUtil.first(document.getCharsSequence(), 10, true)+ "'"; synchronized (PassExecutorService.class) { String infos = StringUtil.join(info, Functions.TO_STRING(), " "); String message = StringUtil.repeatSymbol(' ', getThreadNum() * 4) + " " + pass + " " + infos + "; progress=" + (progressIndicator == null ? null : progressIndicator.hashCode()) + " " + (progressIndicator == null ? "?" : progressIndicator.isCanceled() ? "X" : "V") + docText; LOG.debug(message); //System.out.println(message); } } } private static final Key<Throwable> THROWABLE_KEY = Key.create("THROWABLE_KEY"); static void saveException(@NotNull Throwable e, @NotNull <API key> indicator) { indicator.putUserDataIfAbsent(THROWABLE_KEY, e); } @TestOnly static Throwable getSavedException(@NotNull <API key> indicator) { return indicator.getUserData(THROWABLE_KEY); } // return true if terminated boolean waitFor(int millis) throws Throwable { try { for (Job<Void> job : mySubmittedPasses.values()) { job.waitForCompletion(millis); } return true; } catch (TimeoutException ignored) { return false; } catch (<API key> e) { return true; } catch (ExecutionException e) { throw e.getCause(); } } }
Build a starter map This lab covers the basics for creating a basic starter mapping application. The starter map simply loads a default base map, and centers and zooms it in in a [MapView](https://developers.arcgis.com/javascript/latest/api-reference/esri-views-MapView.html). If you are new to ArcGIS and need a full set of instructions on building a basic mapping application visit the [Getting Started with MapView](https://developers.arcgis.com/javascript/latest/sample-code/get-started-mapview/index.html) tutorial. 1. Copy and paste the code below into a new [jsbin.com](http://jsbin.com). html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no"> <title>JS API Starter App</title> <link rel="stylesheet" href="https://js.arcgis.com/4.0/esri/css/main.css"> <style> html, body, #viewDiv { padding: 0; margin: 0; height: 100%; } </style> <script src="https://js.arcgis.com/4.0/"></script> <script> require([ "esri/Map", "esri/views/MapView", "dojo/domReady!" ], function(Map, MapView) { var map = new Map({ basemap: "dark-gray" }); var view = new MapView({ container: "viewDiv", map: map, center: [-122.68, 45.52], zoom: 10 }); }); </script> </head> <body> <div id="viewDiv"></div> </body> </html> 2. The JSBin `Output` panel should show a dark-grey map centered on Portland, Oregon. Your app should look something like this: * [Code](index.html) * [Live App](https://esri.github.io/geodev-hackerlabs/develop/jsapi/create_starter_map/index.html) Bonus * Experiment with different basemaps such as `topo` or `gray`. * Declare the `view` variable globally instead and open your browser's javascript console ([see some instructions here](https: **Hint:** If you're in a JS Bin, pop the Output into a separate window/tab to get direct access from the console. javascript var view; // DECLARE the 'view' variable globally. require([ "esri/Map", "esri/views/MapView", "dojo/domReady!" ], function( Map, MapView) { view = new MapView({ // REMOVE the 'var' so we're setting the new global 'view' variable. container: "viewDiv", map: map, center: [-122.68, 45.52], zoom: 10 }); Try changing the map's basemap by drilling down through the `view.map` property. E.g. `view.map.basemap = "streets"`. **Note:** You typically don't want to declare global variables like we do here, but it's good to know how to do it for debugging and exploring the API. Plus you're learning about JavaScript variable scope! * Run the code locally on your machine. Eventually if your app gets larger you'll want to migrate it from JSBin to your desktop.
.container-fluid, .container { padding-right: 0px; padding-left: 0px; margin-right: auto; margin-left: auto; } .col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 { position: relative; min-height: 1px; padding-right: 0px; padding-left: 0px; } .wrap__content { position: relative; } /*big bootstrap overwrite*/ .row { margin-right: 0px; margin-left: 0px; } @media only screen and (min-width: 768px) { .container { width: inherit; } } @media only screen and (min-width: 992px) { .container { width: 970px; } } @media only screen and (min-width: 1200px) { .container { width: 1170px; } } html, body { height: 100%; background-color: white; font-family: 'Nunito', sans-serif; } /* Wrapper for page content to push down footer */ #wrap { min-height: 100%; height: auto; /* Negative indent footer by its height */ margin: 0 auto -100px; /* Pad bottom by footer height */ padding: 0 0 100px; } /* Set the fixed height of the footer here */ #footer { height: 100px; background-color: #DC73FF; }
# <API key> ## Properties Name | Type | Description | Notes **kind** | **str** | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds | [optional] **api_version** | **str** | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#resources | [optional] **metadata** | [**UnversionedListMeta**](UnversionedListMeta.md) | | [optional] **items** | [**list[<API key>]**](<API key>.md) | | [[Back to Model list]](../README.md#<API key>) [[Back to API list]](../README.md#<API key>) [[Back to README]](../README.md)
include ../../../mk/pitchfork.mk # Local variables _NAME = pbsvtools $(_NAME)_REPO ?= git://github.com/PacificBiosciences/$(_NAME) _WRKSRC = $(WORKDIR)/$(_NAME) $(_NAME)_VERSION ?= HEAD _REVISION = $(shell cd $(_WRKSRC) && $(GIT) rev-parse --short $($(_NAME)_VERSION) || true) # Local works do-fetch: $(_WRKSRC) $(_WRKSRC): ifeq ($(wildcard $($(_NAME)_REPO)),) $(GIT) clone $($(_NAME)_REPO) $@ cd $(_WRKSRC) && $(GIT) checkout $($(_NAME)_VERSION) DEVOPT = else ln -sfn $($(_NAME)_REPO) $(_WRKSRC) DEVOPT = -e endif do-install: $(PREFIX)/var/pkg/$(_NAME) $(PREFIX)/var/pkg/$(_NAME): | do-fetch $(PIP) install --no-deps $(DEVOPT) $(_WRKSRC)/ @echo pip uninstall $(_NAME) > $@ @echo "# $(_REVISION)" >> $@ do-clean: do-distclean: cd $(_WRKSRC) && $(GIT) clean -xdf || true do-flush: rm -rf $(_WRKSRC)
#ifndef <API key> #define <API key> #include "../../graph/include/graph.hpp" namespace pasl { namespace graph { /* Symmetric vertex */ template <class Vertex_id_bag> class symmetric_vertex { public: typedef Vertex_id_bag vtxid_bag_type; typedef typename vtxid_bag_type::value_type vtxid_type; symmetric_vertex() { } symmetric_vertex(vtxid_bag_type neighbors) : neighbors(neighbors) { } vtxid_bag_type neighbors; vtxid_type get_in_neighbor(vtxid_type j) const { return neighbors[j]; } vtxid_type get_out_neighbor(vtxid_type j) const { return neighbors[j]; } vtxid_type* get_in_neighbors() const { return neighbors.data(); } vtxid_type* get_out_neighbors() const { return neighbors.data(); } void set_in_neighbor(vtxid_type j, vtxid_type nbr) { neighbors[j] = nbr; } void set_out_neighbor(vtxid_type j, vtxid_type nbr) { neighbors[j] = nbr; } vtxid_type get_in_degree() const { return vtxid_type(neighbors.size()); } vtxid_type get_out_degree() const { return vtxid_type(neighbors.size()); } void set_in_degree(vtxid_type j) { neighbors.alloc(j); } // todo: use neighbors.resize() void set_out_degree(vtxid_type j) { neighbors.alloc(j); } void swap_in_neighbors(vtxid_bag_type& other) { neighbors.swap(other); } void swap_out_neighbors(vtxid_bag_type& other) { neighbors.swap(other); } void check(vtxid_type nb_vertices) const { #ifndef NDEBUG for (vtxid_type i = 0; i < neighbors.size(); i++) check_vertex(neighbors[i], nb_vertices); #endif } }; /* Asymmetric vertex */ template <class Vertex_id_bag> class asymmetric_vertex { public: typedef Vertex_id_bag vtxid_bag_type; typedef typename vtxid_bag_type::value_type vtxid_type; vtxid_bag_type in_neighbors; vtxid_bag_type out_neighbors; vtxid_type get_in_neighbor(vtxid_type j) const { return in_neighbors[j]; } vtxid_type get_out_neighbor(vtxid_type j) const { return out_neighbors[j]; } vtxid_type* get_in_neighbors() const { return in_neighbors.data(); } vtxid_type* get_out_neighbors() const { return out_neighbors.data(); } void set_in_neighbor(vtxid_type j, vtxid_type nbr) { in_neighbors[j] = nbr; } void set_out_neighbor(vtxid_type j, vtxid_type nbr) { out_neighbors[j] = nbr; } vtxid_type get_in_degree() const { return vtxid_type(in_neighbors.size()); } vtxid_type get_out_degree() const { return vtxid_type(out_neighbors.size()); } void set_in_degree(vtxid_type j) { in_neighbors.alloc(j); } void set_out_degree(vtxid_type j) { out_neighbors.alloc(j); } void swap_in_neighbors(vtxid_bag_type& other) { in_neighbors.swap(other); } void swap_out_neighbors(vtxid_bag_type& other) { out_neighbors.swap(other); } void check(vtxid_type nb_vertices) const { for (vtxid_type i = 0; i < in_neighbors.size(); i++) check_vertex(in_neighbors[i], nb_vertices); for (vtxid_type i = 0; i < out_neighbors.size(); i++) check_vertex(out_neighbors[i], nb_vertices); } }; /* Adjacency-list format */ template <class Adjlist_seq> class adjlist { public: typedef Adjlist_seq adjlist_seq_type; typedef typename adjlist_seq_type::value_type vertex_type; typedef typename vertex_type::vtxid_bag_type::value_type vtxid_type; typedef typename adjlist_seq_type::alias_type <API key>; typedef adjlist<<API key>> alias_type; edgeid_type nb_edges; adjlist_seq_type adjlists; adjlist() : nb_edges(0) { } adjlist(edgeid_type nb_edges) : nb_edges(nb_edges) { } vtxid_type get_nb_vertices() const { return vtxid_type(adjlists.size()); } void check() const { #ifndef NDEBUG for (vtxid_type i = 0; i < adjlists.size(); i++) adjlists[i].check(get_nb_vertices()); size_t m = 0; for (vtxid_type i = 0; i < adjlists.size(); i++) m += adjlists[i].get_in_degree(); assert(m == nb_edges); m = 0; for (vtxid_type i = 0; i < adjlists.size(); i++) m += adjlists[i].get_out_degree(); assert(m == nb_edges); #endif } }; /* Equality operators */ template <class Vertex_id_bag> bool operator==(const symmetric_vertex<Vertex_id_bag>& v1, const symmetric_vertex<Vertex_id_bag>& v2) { using vtxid_type = typename symmetric_vertex<Vertex_id_bag>::vtxid_type; if (v1.get_out_degree() != v2.get_out_degree()) return false; for (vtxid_type i = 0; i < v1.get_out_degree(); i++) if (v1.get_out_neighbor(i) != v2.get_out_neighbor(i)) return false; return true; } template <class Vertex_id_bag> bool operator!=(const symmetric_vertex<Vertex_id_bag>& v1, const symmetric_vertex<Vertex_id_bag>& v2) { return ! (v1 == v2); } template <class Adjlist_seq> bool operator==(const adjlist<Adjlist_seq>& g1, const adjlist<Adjlist_seq>& g2) { using vtxid_type = typename adjlist<Adjlist_seq>::vtxid_type; if (g1.get_nb_vertices() != g2.get_nb_vertices()) return false; if (g1.nb_edges != g2.nb_edges) return false; for (vtxid_type i = 0; i < g1.get_nb_vertices(); i++) if (g1.adjlists[i] != g2.adjlists[i]) return false; return true; } template <class Adjlist_seq> bool operator!=(const adjlist<Adjlist_seq>& g1, const adjlist<Adjlist_seq>& g2) { return ! (g1 == g2); } /* Flat adjacency-list format */ template <class Vertex_id, bool Is_alias = false> class flat_adjlist_seq { public: typedef flat_adjlist_seq<Vertex_id> self_type; typedef Vertex_id vtxid_type; typedef size_t size_type; typedef data::pointer_seq<vtxid_type> vertex_seq_type; typedef symmetric_vertex<vertex_seq_type> value_type; typedef flat_adjlist_seq<vtxid_type, true> alias_type; char* underlying_array; vtxid_type* offsets; vtxid_type nb_offsets; vtxid_type* edges; flat_adjlist_seq() : underlying_array(NULL), offsets(NULL), nb_offsets(0), edges(NULL) { } flat_adjlist_seq(const flat_adjlist_seq& other) { if (Is_alias) { underlying_array = other.underlying_array; offsets = other.offsets; nb_offsets = other.nb_offsets; edges = other.edges; } else { util::atomic::die("todo"); } } //! \todo instead of using Is_alias, pass either ptr_seq or array_seq as underlying_array ~flat_adjlist_seq() { if (! Is_alias) clear(); } void get_alias(alias_type& alias) const { alias.underlying_array = NULL; alias.offsets = offsets; alias.nb_offsets = nb_offsets; alias.edges = edges; } alias_type get_alias() const { alias_type alias; alias.underlying_array = NULL; alias.offsets = offsets; alias.nb_offsets = nb_offsets; alias.edges = edges; return alias; } void clear() { if (underlying_array != NULL) data::myfree(underlying_array); offsets = NULL; edges = NULL; } vtxid_type degree(vtxid_type v) const { assert(v >= 0); assert(v < size()); return offsets[v + 1] - offsets[v]; } value_type operator[](vtxid_type ix) const { assert(ix >= 0); assert(ix < size()); return value_type(vertex_seq_type(&edges[offsets[ix]], degree(ix))); } vtxid_type size() const { return nb_offsets - 1; } void swap(self_type& other) { std::swap(underlying_array, other.underlying_array); std::swap(offsets, other.offsets); std::swap(nb_offsets, other.nb_offsets); std::swap(edges, other.edges); } void alloc(size_type) { util::atomic::die("unsupported"); } void init(char* bytes, vtxid_type nb_vertices, edgeid_type nb_edges) { nb_offsets = nb_vertices + 1; underlying_array = bytes; offsets = (vtxid_type*)bytes; edges = &offsets[nb_offsets]; } value_type* data() { util::atomic::die("unsupported"); return NULL; } }; template <class Vertex_id, bool Is_alias = false> using flat_adjlist = adjlist<flat_adjlist_seq<Vertex_id, Is_alias>>; template <class Vertex_id> using flat_adjlist_alias = flat_adjlist<Vertex_id, true>; } // end namespace } // end namespace #endif /*! <API key> */
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="pt"> <head> <!-- Generated by javadoc (version 1.7.0_71) on Tue Jun 16 10:36:54 BRT 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class opennlp.tools.ml.model.<API key> (Apache OpenNLP Tools 1.6.0 API)</title> <meta name="date" content="2015-06-16"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class opennlp.tools.ml.model.<API key> (Apache OpenNLP Tools 1.6.0 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../opennlp/tools/ml/model/<API key>.html" title="class in opennlp.tools.ml.model">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?opennlp/tools/ml/model/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class opennlp.tools.ml.model.<API key>" class="title">Uses of Class<br>opennlp.tools.ml.model.<API key></h2> </div> <div class="classUseContainer">No usage of opennlp.tools.ml.model.<API key></div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../opennlp/tools/ml/model/<API key>.html" title="class in opennlp.tools.ml.model">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?opennlp/tools/ml/model/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
package org.anddev.andengine.opengl.texture; import java.util.*; import org.anddev.andengine.opengl.texture.source.*; import org.anddev.andengine.util.*; import org.anddev.andengine.opengl.texture.builder.*; import android.graphics.*; public class BuildableTexture extends Texture { private final ArrayList<<API key>> <API key>; public BuildableTexture(final int n, final int n2) { super(n, n2, TextureOptions.DEFAULT, null); this.<API key> = new ArrayList<<API key>>(); } public BuildableTexture(final int n, final int n2, final <API key> <API key>) { super(n, n2, TextureOptions.DEFAULT, <API key>); this.<API key> = new ArrayList<<API key>>(); } public BuildableTexture(final int n, final int n2, final TextureOptions textureOptions) throws <API key> { super(n, n2, textureOptions, null); this.<API key> = new ArrayList<<API key>>(); } public BuildableTexture(final int n, final int n2, final TextureOptions textureOptions, final <API key> <API key>) throws <API key> { super(n, n2, textureOptions, <API key>); this.<API key> = new ArrayList<<API key>>(); } @Deprecated @Override public <API key> addTextureSource(final ITextureSource textureSource, final int n, final int n2) { return super.addTextureSource(textureSource, n, n2); } public void addTextureSource(final ITextureSource textureSource, final Callback<<API key>> callback) { this.<API key>.add(new <API key>(textureSource, callback)); } public void build(final ITextureBuilder textureBuilder) throws ITextureBuilder.<API key> { textureBuilder.pack(this, this.<API key>); this.<API key>.clear(); this.<API key> = true; } @Override public void clearTextureSources() { super.clearTextureSources(); this.<API key>.clear(); } public void removeTextureSource(final ITextureSource textureSource) { final ArrayList<<API key>> <API key> = this.<API key>; for (int i = -1 + <API key>.size(); i >= 0; --i) { if (<API key>.get(i).mTextureSource == textureSource) { <API key>.remove(i); this.<API key> = true; return; } } } public static class <API key> implements ITextureSource { private final Callback<<API key>> mCallback; private final ITextureSource mTextureSource; public <API key>(final ITextureSource mTextureSource, final Callback<<API key>> mCallback) { super(); this.mTextureSource = mTextureSource; this.mCallback = mCallback; } @Override public <API key> clone() { return null; } public Callback<<API key>> getCallback() { return this.mCallback; } @Override public int getHeight() { return this.mTextureSource.getHeight(); } public ITextureSource getTextureSource() { return this.mTextureSource; } @Override public int getWidth() { return this.mTextureSource.getWidth(); } @Override public Bitmap onLoadBitmap() { return this.mTextureSource.onLoadBitmap(); } @Override public String toString() { return this.mTextureSource.toString(); } } }
//Not using strict: uneven strict support in browsers, #392, and causes //problems with requirejs.exec()/transpiler plugins that may not be strict. /*jslint regexp: true, nomen: true, sloppy: true */ /*global window, navigator, document, importScripts, setTimeout, opera */ var requirejs, require, define; (function (global) { var req, s, head, baseElement, dataMain, src, interactiveScript, <API key>, mainScript, subPath, version = '2.1.15', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, currDirRegExp = /^\.\ op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty, ap = Array.prototype, apsp = ap.splice, isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, // then 'complete'. The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, defContextName = '_', //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', contexts = {}, cfg = {}, globalDefQueue = [], useInteractive = false; function isFunction(it) { return ostring.call(it) === '[object Function]'; } function isArray(it) { return ostring.call(it) === '[object Array]'; } /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } /** * Helper function for iterating over an array backwards. If the func * returns a true value, it will break out of the loop. */ function eachReverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } function hasProp(obj, prop) { return hasOwn.call(obj, prop); } function getOwn(obj, prop) { return hasProp(obj, prop) && obj[prop]; } /** * Cycles over properties in an object and calls a function for each * property value. If the function returns a truthy value, then the * iteration is stopped. */ function eachProp(obj, func) { var prop; for (prop in obj) { if (hasProp(obj, prop)) { if (func(obj[prop], prop)) { break; } } } } /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. */ function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value === 'object' && value && !isArray(value) && !isFunction(value) && !(value instanceof RegExp)) { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; } //Similar to Function.prototype.bind, but the 'this' object is specified //first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; } function scripts() { return document.<API key>('script'); } function defaultOnError(err) { throw err; } //Allow getting a global that is expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function (part) { g = g[part]; }); return g; } /** * Constructs an error with a pointer to an URL with more information. * @param {String} id the error ID that maps to an ID on a web page. * @param {String} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html e.requireType = id; e.requireModules = requireModules; if (err) { e.originalError = err; } return e; } if (typeof define !== 'undefined') { //If a define is already in play via another AMD loader, //do not overwrite. return; } if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { //Do not overwrite an existing requirejs instance. return; } cfg = requirejs; requirejs = undefined; } //Allow for a require config object if (typeof require !== 'undefined' && !isFunction(require)) { //assume it is a config object. cfg = require; require = undefined; } function newContext(contextName) { var inCheckLoaded, Module, context, handlers, <API key>, config = { //Defaults. Do not set a default for map //config to speed up normalize(), which //will run faster if there is no default. waitSeconds: 7, baseUrl: './', paths: {}, bundles: {}, pkgs: {}, shim: {}, config: {} }, registry = {}, //registry of just enabled modules, to speed //cycle breaking code when lots of modules //are registered, but not activated. enabledRegistry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, bundlesMap = {}, requireCounter = 1, unnormalizedCounter = 1; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; i < ary.length; i++) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { // If at the start, or previous value is still .., // keep them so that when converted to a path it may // still work when converted to a path, even though // as an ID it is less than ideal. In larger point // releases, may be better to just kick out an error. if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') { continue; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @param {Boolean} applyMap apply the map config to the value. Should * only be done if this normalization is for a dependency ID. * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, foundMap, foundI, foundStarMap, starI, normalizedBaseParts, baseParts = (baseName && baseName.split('/')), map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name) { name = name.split('/'); lastIndex = name.length - 1; // If wanting node ID compatibility, strip .js from end // of IDs. Have to do this here, and not in nameToUrl // because node allows either .js or non .js to map // to same file. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } // Starts with a '.' so need the baseName if (name[0].charAt(0) === '.' && baseParts) { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); name = normalizedBaseParts.concat(name); } trimDots(name); name = name.join('/'); } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); outerLoop: for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = getOwn(map, baseParts.slice(0, j).join('/')); //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = getOwn(mapValue, nameSegment); if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break outerLoop; } } } } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { foundStarMap = getOwn(starMap, nameSegment); starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } // If the name points to a package's name, use // the package main instead. pkgMain = getOwn(config.pkgs, name); return pkgMain ? pkgMain : name; } function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } } function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); //Custom require that does not do map translation, since //ID is "absolute", already mapped/resolved. context.makeRequire(null, { skipMap: true })([id]); return true; } } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * @param {Boolean} isNormalized: is the ID already normalized. * This is true if this call is done for a define() module ID. * @param {Boolean} applyMap: apply the map config to the ID. * Should only be true if this map is for a dependency. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } nameParts = splitPrefix(name); prefix = nameParts[0]; name = nameParts[1]; if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = getOwn(defined, prefix); } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { // If nested plugin references, then do not try to // normalize, as it will not normalize correctly. This // places a restriction on resourceIds, and the longer // term solution is not to normalize until plugins are // loaded and all normalizations to allow for async // loading of a loader plugin. But for now, fixes the // common uses. Details in #1131 normalizedName = name.indexOf('!') === -1 ? normalize(name, parentName, applyMap) : name; } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); //Normalized name may be a plugin ID due to map config //application in normalize. The map config values must //already be normalized, so do not need to redo that part. nameParts = splitPrefix(normalizedName); prefix = nameParts[0]; normalizedName = nameParts[1]; isNormalized = true; url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix }; } function getModule(depMap) { var id = depMap.id, mod = getOwn(registry, id); if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; } function on(depMap, name, fn) { var id = depMap.id, mod = getOwn(registry, id); if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { mod = getModule(depMap); if (mod.error && name === 'error') { fn(mod.error); } else { mod.on(name, fn); } } } function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } } /** * Internal method to transfer globalQueue items to this context's * defQueue. */ function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(defQueue, [defQueue.length, 0].concat(globalDefQueue)); globalDefQueue = []; } } handlers = { 'require': function (mod) { if (mod.require) { return mod.require; } else { return (mod.require = context.makeRequire(mod.map)); } }, 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { return (defined[mod.map.id] = mod.exports); } else { return (mod.exports = defined[mod.map.id] = {}); } } }, 'module': function (mod) { if (mod.module) { return mod.module; } else { return (mod.module = { id: mod.map.id, uri: mod.map.url, config: function () { return getOwn(config.config, mod.map.id) || {}; }, exports: mod.exports || (mod.exports = {}) }); } } }; function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; delete enabledRegistry[id]; } function breakCycle(mod, traced, processed) { var id = mod.map.id; if (mod.error) { mod.emit('error', mod.error); } else { traced[id] = true; each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); //Only force things that have not completed //being defined, so still in the registry, //and only if it has not been matched up //in the module already. if (dep && !mod.depMatched[i] && !processed[depId]) { if (getOwn(traced, depId)) { mod.defineDep(i, defined[depId]); mod.check(); //pass false? } else { breakCycle(dep, traced, processed); } } }); processed[id] = true; } } function checkLoaded() { var err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], reqCalls = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(enabledRegistry, function (mod) { var map = mod.map, modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!map.isDefine) { reqCalls.push(mod); } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !<API key>) { <API key> = setTimeout(function () { <API key> = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; } Module = function (map) { this.events = getOwn(undefEvents, map.id) || {}; this.map = map; this.shim = getOwn(config.shim, map.id); this.depExports = []; this.depMaps = []; this.depMatched = []; this.pluginMaps = {}; this.depCount = 0; /* this.exports this.factory this.depMaps = [], this.enabled, this.fetched */ }; Module.prototype = { init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there //are multiple define calls for the same module. That is not //a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { //Register for errors on this module. this.on('error', errback); } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. errback = bind(this, function (err) { this.emit('error', err); }); } //Do a copy of the dependency array, so that //source inputs are not modified. For example //"shim" deps are passed in here directly, and //doing a direct modification of the depMaps array //would affect that config. this.depMaps = depMaps && depMaps.slice(0); this.errback = errback; //Indicate this module has be initialized this.inited = true; this.ignore = options.ignore; //Could have option to init this module in enabled mode, //or could have been previously marked as enabled. However, //the dependencies are not known until init is called. So //if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { //Enable this module and dependencies. //Will call this.check() this.enable(); } else { this.check(); } }, defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { this.depMatched[i] = true; this.depCount -= 1; this.depExports[i] = depExports; } }, fetch: function () { if (this.fetched) { return; } this.fetched = true; context.startTime = (new Date()).getTime(); var map = this.map; //If the manager is for a plugin managed resource, //ask the plugin to load it now. if (this.shim) { context.makeRequire(this.map, { enableBuildCallback: true })(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { //Regular dependency. return map.prefix ? this.callPlugin() : this.load(); } }, load: function () { var url = this.map.url; //Regular dependency. if (!urlFetched[url]) { urlFetched[url] = true; context.load(this.map.id, url); } }, /** * Checks if the module is ready to define itself, and if so, * define it. */ check: function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. However, //only do it for define()'d modules. require //errbacks should not be called for failures in //their callbacks (#699). However if a global //onError is set, use that. if ((this.events.error && this.map.isDefine) || req.onError !== defaultOnError) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { err = e; } } else { exports = context.execCb(id, factory, depExports, exports); } // Favor return value over exports. If node/cjs in play, // then will not have a return value anyway. Favor // module.exports assignment over exports object. if (this.map.isDefine && exports === undefined) { cjsModule = this.module; if (cjsModule) { exports = cjsModule.exports; } else if (this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = this.map.isDefine ? [this.map.id] : null; err.requireType = this.map.isDefine ? 'define' : 'require'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { req.onResourceLoad(context, this.map, this.depMaps); } } //Clean up cleanRegistry(id); this.defined = true; } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } }, callPlugin: function () { var map = this.map, id = map.id, //Map already normalized the prefix. pluginMap = makeModuleMap(map.prefix); //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(pluginMap); on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, bundleId = getOwn(bundlesMap, this.map.id), name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null, localRequire = context.makeRequire(map.parentMap, { enableBuildCallback: true }); //If current map is not normalized, wait for that //normalized name to load instead of continuing. if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } //prefix and name should already be normalized, no need //for applying map config again either. normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap); on(normalizedMap, 'defined', bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true, ignore: true }); })); normalizedMod = getOwn(registry, normalizedMap.id); if (normalizedMod) { //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(normalizedMap); if (this.events.error) { normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } normalizedMod.enable(); } return; } //If a paths config, then just load that file instead to //resolve the plugin, as it is built into that paths layer. if (bundleId) { this.map.url = context.nameToUrl(bundleId); this.load(); return; } load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true }); }); load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { cleanRegistry(mod.map.id); } }); onError(err); }); //Allow plugins to load other code without having to know the //context or how to 'complete' the load. load.fromText = bind(this, function (text, textAlt) { /*jslint evil: true */ var moduleName = map.name, moduleMap = makeModuleMap(moduleName), hasInteractive = useInteractive; //As of 2.1.0, support just passing the text, to reinforce //fromText only being called once per resource. Still //support old style of passing moduleName but discard //that moduleName in favor of the internal ref. if (textAlt) { text = textAlt; } //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } //Prime the system by creating a module instance for getModule(moduleMap); //Transfer any config to this other module. if (hasProp(config.config, id)) { config.config[moduleName] = config.config[id]; } try { req.exec(text); } catch (e) { return onError(makeError('fromtexteval', 'fromText eval for ' + id + ' failed: ' + e, e, [id])); } if (hasInteractive) { useInteractive = true; } //Mark this as a dependency for the plugin //resource this.depMaps.push(moduleMap); //Support anonymous modules. context.completeLoad(moduleName); //Bind the value of that module to the value for this //resource ID. localRequire([moduleName], load); }); //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. plugin.load(map.name, localRequire, load, config); })); context.enable(pluginMap, this); this.pluginMaps[pluginMap.id] = pluginMap; }, enable: function () { enabledRegistry[this.map.id] = this; this.enabled = true; //Set flag mentioning that the module is enabling, //so that immediate calls to the defined callbacks //for dependencies do not trigger inadvertent load //with the depCount still being zero. this.enabling = true; //Enable each dependency each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), false, !this.skipMap); this.depMaps[i] = depMap; handler = getOwn(handlers, depMap.id); if (handler) { this.depExports[i] = handler(this); return; } this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', bind(this, this.errback)); } } id = depMap.id; mod = registry[id]; //Skip special modules like 'require', 'exports', 'module' //Also, don't call enable if it is already enabled, //important in circular dependency cases. if (!hasProp(handlers, id) && mod && !mod.enabled) { context.enable(depMap, this); } })); //Enable each plugin that is used in //a dependency eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = getOwn(registry, pluginMap.id); if (mod && !mod.enabled) { context.enable(pluginMap, this); } })); this.enabling = false; this.check(); }, on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit: function (name, evt) { each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { //Now that the error handler was triggered, remove //the listeners, since this broken Module instance //can stay around for a while in the registry. delete this.events[name]; } } }; function callGetModule(args) { //Skip modules already defined. if (!hasProp(defined, args[0])) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } } function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } } /** * Given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * @param {Event} evt * @returns {Object} */ function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; } function intakeDefines() { var args; //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } } context = { config: config, contextName: contextName, registry: registry, defined: defined, urlFetched: urlFetched, defQueue: defQueue, Module: Module, makeModuleMap: makeModuleMap, nextTick: req.nextTick, onError: onError, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } //Save off the paths since they require special processing, //they are additive. var shim = config.shim, objs = { paths: true, bundles: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { if (!config[prop]) { config[prop] = {}; } mixin(config[prop], value, true, true); } else { config[prop] = value; } }); //Reverse map the bundles if (cfg.bundles) { eachProp(cfg.bundles, function (value, prop) { each(value, function (v) { if (v !== prop) { bundlesMap[v] = prop; } }); }); } //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { deps: value }; } if ((value.exports || value.init) && !value.exportsFn) { value.exportsFn = context.makeShimExports(value); } shim[id] = value; }); config.shim = shim; } //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { var location, name; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; name = pkgObj.name; location = pkgObj.location; if (location) { config.paths[name] = pkgObj.location; } //Save pointer to main module ID for pkg name. //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') .replace(currDirRegExp, '') .replace(jsSuffixRegExp, ''); }); } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { mod.map = makeModuleMap(id); } }); //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, makeShimExports: function (value) { function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); } return fn; }, makeRequire: function (relMap, options) { options = options || {}; function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //If require|exports|module are requested, get the //value for them from the special handlers. Caveat: //this only works while module is being defined. if (relMap && hasProp(handlers, deps)) { return handlers[deps](registry[relMap.id]); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. map = makeModuleMap(deps, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); } return defined[id]; } //Grab defines waiting in the global queue. intakeDefines(); //Mark all the dependencies as needing to be loaded. context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); requireMod = getModule(makeModuleMap(null, relMap)); //Store if map config should be applied to this require //call for dependencies. requireMod.skipMap = options.skipMap; requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); }); return localRequire; } mixin(localRequire, { isBrowser: isBrowser, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt) { var ext, index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; //Have a file extension alias, and it is not the //dots from a relative path. if (index !== -1 && (!isRelative || index > 1)) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, true), ext, true); }, defined: function (id) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, specified: function (id) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); } }); //Only allow undef on top level require calls if (!relMap) { localRequire.undef = function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); removeScript(id); delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; //Clean queued defines too. Go backwards //in array so that the splices do not //mess up the iteration. eachReverse(defQueue, function (args, i) { if (args[0] === id) { defQueue.splice(i, 1); } }); if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded //using a different config. if (mod.events.defined) { undefEvents[id] = mod.events; } cleanRegistry(id); } }; } return localRequire; }, /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, * is passed in for context, when this method is overridden by * the optimizer. Not shown here to keep code compact. */ enable: function (depMap) { var mod = getOwn(registry, depMap.id); if (mod) { getModule(depMap).enable(); } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var found, args, mod, shim = getOwn(config.shim, moduleName) || {}, shExports = shim.exports; takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; //If already found an anonymous module and bound it //to this name, then this is some other anon module //waiting for its completeLoad to fire. if (found) { break; } found = true; } else if (args[0] === moduleName) { //Found matching define call for this script! found = true; } callGetModule(args); } //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. mod = getOwn(registry, moduleName); if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { if (hasPathFallback(moduleName)) { return; } else { return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName])); } } else { //A script that does not call define(), so just simulate //the call for it. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); } } checkLoaded(); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. * Note that it **does not** call normalize on the moduleName, * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ nameToUrl: function (moduleName, ext, skipExt) { var paths, syms, i, parentModule, url, parentPath, bundleId, pkgMain = getOwn(config.pkgs, moduleName); if (pkgMain) { moduleName = pkgMain; } bundleId = getOwn(bundlesMap, moduleName); if (bundleId) { return context.nameToUrl(bundleId, ext, skipExt); } //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //or ends with .js, then assume the user meant to use an url and not a module id. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext || ''); } else { //A module that needs to be converted to a path. paths = config.paths; syms = moduleName.split('/'); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, //Choose the one that is desired if (isArray(parentPath)) { parentPath = parentPath[0]; } syms.splice(0, i, parentPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. load: function (id, url) { req.load(context, id, url); }, /** * Executes a module callback function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. */ onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id])); } } }; context.require = context.makeRequire(); return context; } /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. * * Make a local req variable to help Caja compliance (it assumes things * on a require that are not standardized), and to give a short * name for minification/local scope use. */ req = requirejs = function (deps, callback, errback, optional) { //Find the right context, use default var context, config, contextName = defContextName; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== 'string') { // deps is a config object config = deps; if (isArray(callback)) { // Adjust args if there are dependencies deps = callback; callback = errback; errback = optional; } else { deps = []; } } if (config && config.context) { contextName = config.context; } context = getOwn(contexts, contextName); if (!context) { context = contexts[contextName] = req.s.newContext(contextName); } if (config) { context.configure(config); } return context.require(deps, callback, errback); }; /** * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ req.config = function (config) { return req(config); }; /** * Execute something after the current tick * of the event loop. Override for other envs * that have a better solution than setTimeout. * @param {Function} fn function to execute later. */ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 4); } : function (fn) { fn(); }; /** * Export require as a global, but only if it does not already exist. */ if (!require) { require = req; } req.version = version; //Used to filter out dependencies that are already paths. req.jsExtRegExp = /^\/|:|\?|\.js$/; req.isBrowser = isBrowser; s = req.s = { contexts: contexts, newContext: newContext }; //Create default context. req({}); //Exports some context-sensitive methods on global require. each([ 'toUrl', 'undef', 'defined', 'specified' ], function (prop) { //Reference from contexts instead of early binding to default context, //so that during builds, the latest instance of the default context //with its config gets used. req[prop] = function () { var ctx = contexts[defContextName]; return ctx.require[prop].apply(ctx, arguments); }; }); if (isBrowser) { head = s.head = document.<API key>('head')[0]; //If BASE tag is in play, using appendChild is a problem for IE6. //When that browser dies, this can be removed. Details in this jQuery bug: baseElement = document.<API key>('base')[0]; if (baseElement) { head = s.head = baseElement.parentNode; } } /** * Any errors that require explicitly generates will be passed to this * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ req.onError = defaultOnError; /** * Creates the node for the load command. Only used in browser envs. */ req.createNode = function (config, moduleName, url) { var node = config.xhtml ? document.createElementNS('http: document.createElement('script'); node.type = config.scriptType || 'text/javascript'; node.charset = 'utf-8'; node.async = true; return node; }; /** * Does the request to load a module for the browser case. * Make this a separate function to allow other environments * to override it. * * @param {Object} context the require context to find state. * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ req.load = function (context, moduleName, url) { var config = (context && context.config) || {}, node; if (isBrowser) { //In the browser so use a script tag node = req.createNode(config, moduleName, url); node.setAttribute('data-requirecontext', context.contextName); node.setAttribute('data-requiremodule', moduleName); //Set up load listener. Test attachEvent first because IE9 has //a subtle issue in its addEventListener and script onload firings //that do not match the behavior of all other browsers with //addEventListener support, which fire the onload event for a //script right after the script execution. See: //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && //Check if node.attachEvent is artificially added by custom script or //natively supported by browser //if we can NOT find [native code] then it must NOT natively supported. //in IE8, node.attachEvent does not have toString() //Note the test for "[native code" with no closing brace, see: !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. //However, IE reports the script as being in 'interactive' //readyState at the time of the define call. useInteractive = true; node.attachEvent('onreadystatechange', context.onScriptLoad); //It would be great to add an error handler here to catch //404s in IE9+. However, onreadystatechange will fire before //the error handler, so that does not help. If addEventListener //is used, then IE will fire error before load, but we cannot //use that pathway given the connect.microsoft.com issue //mentioned above about not doing the 'script execute, //then fire the script load event listener before execute //next script' that other browsers do. //Best hope: IE10 fixes the issues, //and then destroys all installs of IE 6-9. //node.attachEvent('onerror', context.onScriptError); } else { node.addEventListener('load', context.onScriptLoad, false); node.addEventListener('error', context.onScriptError, false); } node.src = url; //For some cache cases in IE 6-8, the script executes before the end //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. <API key> = node; if (baseElement) { head.insertBefore(node, baseElement); } else { head.appendChild(node); } <API key> = null; return node; } else if (isWebWorker) { try { //In a web worker, use importScripts. This is not a very //efficient use of importScripts, importScripts will block until //its script is downloaded and evaluated. However, if web workers //are in play, the expectation that a build has been done so that //only one script needs to be loaded anyway. This may need to be //reevaluated if other use cases become common. importScripts(url); //Account for anonymous modules context.completeLoad(moduleName); } catch (e) { context.onError(makeError('importscripts', 'importScripts failed for ' + moduleName + ' at ' + url, e, [moduleName])); } } }; function <API key>() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } }); return interactiveScript; } //Look for a data-main script attribute, which could also adjust the baseUrl. if (isBrowser && !cfg.skipDataMain) { //Figure out baseUrl. Get it from the script tag with require.js in it. eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by //using the script's parent. if (!head) { head = script.parentNode; } //Look for a data-main attribute to set main script for the page //to load. If it is there, the path to data main becomes the //baseUrl, if it is not already set. dataMain = script.getAttribute('data-main'); if (dataMain) { //Preserve dataMain in case it is a path (i.e. contains '?') mainScript = dataMain; //Set final baseUrl if there is not already an explicit one. if (!cfg.baseUrl) { //Pull off the directory of data-main for use as the //baseUrl. src = mainScript.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; } //Strip off any trailing .js since mainScript is now //like a module name. mainScript = mainScript.replace(jsSuffixRegExp, ''); //If mainScript is still a path, fall back to dataMain if (req.jsExtRegExp.test(mainScript)) { mainScript = dataMain; } //Put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; return true; } }); } /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ define = function (name, deps, callback) { var node, context; //Allow for anonymous modules if (typeof name !== 'string') { //Adjust args appropriately callback = deps; deps = name; name = null; } //This module may not have dependencies if (!isArray(deps)) { callback = deps; deps = null; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. if (!deps && isFunction(callback)) { deps = []; //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { callback .toString() .replace(commentRegExp, '') .replace(cjsRequireRegExp, function (match, dep) { deps.push(dep); }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module //work though if it just needs require. //REQUIRES the function to expect the CommonJS variables in the //order listed below. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } } //If in IE 6-8 and hit an anonymous define() call, do the interactive //work. if (useInteractive) { node = <API key> || <API key>(); if (node) { if (!name) { name = node.getAttribute('data-requiremodule'); } context = contexts[node.getAttribute('data-requirecontext')]; } } //Always save off evaluating the def call until the script onload handler. //This allows multiple modules to be in a file without prematurely //tracing dependencies, and allows for anonymous module support, //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); }; define.amd = { jQuery: true }; /** * Executes the text. Normally just uses eval, but can be modified * to use a better, <API key> call. Only used for transpiling * loader plugins, not for plain JS modules. * @param {String} text the text to execute/evaluate. */ req.exec = function (text) { /*jslint evil: true */ return eval(text); }; //Set up with config info. req(cfg); }(this));
import application = require("application"); // Specify custom <API key>. /* class MyDelegate extends UIResponder implements <API key> { public static ObjCProtocols = [<API key>]; <API key>(application: UIApplication, launchOptions: NSDictionary): boolean { console.log("<API key>: " + launchOptions) return true; } <API key>(application: UIApplication): void { console.log("<API key>: " + application) } } application.ios.delegate = MyDelegate; */ if (application.ios) { // Observe application notifications. application.ios.<API key>(<API key>, (notification: NSNotification) => { console.log("<API key>: " + notification) }); } application.mainModule = "app/mainPage"; // Common events for both Android and iOS. application.on(application.launchEvent, function (args: application.<API key>) { if (args.android) { // For Android applications, args.android is an android.content.Intent class. console.log("Launched Android application with the following intent: " + args.android + "."); } else if (args.ios !== undefined) { // For iOS applications, args.ios is NSDictionary (launchOptions). console.log("Launched iOS application with options: " + args.ios); } }); application.on(application.suspendEvent, function (args: application.<API key>) { if (args.android) { // For Android applications, args.android is an android activity class. console.log("Activity: " + args.android); } else if (args.ios) { // For iOS applications, args.ios is UIApplication. console.log("UIApplication: " + args.ios); } }); application.on(application.resumeEvent, function (args: application.<API key>) { if (args.android) { // For Android applications, args.android is an android activity class. console.log("Activity: " + args.android); } else if (args.ios) { // For iOS applications, args.ios is UIApplication. console.log("UIApplication: " + args.ios); } }); application.on(application.exitEvent, function (args: application.<API key>) { if (args.android) { // For Android applications, args.android is an android activity class. console.log("Activity: " + args.android); } else if (args.ios) { // For iOS applications, args.ios is UIApplication. console.log("UIApplication: " + args.ios); } }); application.on(application.lowMemoryEvent, function (args: application.<API key>) { if (args.android) { // For Android applications, args.android is an android activity class. console.log("Activity: " + args.android); } else if (args.ios) { // For iOS applications, args.ios is UIApplication. console.log("UIApplication: " + args.ios); } }); application.on(application.uncaughtErrorEvent, function (args: application.<API key>) { if (args.android) { // For Android applications, args.android is an NativeScriptError. console.log("NativeScriptError: " + args.android); } else if (args.ios) { // For iOS applications, args.ios is NativeScriptError. console.log("NativeScriptError: " + args.ios); } }); // Android activity events if (application.android) { application.android.on(application.AndroidApplication.<API key>, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity + ", Bundle: " + args.bundle); }); application.android.on(application.AndroidApplication.<API key>, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity); }); application.android.on(application.AndroidApplication.<API key>, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity); }); application.android.on(application.AndroidApplication.activityPausedEvent, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity); }); application.android.on(application.AndroidApplication.<API key>, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity); }); application.android.on(application.AndroidApplication.<API key>, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity); }); application.android.on(application.AndroidApplication.<API key>, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity + ", Bundle: " + args.bundle); }); application.android.on(application.AndroidApplication.activityResultEvent, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity + ", requestCode: " + args.requestCode + ", resultCode: " + args.resultCode + ", Intent: " + args.intent); }); application.android.on(application.AndroidApplication.<API key>, function (args: application.<API key>) { console.log("Event: " + args.eventName + ", Activity: " + args.activity); // Set args.cancel = true to cancel back navigation and do something custom. }); } application.start();
/ [variadicTuples1.ts] // Variadics in tuple types type TV0<T extends unknown[]> = [string, ...T]; type TV1<T extends unknown[]> = [string, ...T, number]; type TV2<T extends unknown[]> = [string, ...T, number, ...T]; type TV3<T extends unknown[]> = [string, ...T, ...number[], ...T]; // Normalization type TN1 = TV1<[boolean, string]>; type TN2 = TV1<[]>; type TN3 = TV1<[boolean?]>; type TN4 = TV1<string[]>; type TN5 = TV1<[boolean] | [symbol, symbol]>; type TN6 = TV1<any>; type TN7 = TV1<never>; // Variadics in array literals function tup2<T extends unknown[], U extends unknown[]>(t: [...T], u: [...U]) { return [1, ...t, 2, ...u, 3] as const; } const t2 = tup2(['hello'], [10, true]); function concat<T extends unknown[], U extends unknown[]>(t: [...T], u: [...U]): [...T, ...U] { return [...t, ...u]; } declare const sa: string[]; const tc1 = concat([], []); const tc2 = concat(['hello'], [42]); const tc3 = concat([1, 2, 3], sa); const tc4 = concat(sa, [1, 2, 3]); // Ideally would be [...string[], number, number, number] function concat2<T extends readonly unknown[], U extends readonly unknown[]>(t: T, u: U) { return [...t, ...u]; // (T[number] | U[number])[] } const tc5 = concat2([1, 2, 3] as const, [4, 5, 6] as const); // (1 | 2 | 3 | 4 | 5 | 6)[] // Spread arguments declare function foo1(a: number, b: string, c: boolean, ...d: number[]): void; function foo2(t1: [number, string], t2: [boolean], a1: number[]) { foo1(1, 'abc', true, 42, 43, 44); foo1(...t1, true, 42, 43, 44); foo1(...t1, ...t2, 42, 43, 44); foo1(...t1, ...t2, ...a1); foo1(...t1); // Error foo1(...t1, 45); // Error } declare function foo3<T extends unknown[]>(x: number, ...args: [...T, number]): T; function foo4<U extends unknown[]>(u: U) { foo3(1, 2); foo3(1, 'hello', true, 2); foo3(1, ...u, 'hi', 2); foo3(1); } // Contextual typing of array literals declare function ft1<T extends unknown[]>(t: T): T; declare function ft2<T extends unknown[]>(t: T): readonly [...T]; declare function ft3<T extends unknown[]>(t: [...T]): T; declare function ft4<T extends unknown[]>(t: [...T]): readonly [...T]; ft1(['hello', 42]); // (string | number)[] ft2(['hello', 42]); // readonly (string | number)[] ft3(['hello', 42]); // [string, number] ft4(['hello', 42]); // readonly [string, number] // Indexing variadic tuple types function f0<T extends unknown[]>(t: [string, ...T], n: number) { const a = t[0]; // string const b = t[1]; // [string, ...T][1] const c = t[2]; // [string, ...T][2] const d = t[n]; // [string, ...T][number] } function f1<T extends unknown[]>(t: [string, ...T, number], n: number) { const a = t[0]; // string const b = t[1]; // [string, ...T, number][1] const c = t[2]; // [string, ...T, number][2] const d = t[n]; // [string, ...T, number][number] } // Destructuring variadic tuple types function f2<T extends unknown[]>(t: [string, ...T]) { let [...ax] = t; // [string, ...T] let [b1, ...bx] = t; // string, [...T] let [c1, c2, ...cx] = t; // string, [string, ...T][1], T[number][] } function f3<T extends unknown[]>(t: [string, ...T, number]) { let [...ax] = t; // [string, ...T, number] let [b1, ...bx] = t; // string, [...T, number] let [c1, c2, ...cx] = t; // string, [string, ...T, number][1], (number | T[number])[] } // Mapped types applied to variadic tuple types type Arrayify<T> = { [P in keyof T]: T[P][] }; type TM1<U extends unknown[]> = Arrayify<readonly [string, number?, ...U, ...boolean[]]>; // [string[], (number | undefined)[]?, Arrayify<U>, ...boolean[][]] type TP1<T extends unknown[]> = Partial<[string, ...T, number]>; // [string?, Partial<T>, number?] type TP2<T extends unknown[]> = Partial<[string, ...T, ...number[]]>; // [string?, Partial<T>, ...(number | undefined)[]] // Reverse mapping through mapped type applied to variadic tuple type declare function fm1<T extends unknown[]>(t: Arrayify<[string, number, ...T]>): T; let tm1 = fm1([['abc'], [42], [true], ['def']]); // [boolean, string] // Spread of readonly array-like infers mutable array-like declare function fx1<T extends unknown[]>(a: string, ...args: T): T; function gx1<U extends unknown[], V extends readonly unknown[]>(u: U, v: V) { fx1('abc'); fx1('abc', ...u); fx1('abc', ...v); fx1<U>('abc', ...u); fx1<V>('abc', ...v); // Error } declare function fx2<T extends readonly unknown[]>(a: string, ...args: T): T; function gx2<U extends unknown[], V extends readonly unknown[]>(u: U, v: V) { fx2('abc'); fx2('abc', ...u); fx2('abc', ...v); fx2<U>('abc', ...u); fx2<V>('abc', ...v); } // Relations involving variadic tuple types function f10<T extends string[], U extends T>(x: [string, ...unknown[]], y: [string, ...T], z: [string, ...U]) { x = y; x = z; y = x; // Error y = z; z = x; // Error z = y; // Error } // For a generic type T, [...T] is assignable to T, T is assignable to readonly [...T], and T is assignable // to [...T] when T is constrained to a mutable array or tuple type. function f11<T extends unknown[]>(t: T, m: [...T], r: readonly [...T]) { t = m; t = r; // Error m = t; m = r; // Error r = t; r = m; } function f12<T extends readonly unknown[]>(t: T, m: [...T], r: readonly [...T]) { t = m; t = r; // Error m = t; // Error m = r; // Error r = t; r = m; } function f13<T extends string[], U extends T>(t0: T, t1: [...T], t2: [...U]) { t0 = t1; t0 = t2; t1 = t0; t1 = t2; t2 = t0; // Error t2 = t1; // Error } function f14<T extends readonly string[], U extends T>(t0: T, t1: [...T], t2: [...U]) { t0 = t1; t0 = t2; t1 = t0; // Error t1 = t2; t2 = t0; // Error t2 = t1; // Error } function f15<T extends string[], U extends T>(k0: keyof T, k1: keyof [...T], k2: keyof [...U], k3: keyof [1, 2, ...T]) { k0 = 'length'; k1 = 'length'; k2 = 'length'; k0 = 'slice'; k1 = 'slice'; k2 = 'slice'; k3 = '0'; k3 = '1'; k3 = '2'; // Error } // Inference between variadic tuple types type First<T extends readonly unknown[]> = T extends readonly [unknown, ...unknown[]] ? T[0] : T[0] | undefined; type DropFirst<T extends readonly unknown[]> = T extends readonly [unknown?, ...infer U] ? U : [...T]; type Last<T extends readonly unknown[]> = T extends readonly [...unknown[], infer U] ? U : T extends readonly [unknown, ...unknown[]] ? T[number] : T[number] | undefined; type DropLast<T extends readonly unknown[]> = T extends readonly [...infer U, unknown] ? U : [...T]; type T00 = First<[number, symbol, string]>; type T01 = First<[symbol, string]>; type T02 = First<[string]>; type T03 = First<[number, symbol, ...string[]]>; type T04 = First<[symbol, ...string[]]>; type T05 = First<[string?]>; type T06 = First<string[]>; type T07 = First<[]>; type T08 = First<any>; type T09 = First<never>; type T10 = DropFirst<[number, symbol, string]>; type T11 = DropFirst<[symbol, string]>; type T12 = DropFirst<[string]>; type T13 = DropFirst<[number, symbol, ...string[]]>; type T14 = DropFirst<[symbol, ...string[]]>; type T15 = DropFirst<[string?]>; type T16 = DropFirst<string[]>; type T17 = DropFirst<[]>; type T18 = DropFirst<any>; type T19 = DropFirst<never>; type T20 = Last<[number, symbol, string]>; type T21 = Last<[symbol, string]>; type T22 = Last<[string]>; type T23 = Last<[number, symbol, ...string[]]>; type T24 = Last<[symbol, ...string[]]>; type T25 = Last<[string?]>; type T26 = Last<string[]>; type T27 = Last<[]>; type T28 = Last<any>; type T29 = Last<never>; type T30 = DropLast<[number, symbol, string]>; type T31 = DropLast<[symbol, string]>; type T32 = DropLast<[string]>; type T33 = DropLast<[number, symbol, ...string[]]>; type T34 = DropLast<[symbol, ...string[]]>; type T35 = DropLast<[string?]>; type T36 = DropLast<string[]>; type T37 = DropLast<[]>; // unknown[], maybe should be [] type T38 = DropLast<any>; type T39 = DropLast<never>; type R00 = First<readonly [number, symbol, string]>; type R01 = First<readonly [symbol, string]>; type R02 = First<readonly [string]>; type R03 = First<readonly [number, symbol, ...string[]]>; type R04 = First<readonly [symbol, ...string[]]>; type R05 = First<readonly string[]>; type R06 = First<readonly []>; type R10 = DropFirst<readonly [number, symbol, string]>; type R11 = DropFirst<readonly [symbol, string]>; type R12 = DropFirst<readonly [string]>; type R13 = DropFirst<readonly [number, symbol, ...string[]]>; type R14 = DropFirst<readonly [symbol, ...string[]]>; type R15 = DropFirst<readonly string[]>; type R16 = DropFirst<readonly []>; type R20 = Last<readonly [number, symbol, string]>; type R21 = Last<readonly [symbol, string]>; type R22 = Last<readonly [string]>; type R23 = Last<readonly [number, symbol, ...string[]]>; type R24 = Last<readonly [symbol, ...string[]]>; type R25 = Last<readonly string[]>; type R26 = Last<readonly []>; type R30 = DropLast<readonly [number, symbol, string]>; type R31 = DropLast<readonly [symbol, string]>; type R32 = DropLast<readonly [string]>; type R33 = DropLast<readonly [number, symbol, ...string[]]>; type R34 = DropLast<readonly [symbol, ...string[]]>; type R35 = DropLast<readonly string[]>; type R36 = DropLast<readonly []>; // Inference to [...T, ...U] with implied arity for T function curry<T extends unknown[], U extends unknown[], R>(f: (...args: [...T, ...U]) => R, ...a: T) { return (...b: U) => f(...a, ...b); } const fn1 = (a: number, b: string, c: boolean, d: string[]) => 0; const c0 = curry(fn1); // (a: number, b: string, c: boolean, d: string[]) => number const c1 = curry(fn1, 1); // (b: string, c: boolean, d: string[]) => number const c2 = curry(fn1, 1, 'abc'); // (c: boolean, d: string[]) => number const c3 = curry(fn1, 1, 'abc', true); // (d: string[]) => number const c4 = curry(fn1, 1, 'abc', true, ['x', 'y']); // () => number const fn2 = (x: number, b: boolean, ...args: string[]) => 0; const c10 = curry(fn2); // (x: number, b: boolean, ...args: string[]) => number const c11 = curry(fn2, 1); // (b: boolean, ...args: string[]) => number const c12 = curry(fn2, 1, true); // (...args: string[]) => number const c13 = curry(fn2, 1, true, 'abc', 'def'); // (...args: string[]) => number const fn3 = (...args: string[]) => 0; const c20 = curry(fn3); // (...args: string[]) => number const c21 = curry(fn3, 'abc', 'def'); // (...args: string[]) => number const c22 = curry(fn3, ...sa); // (...args: string[]) => number // No inference to [...T, ...U] when there is no implied arity function curry2<T extends unknown[], U extends unknown[], R>(f: (...args: [...T, ...U]) => R, t: [...T], u: [...U]) { return f(...t, ...u); } declare function fn10(a: string, b: number, c: boolean): string[]; curry2(fn10, ['hello', 42], [true]); curry2(fn10, ['hello'], [42, true]); // Inference to [...T] has higher priority than inference to [...T, number?] declare function ft<T extends unknown[]>(t1: [...T], t2: [...T, number?]): T; ft([1, 2, 3], [1, 2, 3]); ft([1, 2], [1, 2, 3]); ft(['a', 'b'], ['c', 'd']) ft(['a', 'b'], ['c', 'd', 42]) // Last argument is contextually typed declare function call<T extends unknown[], R>(...args: [...T, (...args: T) => R]): [T, R]; call('hello', 32, (a, b) => 42); call(...sa, (...x) => 42); // No inference to ending optional elements (except with identical structure) declare function f20<T extends unknown[] = []>(args: [...T, number?]): T; function f21<U extends string[]>(args: [...U, number?]) { let v1 = f20(args); let v2 = f20(["foo", "bar"]); // [string] let v3 = f20(["foo", 42]); // [string] } declare function f22<T extends unknown[] = []>(args: [...T, number]): T; declare function f22<T extends unknown[] = []>(args: [...T]): T; function f23<U extends string[]>(args: [...U, number]) { let v1 = f22(args); let v2 = f22(["foo", "bar"]); // [string, string] let v3 = f22(["foo", 42]); // [string] } // Repro from #39327 interface Desc<A extends unknown[], T> { readonly f: (...args: A) => T; bind<T extends unknown[], U extends unknown[], R>(this: Desc<[...T, ...U], R>, ...args: T): Desc<[...U], R>; } declare const a: Desc<[string, number, boolean], object>; const b = a.bind("", 1); // Desc<[boolean], object> // Repro from #39607 declare function getUser(id: string, options?: { x?: string }): string; declare function getOrgUser(id: string, orgId: number, options?: { y?: number, z?: boolean }): void; function callApi<T extends unknown[] = [], U = void>(method: (...args: [...T, object]) => U) { return (...args: [...T]) => method(...args, {}); } callApi(getUser); callApi(getOrgUser); // Repro from #40235 type Numbers = number[]; type Unbounded = [...Numbers, boolean]; const data: Unbounded = [false, false]; // Error type U1 = [string, ...Numbers, boolean]; type U2 = [...[string, ...Numbers], boolean]; type U3 = [...[string, number], boolean]; / [variadicTuples1.js] "use strict"; // Variadics in tuple types var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; // Variadics in array literals function tup2(t, u) { return __spreadArray(__spreadArray(__spreadArray(__spreadArray([1], t, true), [2], false), u, true), [3], false); } var t2 = tup2(['hello'], [10, true]); function concat(t, u) { return __spreadArray(__spreadArray([], t, true), u, true); } var tc1 = concat([], []); var tc2 = concat(['hello'], [42]); var tc3 = concat([1, 2, 3], sa); var tc4 = concat(sa, [1, 2, 3]); // Ideally would be [...string[], number, number, number] function concat2(t, u) { return __spreadArray(__spreadArray([], t, true), u, true); // (T[number] | U[number])[] } var tc5 = concat2([1, 2, 3], [4, 5, 6]); // (1 | 2 | 3 | 4 | 5 | 6)[] function foo2(t1, t2, a1) { foo1(1, 'abc', true, 42, 43, 44); foo1.apply(void 0, __spreadArray(__spreadArray([], t1, false), [true, 42, 43, 44], false)); foo1.apply(void 0, __spreadArray(__spreadArray(__spreadArray([], t1, false), t2, false), [42, 43, 44], false)); foo1.apply(void 0, __spreadArray(__spreadArray(__spreadArray([], t1, false), t2, false), a1, false)); foo1.apply(void 0, t1); // Error foo1.apply(void 0, __spreadArray(__spreadArray([], t1, false), [45], false)); // Error } function foo4(u) { foo3(1, 2); foo3(1, 'hello', true, 2); foo3.apply(void 0, __spreadArray(__spreadArray([1], u, false), ['hi', 2], false)); foo3(1); } ft1(['hello', 42]); // (string | number)[] ft2(['hello', 42]); // readonly (string | number)[] ft3(['hello', 42]); // [string, number] ft4(['hello', 42]); // readonly [string, number] // Indexing variadic tuple types function f0(t, n) { var a = t[0]; // string var b = t[1]; // [string, ...T][1] var c = t[2]; // [string, ...T][2] var d = t[n]; // [string, ...T][number] } function f1(t, n) { var a = t[0]; // string var b = t[1]; // [string, ...T, number][1] var c = t[2]; // [string, ...T, number][2] var d = t[n]; // [string, ...T, number][number] } // Destructuring variadic tuple types function f2(t) { var ax = t.slice(0); // [string, ...T] var b1 = t[0], bx = t.slice(1); // string, [...T] var c1 = t[0], c2 = t[1], cx = t.slice(2); // string, [string, ...T][1], T[number][] } function f3(t) { var ax = t.slice(0); // [string, ...T, number] var b1 = t[0], bx = t.slice(1); // string, [...T, number] var c1 = t[0], c2 = t[1], cx = t.slice(2); // string, [string, ...T, number][1], (number | T[number])[] } var tm1 = fm1([['abc'], [42], [true], ['def']]); // [boolean, string] function gx1(u, v) { fx1('abc'); fx1.apply(void 0, __spreadArray(['abc'], u, false)); fx1.apply(void 0, __spreadArray(['abc'], v, false)); fx1.apply(void 0, __spreadArray(['abc'], u, false)); fx1.apply(void 0, __spreadArray(['abc'], v, false)); // Error } function gx2(u, v) { fx2('abc'); fx2.apply(void 0, __spreadArray(['abc'], u, false)); fx2.apply(void 0, __spreadArray(['abc'], v, false)); fx2.apply(void 0, __spreadArray(['abc'], u, false)); fx2.apply(void 0, __spreadArray(['abc'], v, false)); } // Relations involving variadic tuple types function f10(x, y, z) { x = y; x = z; y = x; // Error y = z; z = x; // Error z = y; // Error } // For a generic type T, [...T] is assignable to T, T is assignable to readonly [...T], and T is assignable // to [...T] when T is constrained to a mutable array or tuple type. function f11(t, m, r) { t = m; t = r; // Error m = t; m = r; // Error r = t; r = m; } function f12(t, m, r) { t = m; t = r; // Error m = t; // Error m = r; // Error r = t; r = m; } function f13(t0, t1, t2) { t0 = t1; t0 = t2; t1 = t0; t1 = t2; t2 = t0; // Error t2 = t1; // Error } function f14(t0, t1, t2) { t0 = t1; t0 = t2; t1 = t0; // Error t1 = t2; t2 = t0; // Error t2 = t1; // Error } function f15(k0, k1, k2, k3) { k0 = 'length'; k1 = 'length'; k2 = 'length'; k0 = 'slice'; k1 = 'slice'; k2 = 'slice'; k3 = '0'; k3 = '1'; k3 = '2'; // Error } // Inference to [...T, ...U] with implied arity for T function curry(f) { var a = []; for (var _i = 1; _i < arguments.length; _i++) { a[_i - 1] = arguments[_i]; } return function () { var b = []; for (var _i = 0; _i < arguments.length; _i++) { b[_i] = arguments[_i]; } return f.apply(void 0, __spreadArray(__spreadArray([], a, false), b, false)); }; } var fn1 = function (a, b, c, d) { return 0; }; var c0 = curry(fn1); // (a: number, b: string, c: boolean, d: string[]) => number var c1 = curry(fn1, 1); // (b: string, c: boolean, d: string[]) => number var c2 = curry(fn1, 1, 'abc'); // (c: boolean, d: string[]) => number var c3 = curry(fn1, 1, 'abc', true); // (d: string[]) => number var c4 = curry(fn1, 1, 'abc', true, ['x', 'y']); // () => number var fn2 = function (x, b) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return 0; }; var c10 = curry(fn2); // (x: number, b: boolean, ...args: string[]) => number var c11 = curry(fn2, 1); // (b: boolean, ...args: string[]) => number var c12 = curry(fn2, 1, true); // (...args: string[]) => number var c13 = curry(fn2, 1, true, 'abc', 'def'); // (...args: string[]) => number var fn3 = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return 0; }; var c20 = curry(fn3); // (...args: string[]) => number var c21 = curry(fn3, 'abc', 'def'); // (...args: string[]) => number var c22 = curry.apply(void 0, __spreadArray([fn3], sa, false)); // (...args: string[]) => number // No inference to [...T, ...U] when there is no implied arity function curry2(f, t, u) { return f.apply(void 0, __spreadArray(__spreadArray([], t, false), u, false)); } curry2(fn10, ['hello', 42], [true]); curry2(fn10, ['hello'], [42, true]); ft([1, 2, 3], [1, 2, 3]); ft([1, 2], [1, 2, 3]); ft(['a', 'b'], ['c', 'd']); ft(['a', 'b'], ['c', 'd', 42]); call('hello', 32, function (a, b) { return 42; }); call.apply(void 0, __spreadArray(__spreadArray([], sa, false), [function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return 42; }], false)); function f21(args) { var v1 = f20(args); var v2 = f20(["foo", "bar"]); // [string] var v3 = f20(["foo", 42]); // [string] } function f23(args) { var v1 = f22(args); var v2 = f22(["foo", "bar"]); // [string, string] var v3 = f22(["foo", 42]); // [string] } var b = a.bind("", 1); // Desc<[boolean], object> function callApi(method) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return method.apply(void 0, __spreadArray(__spreadArray([], args, false), [{}], false)); }; } callApi(getUser); callApi(getOrgUser); var data = [false, false]; // Error / [variadicTuples1.d.ts] declare type TV0<T extends unknown[]> = [string, ...T]; declare type TV1<T extends unknown[]> = [string, ...T, number]; declare type TV2<T extends unknown[]> = [string, ...T, number, ...T]; declare type TV3<T extends unknown[]> = [string, ...T, ...number[], ...T]; declare type TN1 = TV1<[boolean, string]>; declare type TN2 = TV1<[]>; declare type TN3 = TV1<[boolean?]>; declare type TN4 = TV1<string[]>; declare type TN5 = TV1<[boolean] | [symbol, symbol]>; declare type TN6 = TV1<any>; declare type TN7 = TV1<never>; declare function tup2<T extends unknown[], U extends unknown[]>(t: [...T], u: [...U]): readonly [1, ...T, 2, ...U, 3]; declare const t2: readonly [1, string, 2, number, boolean, 3]; declare function concat<T extends unknown[], U extends unknown[]>(t: [...T], u: [...U]): [...T, ...U]; declare const sa: string[]; declare const tc1: []; declare const tc2: [string, number]; declare const tc3: [number, number, number, ...string[]]; declare const tc4: [...string[], number, number, number]; declare function concat2<T extends readonly unknown[], U extends readonly unknown[]>(t: T, u: U): (T[number] | U[number])[]; declare const tc5: (2 | 4 | 1 | 3 | 6 | 5)[]; declare function foo1(a: number, b: string, c: boolean, ...d: number[]): void; declare function foo2(t1: [number, string], t2: [boolean], a1: number[]): void; declare function foo3<T extends unknown[]>(x: number, ...args: [...T, number]): T; declare function foo4<U extends unknown[]>(u: U): void; declare function ft1<T extends unknown[]>(t: T): T; declare function ft2<T extends unknown[]>(t: T): readonly [...T]; declare function ft3<T extends unknown[]>(t: [...T]): T; declare function ft4<T extends unknown[]>(t: [...T]): readonly [...T]; declare function f0<T extends unknown[]>(t: [string, ...T], n: number): void; declare function f1<T extends unknown[]>(t: [string, ...T, number], n: number): void; declare function f2<T extends unknown[]>(t: [string, ...T]): void; declare function f3<T extends unknown[]>(t: [string, ...T, number]): void; declare type Arrayify<T> = { [P in keyof T]: T[P][]; }; declare type TM1<U extends unknown[]> = Arrayify<readonly [string, number?, ...U, ...boolean[]]>; declare type TP1<T extends unknown[]> = Partial<[string, ...T, number]>; declare type TP2<T extends unknown[]> = Partial<[string, ...T, ...number[]]>; declare function fm1<T extends unknown[]>(t: Arrayify<[string, number, ...T]>): T; declare let tm1: [boolean, string]; declare function fx1<T extends unknown[]>(a: string, ...args: T): T; declare function gx1<U extends unknown[], V extends readonly unknown[]>(u: U, v: V): void; declare function fx2<T extends readonly unknown[]>(a: string, ...args: T): T; declare function gx2<U extends unknown[], V extends readonly unknown[]>(u: U, v: V): void; declare function f10<T extends string[], U extends T>(x: [string, ...unknown[]], y: [string, ...T], z: [string, ...U]): void; declare function f11<T extends unknown[]>(t: T, m: [...T], r: readonly [...T]): void; declare function f12<T extends readonly unknown[]>(t: T, m: [...T], r: readonly [...T]): void; declare function f13<T extends string[], U extends T>(t0: T, t1: [...T], t2: [...U]): void; declare function f14<T extends readonly string[], U extends T>(t0: T, t1: [...T], t2: [...U]): void; declare function f15<T extends string[], U extends T>(k0: keyof T, k1: keyof [...T], k2: keyof [...U], k3: keyof [1, 2, ...T]): void; declare type First<T extends readonly unknown[]> = T extends readonly [unknown, ...unknown[]] ? T[0] : T[0] | undefined; declare type DropFirst<T extends readonly unknown[]> = T extends readonly [unknown?, ...infer U] ? U : [...T]; declare type Last<T extends readonly unknown[]> = T extends readonly [...unknown[], infer U] ? U : T extends readonly [unknown, ...unknown[]] ? T[number] : T[number] | undefined; declare type DropLast<T extends readonly unknown[]> = T extends readonly [...infer U, unknown] ? U : [...T]; declare type T00 = First<[number, symbol, string]>; declare type T01 = First<[symbol, string]>; declare type T02 = First<[string]>; declare type T03 = First<[number, symbol, ...string[]]>; declare type T04 = First<[symbol, ...string[]]>; declare type T05 = First<[string?]>; declare type T06 = First<string[]>; declare type T07 = First<[]>; declare type T08 = First<any>; declare type T09 = First<never>; declare type T10 = DropFirst<[number, symbol, string]>; declare type T11 = DropFirst<[symbol, string]>; declare type T12 = DropFirst<[string]>; declare type T13 = DropFirst<[number, symbol, ...string[]]>; declare type T14 = DropFirst<[symbol, ...string[]]>; declare type T15 = DropFirst<[string?]>; declare type T16 = DropFirst<string[]>; declare type T17 = DropFirst<[]>; declare type T18 = DropFirst<any>; declare type T19 = DropFirst<never>; declare type T20 = Last<[number, symbol, string]>; declare type T21 = Last<[symbol, string]>; declare type T22 = Last<[string]>; declare type T23 = Last<[number, symbol, ...string[]]>; declare type T24 = Last<[symbol, ...string[]]>; declare type T25 = Last<[string?]>; declare type T26 = Last<string[]>; declare type T27 = Last<[]>; declare type T28 = Last<any>; declare type T29 = Last<never>; declare type T30 = DropLast<[number, symbol, string]>; declare type T31 = DropLast<[symbol, string]>; declare type T32 = DropLast<[string]>; declare type T33 = DropLast<[number, symbol, ...string[]]>; declare type T34 = DropLast<[symbol, ...string[]]>; declare type T35 = DropLast<[string?]>; declare type T36 = DropLast<string[]>; declare type T37 = DropLast<[]>; declare type T38 = DropLast<any>; declare type T39 = DropLast<never>; declare type R00 = First<readonly [number, symbol, string]>; declare type R01 = First<readonly [symbol, string]>; declare type R02 = First<readonly [string]>; declare type R03 = First<readonly [number, symbol, ...string[]]>; declare type R04 = First<readonly [symbol, ...string[]]>; declare type R05 = First<readonly string[]>; declare type R06 = First<readonly []>; declare type R10 = DropFirst<readonly [number, symbol, string]>; declare type R11 = DropFirst<readonly [symbol, string]>; declare type R12 = DropFirst<readonly [string]>; declare type R13 = DropFirst<readonly [number, symbol, ...string[]]>; declare type R14 = DropFirst<readonly [symbol, ...string[]]>; declare type R15 = DropFirst<readonly string[]>; declare type R16 = DropFirst<readonly []>; declare type R20 = Last<readonly [number, symbol, string]>; declare type R21 = Last<readonly [symbol, string]>; declare type R22 = Last<readonly [string]>; declare type R23 = Last<readonly [number, symbol, ...string[]]>; declare type R24 = Last<readonly [symbol, ...string[]]>; declare type R25 = Last<readonly string[]>; declare type R26 = Last<readonly []>; declare type R30 = DropLast<readonly [number, symbol, string]>; declare type R31 = DropLast<readonly [symbol, string]>; declare type R32 = DropLast<readonly [string]>; declare type R33 = DropLast<readonly [number, symbol, ...string[]]>; declare type R34 = DropLast<readonly [symbol, ...string[]]>; declare type R35 = DropLast<readonly string[]>; declare type R36 = DropLast<readonly []>; declare function curry<T extends unknown[], U extends unknown[], R>(f: (...args: [...T, ...U]) => R, ...a: T): (...b: U) => R; declare const fn1: (a: number, b: string, c: boolean, d: string[]) => number; declare const c0: (a: number, b: string, c: boolean, d: string[]) => number; declare const c1: (b: string, c: boolean, d: string[]) => number; declare const c2: (c: boolean, d: string[]) => number; declare const c3: (d: string[]) => number; declare const c4: () => number; declare const fn2: (x: number, b: boolean, ...args: string[]) => number; declare const c10: (x: number, b: boolean, ...args: string[]) => number; declare const c11: (b: boolean, ...args: string[]) => number; declare const c12: (...b: string[]) => number; declare const c13: (...b: string[]) => number; declare const fn3: (...args: string[]) => number; declare const c20: (...b: string[]) => number; declare const c21: (...b: string[]) => number; declare const c22: (...b: string[]) => number; declare function curry2<T extends unknown[], U extends unknown[], R>(f: (...args: [...T, ...U]) => R, t: [...T], u: [...U]): R; declare function fn10(a: string, b: number, c: boolean): string[]; declare function ft<T extends unknown[]>(t1: [...T], t2: [...T, number?]): T; declare function call<T extends unknown[], R>(...args: [...T, (...args: T) => R]): [T, R]; declare function f20<T extends unknown[] = []>(args: [...T, number?]): T; declare function f21<U extends string[]>(args: [...U, number?]): void; declare function f22<T extends unknown[] = []>(args: [...T, number]): T; declare function f22<T extends unknown[] = []>(args: [...T]): T; declare function f23<U extends string[]>(args: [...U, number]): void; interface Desc<A extends unknown[], T> { readonly f: (...args: A) => T; bind<T extends unknown[], U extends unknown[], R>(this: Desc<[...T, ...U], R>, ...args: T): Desc<[...U], R>; } declare const a: Desc<[string, number, boolean], object>; declare const b: Desc<[boolean], object>; declare function getUser(id: string, options?: { x?: string; }): string; declare function getOrgUser(id: string, orgId: number, options?: { y?: number; z?: boolean; }): void; declare function callApi<T extends unknown[] = [], U = void>(method: (...args: [...T, object]) => U): (...args_0: T) => U; declare type Numbers = number[]; declare type Unbounded = [...Numbers, boolean]; declare const data: Unbounded; declare type U1 = [string, ...Numbers, boolean]; declare type U2 = [...[string, ...Numbers], boolean]; declare type U3 = [...[string, number], boolean];
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "- <html> <head> <title>groupby - org.saddle.groupby</title> <meta name="description" content="groupby - org.saddle.groupby" /> <meta name="keywords" content="groupby org.saddle.groupby" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'org.saddle.groupby.package'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="value"> <div id="definition"> <img src="../../../lib/package_big.png" /> <p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.saddle">saddle</a></p> <h1>groupby</h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <span class="name">groupby</span> </span> </h4> <div id="comment" class="fullcommenttop"></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="types" class="types members"> <h3>Type Members</h3> <ol><li name="org.saddle.groupby.FrameGrouper" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="FrameGrouper[Z,X,Y,T]extendsAnyRef"></a> <a id="FrameGrouper[Z,X,Y,T]:FrameGrouper[Z,X,Y,T]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <a href="FrameGrouper.html"><span class="name">FrameGrouper</span></a><span class="tparams">[<span name="Z">Z</span>, <span name="X">X</span>, <span name="Y">Y</span>, <span name="T">T</span>]</span><span class="result"> extends <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <p class="comment cmt">Helper class to do combine or transform after a groupBy </p> </li><li name="org.saddle.groupby.IndexGrouper" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="IndexGrouper[Y]extendsAnyRef"></a> <a id="IndexGrouper[Y]:IndexGrouper[Y]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <a href="IndexGrouper.html"><span class="name">IndexGrouper</span></a><span class="tparams">[<span name="Y">Y</span>]</span><span class="result"> extends <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <p class="comment cmt">Creates groups for each unique key in an index </p> </li><li name="org.saddle.groupby.SeriesGrouper" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="SeriesGrouper[Y,X,T]extendsIndexGrouper[Y]"></a> <a id="SeriesGrouper[Y,X,T]:SeriesGrouper[Y,X,T]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <a href="SeriesGrouper.html"><span class="name">SeriesGrouper</span></a><span class="tparams">[<span name="Y">Y</span>, <span name="X">X</span>, <span name="T">T</span>]</span><span class="result"> extends <a href="IndexGrouper.html" class="extype" name="org.saddle.groupby.IndexGrouper">IndexGrouper</a>[<span class="extype" name="org.saddle.groupby.SeriesGrouper.Y">Y</span>]</span> </span> </h4> <p class="comment cmt">Helper class to do combine or transform after a groupBy </p> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="org.saddle.groupby.FrameGrouper" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="FrameGrouper"></a> <a id="FrameGrouper:FrameGrouper"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <a href="FrameGrouper$.html"><span class="name">FrameGrouper</span></a> </span> </h4> </li><li name="org.saddle.groupby.IndexGrouper" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="IndexGrouper"></a> <a id="IndexGrouper:IndexGrouper"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <a href="IndexGrouper$.html"><span class="name">IndexGrouper</span></a> </span> </h4> </li><li name="org.saddle.groupby.SeriesGrouper" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="SeriesGrouper"></a> <a id="SeriesGrouper:SeriesGrouper"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <a href="SeriesGrouper$.html"><span class="name">SeriesGrouper</span></a> </span> </h4> </li></ol> </div> </div> <div id="inheritedMembers"> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> <script defer="defer" type="text/javascript" id="jquery-js" src="../../../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../../../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../../../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../../../lib/template.js"></script> </body> </html>
package io.agrest.it.fixture.cayenne; import io.agrest.it.fixture.cayenne.auto._E15E1; public class E15E1 extends _E15E1 { private static final long serialVersionUID = 1L; }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="pt"> <head> <!-- Generated by javadoc (version 1.7.0_71) on Tue Jun 16 10:37:20 BRT 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>opennlp.tools.doccat (Apache OpenNLP Tools 1.6.0 API)</title> <meta name="date" content="2015-06-16"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../opennlp/tools/doccat/package-summary.html" target="classFrame">opennlp.tools.doccat</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="<API key>.html" title="interface in opennlp.tools.doccat" target="classFrame"><i><API key></i></a></li> <li><a href="DocumentCategorizer.html" title="interface in opennlp.tools.doccat" target="classFrame"><i>DocumentCategorizer</i></a></li> <li><a href="FeatureGenerator.html" title="interface in opennlp.tools.doccat" target="classFrame"><i>FeatureGenerator</i></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="<API key>.html" title="class in opennlp.tools.doccat" target="classFrame"><API key></a></li> <li><a href="<API key>.html" title="class in opennlp.tools.doccat" target="classFrame"><API key></a></li> <li><a href="DoccatFactory.html" title="class in opennlp.tools.doccat" target="classFrame">DoccatFactory</a></li> <li><a href="DoccatModel.html" title="class in opennlp.tools.doccat" target="classFrame">DoccatModel</a></li> <li><a href="<API key>.html" title="class in opennlp.tools.doccat" target="classFrame"><API key></a></li> <li><a href="<API key>.html" title="class in opennlp.tools.doccat" target="classFrame"><API key></a></li> <li><a href="<API key>.html" title="class in opennlp.tools.doccat" target="classFrame"><API key></a></li> <li><a href="DocumentSample.html" title="class in opennlp.tools.doccat" target="classFrame">DocumentSample</a></li> <li><a href="<API key>.html" title="class in opennlp.tools.doccat" target="classFrame"><API key></a></li> <li><a href="<API key>.html" title="class in opennlp.tools.doccat" target="classFrame"><API key></a></li> </ul> </div> </body> </html>
<html> <head> <link rel="stylesheet" type="text/css" href="{{{host}}}/stylesheets/bootstrap.min.css"> <script src="{{{host}}}/javascripts/jquery-1.8.3.js"></script> <script src="{{{host}}}/javascripts/oauth2client.js"></script> <script src="{{{host}}}/{{{TILE_NAME}}}/javascripts/action.js"></script> <script> $(document).ready( function() { doIt( '{{{host}}}'); }); </script> </head> <body> <div id="<API key>" class="j-card" style='display: none'> <h2>Expanded Project Information ..</h2> <p> <p>The remote system (Basecamp) requires you to grant access before proceeding</p> <! Project: <label id="projectA"><b>Placeholder for Project</b> </label> <br> Description: <label id="descriptionA"><b>Placeholder for Description</b> </label> <br> <a id="BasecampLinkA" href="https://basecamp.com" target="_blank" >Vist this project at Basecamp</a> </p> <br><br> <button class="btn btn-primary" id="oauth">Grant Access</button> <button class="btn btn-primary" id="btn_doneA">Exit</button> </div> <div id="j-card-action" class="j-card" style='display: none'> <h3>Expanded Project Information ..</h3> <p> <h5><u>Project:</u></h5><br> <label id="projectB">Placeholder for Project</label> <br><br> <h5><u>Description:</u></h5> &nbsp;&nbsp; <br> <label id="descriptionB">Placeholder for Description</label> <br><br><br> <a id="BasecampLinkB" href="https://basecamp.com" target="_blank" >Vist this project at Basecamp</a> </p> <button class="btn btn-primary" id="btn_done">Close Window</button> </div> </body> </html>
#pragma once #include "generator/collector_interface.hpp" #include <fstream> #include <functional> #include <memory> #include <string> struct OsmElement; namespace base { class GeoObjectId; } // namespace base namespace generator { namespace cache { class <API key>; } // namespace cache // CollectorTag class collects validated value of a tag and saves it to file with following // format: osmId<tab>tagValue. class CollectorTag : public CollectorInterface { public: using Validator = std::function<bool(std::string const & tagValue)>; explicit CollectorTag(std::string const & filename, std::string const & tagKey, Validator const & validator); // CollectorInterface overrides: std::shared_ptr<CollectorInterface> Clone( std::shared_ptr<cache::<API key>> const & = {}) const override; void Collect(OsmElement const & el) override; void Finish() override; void Merge(CollectorInterface const & collector) override; void MergeInto(CollectorTag & collector) const override; protected: void Save() override; void OrderCollectedData() override; private: std::ofstream m_stream; std::string m_tagKey; Validator m_validator; }; } // namespace generator
#include "db_config.h" #include "db_int.h" /* * __os_id -- * Return the current process ID. * * PUBLIC: void __os_id __P((DB_ENV *, pid_t *, db_threadid_t*)); */ void __os_id(dbenv, pidp, tidp) DB_ENV *dbenv; pid_t *pidp; db_threadid_t *tidp; { /* * We can't depend on dbenv not being NULL, this routine is called * from places where there's no DB_ENV handle. * * We cache the pid in the ENV handle, getting the process ID is a * fairly slow call on lots of systems. */ if (pidp != NULL) { if (dbenv == NULL) { #if defined(HAVE_VXWORKS) *pidp = taskIdSelf(); #else *pidp = getpid(); #endif } else *pidp = dbenv->env->pid_cache; } if (tidp != NULL) { #if defined(DB_WIN32) *tidp = GetCurrentThreadId(); #elif defined(<API key>) *tidp = thr_self(); #elif defined(HAVE_PTHREAD_SELF) *tidp = pthread_self(); #else /* * Default to just getpid. */ *tidp = 0; #endif } }
@extends('dashboard.main') @section('styles') <meta name="lang" content="{{ \Session::get('locale') }}"> <link rel="stylesheet" href="{{ URL::to('libs/vendor/iCheck/skins/square/blue.css') }}"> <link rel="stylesheet" href="{{ URL::to('libs/vendor/<API key>/jquery.mCustomScrollbar.css') }}"> <link rel="stylesheet" href="{{ URL::to('libs/vendor/datetimepicker/jquery.datetimepicker.css') }}"> <link rel="stylesheet" href="{{ URL::to('libs/vendor/bootstrap-select/dist/css/bootstrap-select.css') }}"> @endsection @section('scripts') <script src="{{ URL::to('libs/vendor/moment/moment.js') }}"></script> <script src="{{ URL::to('libs/vendor/moment/locale/en-gb.js') }}"></script> <script src="{{ URL::to('libs/dashboard/moment-ru.js') }}"></script> <script src="{{ URL::to('libs/vendor/underscore/underscore.js') }}"></script> <script src="{{ URL::to('libs/dashboard/notify.min.js') }}"></script> <script src="{{ URL::to('libs/vendor/bootstrap-select/dist/js/bootstrap-select.js') }}"></script> <script src="{{ URL::to('libs/vendor/<API key>/jquery.mCustomScrollbar.js') }}"></script> <script src="{{ URL::to('libs/vendor/datetimepicker/build/jquery.datetimepicker.full.js') }}"></script> <script src="{{ URL::asset('libs/vendor/clndr/src/clndr.js') }}"></script> <script src="{{ URL::asset('libs/vendor/iCheck/icheck.js') }}"></script> <script src="{{ URL::to('libs/dashboard/schedule.js') }}"></script> @endsection @section('navigation') @include('dashboard.components.nav') @endsection @section('body-class', 'page-schedule') @section('content') <div id="full-clndr" class="clearfix"> @include('dashboard.components.clndr') </div> <div id="fountainTextG"><div id="fountainTextG_1" class="fountainTextG">L</div><div id="fountainTextG_2" class="fountainTextG">o</div><div id="fountainTextG_3" class="fountainTextG">a</div><div id="fountainTextG_4" class="fountainTextG">d</div><div id="fountainTextG_5" class="fountainTextG">i</div><div id="fountainTextG_6" class="fountainTextG">n</div><div id="fountainTextG_7" class="fountainTextG">g</div></div> <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">@lang('dashboard.components.scheduler.modal.modalTitle')</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="Title">@lang('dashboard.components.scheduler.modal.title')</label> <input type="text" class="form-control" id="Title" placeholder="@lang('dashboard.components.scheduler.modal.title')" title="@lang('dashboard.components.scheduler.modal.titleTip')"> </div> <div class="form-group"> <label for="Description">@lang('dashboard.components.scheduler.modal.desc')</label> <input type="text" class="form-control" id="Description" placeholder="@lang('dashboard.components.scheduler.modal.desc')"> </div> <div class="form-group"> <label for="playlist">@lang('dashboard.components.scheduler.modal.playlist')</label> <select class="selectpicker form-control" id="playlist" name="playlist"> <option value="0">@lang('dashboard.components.scheduler.modal.emptyPlaylist')</option> </select> </div> <div class="form-group"> <input type="checkbox" id="repeat-day"> <label for="repeat-day">@lang('dashboard.components.scheduler.modal.repeat.everyDay')</label> </div> <div class="form-group"> <input type="checkbox" id="repeat-month"> <label for="repeat-month">@lang('dashboard.components.scheduler.modal.repeat.everyWeek')</label> <div class="form-group" id="repeat-on"> <input type="checkbox" id="repeat-on-mon"> <label for="repeat-on-mon">@lang('dashboard.components.scheduler.modal.repeat.weeks.mon')</label> <input type="checkbox" id="repeat-on-tue"> <label for="repeat-on-tue">@lang('dashboard.components.scheduler.modal.repeat.weeks.tue')</label> <input type="checkbox" id="repeat-on-wed"> <label for="repeat-on-wed">@lang('dashboard.components.scheduler.modal.repeat.weeks.wed')</label> <input type="checkbox" id="repeat-on-thu"> <label for="repeat-on-thu">@lang('dashboard.components.scheduler.modal.repeat.weeks.thu')</label> <input type="checkbox" id="repeat-on-fri"> <label for="repeat-on-fri">@lang('dashboard.components.scheduler.modal.repeat.weeks.fri')</label> <input type="checkbox" id="repeat-on-sat"> <label for="repeat-on-sat">@lang('dashboard.components.scheduler.modal.repeat.weeks.sat')</label> <input type="checkbox" id="repeat-on-sun"> <label for="repeat-on-sun">@lang('dashboard.components.scheduler.modal.repeat.weeks.sun')</label> </div> </div> <div class="form-group"> <label for="datetimepicker">@lang('dashboard.components.scheduler.modal.datetime')</label> <input type="text" class="form-control" id="datetimepicker" placeholder="Datetime" autocomplete="off"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger pull-left delete-event">@lang('dashboard.core.buttons.delete')</button> <button type="button" class="btn btn-default" data-dismiss="modal">@lang('dashboard.core.buttons.close')</button> <button type="button" class="btn btn-primary save-changes">@lang('dashboard.core.buttons.save')</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> @endsection
package rule import ( "fmt" "github.com/mgechev/revive/lint" ) // <API key> lints given else constructs. type <API key> struct { blacklist map[string]bool } // Apply applies the rule to given file. func (r *<API key>) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { var failures []lint.Failure if file.IsTest() { return failures // skip, test file } if r.blacklist == nil { r.blacklist = make(map[string]bool, len(arguments)) for _, arg := range arguments { argStr, ok := arg.(string) if !ok { panic(fmt.Sprintf("Invalid argument to the imports-blacklist rule. Expecting a string, got %T", arg)) } // we add quotes if not present, because when parsed, the value of the AST node, will be quoted if len(argStr) > 2 && argStr[0] != '"' && argStr[len(argStr)-1] != '"' { argStr = fmt.Sprintf(`%q`, argStr) } r.blacklist[argStr] = true } } for _, is := range file.AST.Imports { path := is.Path if path != nil && r.blacklist[path.Value] { failures = append(failures, lint.Failure{ Confidence: 1, Failure: "should not use the following blacklisted import: " + path.Value, Node: is, Category: "imports", }) } } return failures } // Name returns the rule name. func (r *<API key>) Name() string { return "imports-blacklist" }
<?php defined('IN_IA') or exit('Access Denied'); /** * * @var int */ define('TEMPLATE_DISPLAY', 0); /** * * @var int */ define('TEMPLATE_FETCH', 1); /** * * @var int */ define('<API key>', 2); /** * @todo * @var int */ define('TEMPLATE_CACHE', 3); function template($filename, $flag = TEMPLATE_DISPLAY) { global $_W; $source = "{$_W['template']['source']}/{$_W['template']['current']}/{$filename}.html"; // exit($source); if(!is_file($source)) { $source = "{$_W['template']['source']}/default/{$filename}.html"; } if(!is_file($source)) { exit("Error: template source '{$filename}' is not exist!"); } $compile = "{$_W['template']['compile']}/{$_W['template']['current']}/{$filename}.tpl.php"; if (DEVELOPMENT || !is_file($compile) || filemtime($source) > filemtime($compile)) { template_compile($source, $compile); } switch ($flag) { case TEMPLATE_DISPLAY: default: extract($GLOBALS, EXTR_SKIP); include $compile; break; case TEMPLATE_FETCH: extract($GLOBALS, EXTR_SKIP); ob_start(); ob_clean(); include $compile; $contents = ob_get_contents(); ob_clean(); return $contents; break; case <API key>: return $compile; break; case TEMPLATE_CACHE: exit(''); break; } } function template_compile($from, $to) { $path = dirname($to); if (!is_dir($path)) mkdirs($path); $content = template_parse(file_get_contents($from)); file_put_contents($to, $content); } function template_parse($str) { $str = preg_replace('//s', '{$1}', $str); $str = preg_replace('/{template\s+(.+?)}/', '<?php include template($1, <API key>);?>', $str); $str = preg_replace('/{php\s+(.+?)}/', '<?php $1?>', $str); $str = preg_replace('/{if\s+(.+?)}/', '<?php if($1) { ?>', $str); $str = preg_replace('/{else}/', '<?php } else { ?>', $str); $str = preg_replace('/{else ?if\s+(.+?)}/', '<?php } else if($1) { ?>', $str); $str = preg_replace('/{\/if}/', '<?php } ?>', $str); $str = preg_replace('/{loop\s+(\S+)\s+(\S+)}/', '<?php if(is_array($1)) { foreach($1 as $2) { ?>', $str); $str = preg_replace('/{loop\s+(\S+)\s+(\S+)\s+(\S+)}/', '<?php if(is_array($1)) { foreach($1 as $2 => $3) { ?>', $str); $str = preg_replace('/{\/loop}/', '<?php } } ?>', $str); $str = preg_replace('/{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}/', '<?php echo $1;?>', $str); $str = preg_replace('/{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff\[\]\'\"\$]*)}/', '<?php echo $1;?>', $str); $str = preg_replace('/<\?php([^\?]+)\?>/es', "template_addquote('<?php$1?>')", $str); $str = preg_replace('/{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)}/s', '<?php echo $1;?>', $str); $str = str_replace('{##', '{', $str); $str = str_replace('##}', '}', $str); $str = "<?php defined('IN_IA') or exit('Access Denied');?>" . $str; return $str; } function template_addquote($code) { $code = preg_replace('/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s', "['$1']", $code); return str_replace('\\\"', '\"', $code); }
package com.intellij.openapi.diff.impl.settings; import com.intellij.icons.AllIcons; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.ToggleAction; import com.intellij.openapi.editor.Editor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; /** * The "gear" action allowing to configure merge tool visual preferences, such as displaying whitespaces, line numbers and soft wraps. * * @see DiffMergeSettings */ public class <API key> extends ActionGroup { @NotNull private final Collection<Editor> myEditors; @NotNull private final DiffMergeSettings mySettings; public <API key>(@NotNull Collection<Editor> editors, @NotNull DiffMergeSettings settings) { super("Settings", null, AllIcons.General.GearPlain); setPopup(true); myEditors = editors; mySettings = settings; } @NotNull @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { return new AnAction[] { new <API key>("<API key>", <API key>.WHITESPACES, myEditors, mySettings), new <API key>("<API key>", <API key>.LINE_NUMBERS, myEditors, mySettings), new <API key>("<API key>", <API key>.INDENT_LINES, myEditors, mySettings), new <API key>("<API key>", <API key>.SOFT_WRAPS, myEditors, mySettings) }; } private static class <API key> extends ToggleAction { @NotNull private final <API key> mySetting; @NotNull private final Collection<Editor> myEditors; @NotNull private final DiffMergeSettings mySettings; private <API key>(@NotNull String actionId, @NotNull <API key> setting, @NotNull Collection<Editor> editors, @NotNull DiffMergeSettings settings) { super(ActionsBundle.actionText(actionId), ActionsBundle.actionDescription(actionId), null); mySetting = setting; myEditors = editors; mySettings = settings; } @Override public boolean isSelected(@NotNull AnActionEvent e) { return getPreference(mySetting); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { setPreference(mySetting, state); for (Editor editor : myEditors) { mySetting.apply(editor, state); } } private void setPreference(<API key> preference, boolean state) { mySettings.setPreference(preference, state); } private boolean getPreference(<API key> preference) { return mySettings.getPreference(preference); } } }
package frc.team5333.lib; import java.util.HashMap; /** * A static class that contains all kinds of Launch data for the robot, * such as network ports, current state and more * * @author Jaci */ public class RobotData { /** * A blackboard containing objects that are common throughout the * program, along with their String Identifier */ public static HashMap<String, Object> blackboard = new HashMap<String, Object>(); }
function ChangeTo(to) { if (to == "text") { $('#admincommentlinks').ghide(); $('#admincomment').gshow(); resize('admincomment'); var buttons = document.getElementsByName('admincommentbutton'); for (var i = 0; i < buttons.length; i++) { buttons[i].setAttribute('onclick',"ChangeTo('links'); return false;"); } } else if (to == "links") { ajax.post("ajax.php?action=preview","form", function(response) { $('#admincommentlinks').raw().innerHTML = response; $('#admincomment').ghide(); $('#admincommentlinks').gshow(); var buttons = document.getElementsByName('admincommentbutton'); for (var i = 0; i < buttons.length; i++) { buttons[i].setAttribute('onclick',"ChangeTo('text'); return false;"); } }) } } function UncheckIfDisabled(checkbox) { if (checkbox.disabled) { checkbox.checked = false; } } function AlterParanoia() { // Required Ratio is almost deducible from downloaded, the count of seeding and the count of snatched // we will "warn" the user by automatically checking the required ratio box when they are // revealing that information elsewhere if (!$('input[name=p_ratio]').raw()) { return; } var showDownload = $('input[name=p_downloaded]').raw().checked || ($('input[name=p_uploaded]').raw().checked && $('input[name=p_ratio]').raw().checked); if (($('input[name=p_seeding_c]').raw().checked) && ($('input[name=p_snatched_c]').raw().checked) && showDownload) { $('input[type=checkbox][name=p_requiredratio]').raw().checked = true; $('input[type=checkbox][name=p_requiredratio]').raw().disabled = true; } else { $('input[type=checkbox][name=p_requiredratio]').raw().disabled = false; } $('input[name=p_torrentcomments_l]').raw().disabled = !$('input[name=p_torrentcomments_c]').raw().checked; $('input[name=p_collagecontribs_l]').raw().disabled = !$('input[name=p_collagecontribs_c]').raw().checked; $('input[name=<API key>]').raw().disabled = !($('input[name=<API key>]').raw().checked && $('input[name=<API key>]').raw().checked); $('input[name=<API key>]').raw().disabled = !($('input[name=<API key>]').raw().checked && $('input[name=<API key>]').raw().checked); $('input[name=p_uploads_l]').raw().disabled = !$('input[name=p_uploads_c]').raw().checked; $('input[name=p_uniquegroups_l]').raw().disabled = !$('input[name=p_uniquegroups_c]').raw().checked; $('input[name=p_perfectflacs_l]').raw().disabled = !$('input[name=p_perfectflacs_c]').raw().checked; $('input[name=p_seeding_l]').raw().disabled = !$('input[name=p_seeding_c]').raw().checked; $('input[name=p_leeching_l]').raw().disabled = !$('input[name=p_leeching_c]').raw().checked; $('input[name=p_snatched_l]').raw().disabled = !$('input[name=p_snatched_c]').raw().checked; UncheckIfDisabled($('input[name=p_torrentcomments_l]').raw()); UncheckIfDisabled($('input[name=p_collagecontribs_l]').raw()); UncheckIfDisabled($('input[name=<API key>]').raw()); UncheckIfDisabled($('input[name=<API key>]').raw()); UncheckIfDisabled($('input[name=p_uploads_l]').raw()); UncheckIfDisabled($('input[name=p_uniquegroups_l]').raw()); UncheckIfDisabled($('input[name=p_perfectflacs_l]').raw()); UncheckIfDisabled($('input[name=p_seeding_l]').raw()); UncheckIfDisabled($('input[name=p_leeching_l]').raw()); UncheckIfDisabled($('input[name=p_snatched_l]').raw()); // unique groups, "Perfect" FLACs and artists added are deducible from the list of uploads if ($('input[name=p_uploads_l]').raw().checked) { $('input[name=p_uniquegroups_c]').raw().checked = true; $('input[name=p_uniquegroups_l]').raw().checked = true; $('input[name=p_uniquegroups_c]').raw().disabled = true; $('input[name=p_uniquegroups_l]').raw().disabled = true; $('input[name=p_perfectflacs_c]').raw().checked = true; $('input[name=p_perfectflacs_l]').raw().checked = true; $('input[name=p_perfectflacs_c]').raw().disabled = true; $('input[name=p_perfectflacs_l]').raw().disabled = true; $('input[type=checkbox][name=p_artistsadded]').raw().checked = true; $('input[type=checkbox][name=p_artistsadded]').raw().disabled = true; } else { $('input[name=p_uniquegroups_c]').raw().disabled = false; $('input[name=p_uniquegroups_l]').raw().checked = false; $('input[name=p_uniquegroups_l]').raw().disabled = true; $('input[name=p_perfectflacs_c]').raw().disabled = false; $('input[type=checkbox][name=p_artistsadded]').raw().disabled = false; } if ($('input[name=p_collagecontribs_l]').raw().checked) { $('input[name=p_collages_c]').raw().disabled = true; $('input[name=p_collages_l]').raw().disabled = true; $('input[name=p_collages_c]').raw().checked = true; $('input[name=p_collages_l]').raw().checked = true; } else { $('input[name=p_collages_c]').raw().disabled = false; $('input[name=p_collages_l]').raw().disabled = !$('input[name=p_collages_c]').raw().checked; UncheckIfDisabled($('input[name=p_collages_l]').raw()); } } function ParanoiaReset(checkbox, drops) { var selects = $('select'); for (var i = 0; i < selects.results(); i++) { if (selects.raw(i).name.match(/^p_/)) { if (drops == 0) { selects.raw(i).selectedIndex = 0; } else if (drops == 1) { selects.raw(i).selectedIndex = selects.raw(i).options.length - 2; } else if (drops == 2) { selects.raw(i).selectedIndex = selects.raw(i).options.length - 1; } AlterParanoia(); } } var checkboxes = $(':checkbox'); for (var i = 0; i < checkboxes.results(); i++) { if (checkboxes.raw(i).name.match(/^p_/) && (checkboxes.raw(i).name != 'p_lastseen')) { if (checkbox == 3) { checkboxes.raw(i).checked = !(checkboxes.raw(i).name.match(/_list$/) || checkboxes.raw(i).name.match(/_l$/)); } else { checkboxes.raw(i).checked = checkbox; } AlterParanoia(); } } } function ParanoiaResetOff() { ParanoiaReset(true, 0); } function ParanoiaResetStats() { ParanoiaReset(3, 0); $('input[name=p_collages_l]').raw().checked = false; } function ParanoiaResetOn() { ParanoiaReset(false, 0); $('input[name=p_collages_c]').raw().checked = false; $('input[name=p_collages_l]').raw().checked = false; } addDOMLoadEvent(AlterParanoia); function ToggleWarningAdjust(selector) { if (selector.options[selector.selectedIndex].value == ' $('#ReduceWarningTR').gshow(); $('#ReduceWarning').raw().disabled = false; } else { $('#ReduceWarningTR').ghide(); $('#ReduceWarning').raw().disabled = true; } } addDOMLoadEvent(ToggleIdenticons); function ToggleIdenticons() { var disableAvatars = $('#disableavatars'); if (disableAvatars.size()) { var selected = disableAvatars[0].selectedIndex; if (selected == 2 || selected == 3) { $('#identicons').gshow(); } else { $('#identicons').ghide(); } } } function userform_submit() { if ($('#resetpasskey').is(':checked')) { if (!confirm('Are you sure you want to reset your passkey?')) { return false; } } return formVal(); } function togglePassKey(key) { if ($('#passkey').raw().innerHTML == 'View') { $('#passkey').raw().innerHTML = key; } else { $('#passkey').raw().innerHTML = 'View'; } } function commStats(userid) { $('.user_commstats').html('Loading...'); ajax.get('ajax.php?action=community_stats&userid=' + userid, function(JSONresponse) { var response = JSON.parse(JSONresponse) || false; if (!response || response.status == 'failure') { $('.user_commstats').html('An error occurred'); return; } displayCommStats(response.response); }); } function displayCommStats(stats) { var baseid = '#user_commstats_'; for (x in stats) { if (stats[x] === false) { continue; } switch (x) { case 'leeching': $(baseid + x).html(stats[x]); break; case 'seeding': $(baseid + x).html(stats[x]); break; case 'downloaded': $(baseid + x).html(stats[x]); break; case 'snatched': $(baseid + x).html(stats[x]); break; case 'usnatched': $(baseid + x).html('(' + stats[x] + ')'); break; case 'udownloaded': $(baseid + x).html('(' + stats[x] + ')'); break; case 'seedingperc': $(baseid + x).html('(' + stats[x] + '%)'); break; } } } $(document).ready(function() { $("#random_password").click(function() { var length = 15, charset = "<API key>!@ password = ""; for (var i = 0, n = charset.length; i < length; ++i) { password += charset.charAt(Math.floor(Math.random() * n)); } $('#change_password').val(password); }); });
#!/usr/bin/env perl # $Source: /cvsroot/ensembl/ensembl-personal/genebuilders/ccds/scripts/store_ccds_xrefs.pl,v $ # $Revision: 1.13 $ =pod =head1 NAME store_ccds_xrefs.pl =head1 SYNOPSIS Make CCDS Xrefs. =head1 DESCRIPTION Will store the Ensembl transcript stable_id that matches the ccds structure. Originally written for Ian Longden. Based on make_enst_to_ccds.pl =head1 ARGUMENTS perl store_ccds_xrefs.pl -ccds_dbname -ccds_host -ccds_port -ccds_user -ccds_pass -dbname -host -port -user -verbose -species -path -write -delete_old =head1 EXAMPLE perl $ENSEMBL_PERSONAL/genebuilders/ccds/scripts/store_ccds_xrefs.pl -ccds_dbname db8_human_vega_61 \ -ccds_host genebuild7 -ccds_port 3306 -ccds_user user -ccds_pass password \ -dbname <API key> -host ens-staging1 -port 3306 -user ensro -verbose \ -species human -path GRCh37 -write -delete_old =cut use warnings; use strict; use Getopt::Long; use Bio::EnsEMBL::DBSQL::DBAdaptor; use Bio::EnsEMBL::Utils::Exception qw(warning throw); # db of CCDS strcutures my $ccds_host = ''; my $ccds_port = '3306'; my $ccds_user = 'ensro'; my $ccds_pass = undef; my $ccds_dbname = ''; # db of Ensembl (protein_coding) genes my $host = 'ens-staging'; my $port = ''; my $user = 'ensro'; my $dbname = ''; my $path = 'GRCh37'; my $species = 'human'; my $verbose; my $write; my $delete_old; &GetOptions( 'ccds_host=s' => \$ccds_host, 'ccds_port=s' => \$ccds_port, 'ccds_user=s' => \$ccds_user, 'ccds_pass=s' => \$ccds_pass, 'ccds_dbname=s' => \$ccds_dbname, 'host=s' => \$host, 'port=s' => \$port, 'user=s' => \$user, 'dbname=s' => \$dbname, 'path=s' => \$path, 'species=s' => \$species, 'verbose' => \$verbose, 'delete_old' => \$delete_old, 'write' => \$write, ); if ( !defined $species ) { throw("Please define species as human or mouse"); } else { $species =~ s/\s if ( $species =~ /^human$/i || $species =~ /^mouse$/i ) { # we're ok print "Species is *$species*\n"; } else { throw("Species must be defined as human or mouse"); } } # we want to keep a record of any polymorphic pseudogenes for havana # let's not write a file until the end though since they are not # common my @<API key>; # connect to dbs my $db = new Bio::EnsEMBL::DBSQL::DBAdaptor( -host => $host, -user => $user, -port => $port, -dbname => $dbname ); my $ccds_db = new Bio::EnsEMBL::DBSQL::DBAdaptor( -host => $ccds_host, -user => $ccds_user, -pass => $ccds_pass, -port => $ccds_port, -dbname => $ccds_dbname ); $ccds_db->dnadb($db); my $ccds_sa = $ccds_db->get_SliceAdaptor; my $outdea = $ccds_db->get_DBEntryAdaptor; my $sa = $db->get_SliceAdaptor; # delete old ones if delete_old set if($write and $delete_old){ my $sth = $outdea->prepare('delete ox from xref x, object_xref ox, external_db e where x.xref_id = ox.xref_id and x.external_db_id = e.external_db_id and e.db_name like "Ens_%"'); $sth->execute || die "Could not delete old object_xrefs"; $sth = $outdea->prepare('delete x from xref x, external_db e where x.external_db_id = e.external_db_id and e.db_name like "Ens_%"'); $sth->execute || die "Could not delete ols xrefs"; } # Loop thru toplevels # maybe should use toplevel instead of chromosome? foreach my $chr ( @{ $ccds_sa->fetch_all('chromosome') } ) { print "Doing chromosome " . $chr->name . "\n" if ($verbose); # fetch all CCDS structures on slice foreach my $ccds_gene ( @{ $chr->get_all_Genes( undef, undef, 1 ) } ) { # make sure genes are al on chr level $ccds_gene = $ccds_gene->transform( 'chromosome', $path ); # loop thru all CCDS transcripts foreach my $ccds_trans ( @{ $ccds_gene->get_all_Transcripts() } ) { print "=> doing ccds trans " . $ccds_trans->dbID . ": start " . $ccds_trans->start . " stop " . $ccds_trans->end . " strand " . $ccds_trans->strand . " \n" if ($verbose); # find the ccds_id my $ccds_id; my @db_entries = @{ $ccds_trans->get_all_DBEntries('CCDS') }; my %xref_hash; foreach my $dbe (@db_entries) { print "dbe " . $dbe->display_id . " " . $dbe->dbname . "\n"; } # store unique CCDS xrefs for the transcript foreach my $entry (@db_entries) { $xref_hash{ $entry->display_id() } = 1; } # we should not have more than one CCDS id # associated with a transcript if ( scalar keys %xref_hash != 1 ) { foreach my $entry ( keys %xref_hash ) { print " Dodgy xref : " . $entry . "\n"; } throw( "Something odd going on: Transcript dbID " . $ccds_trans->dbID . " has " . scalar( keys %xref_hash ) . " xrefs" ); } else { # all is good; CCDS transcript only has 1 CCDS xref foreach my $entry ( keys %xref_hash ) { $ccds_id = $entry; print "=> on ccds $ccds_id\n" if ($verbose); } } # define the genomic location that we're working in # ie. where the CCDS transcript is my $chr_name = $ccds_trans->slice->seq_region_name; my $start = $ccds_trans->start(); my $end = $ccds_trans->end(); # now fetch the slice out of ensembl db my $slice = $sa->fetch_by_region( 'chromosome', $chr_name, $start, $end, '1', $path ); print " Ensembl slice name " . $slice->name . "\n" if ($verbose); # get ccds coding exons my @ccds_exons = @{ $ccds_trans-><API key>() }; print " have " . @ccds_exons . " ccds coding exons\n" if ($verbose); # get all Ensembl genes overlapping the CCDS regions foreach my $gene ( @{ $slice->get_all_Genes( undef, undef, 1 ) } ) { # only look at protein_coding genes next unless ( $gene->biotype =~ /protein_coding/ || $gene->biotype =~ /<API key>/); # debug # next if $gene->biotype =~ /protein_coding/ ; # keep a record if it is a polymorphic pseudogene - these will need to be sent to havana if ($gene->biotype =~ /<API key>/) { print STDERR " found a poly pseudo gene\n" if ($verbose); push @<API key>, $ccds_id; } # make sure ensembl gene also on chr level print " on ensembl gene " . $gene->display_id . "\n" if ($verbose); $gene = $gene->transform( 'chromosome', $path ); # loop thru ensembl transcripts foreach my $trans ( @{ $gene->get_all_Transcripts } ) { print " on ensembl trans " . $trans->display_id . "\n" if ($verbose); # get ensembl coding exons my @exons = @{ $trans-><API key>() }; print " have " . @exons . " ensembl coding exons\n" if ($verbose); # loop thru ensembl coding exons and make sure they all match the ccds # exons exactly my $match = 0; if ( scalar @exons == scalar @ccds_exons ) { for ( my $i = 0 ; $i < scalar(@exons) ; $i++ ) { # print " Ensembl start ".$exons[$i]->start." end ".$exons[$i]->end. # " CCDS start ".$ccds_exons[$i]->start." end ".$ccds_exons[$i]->end."\n"; if ( $ccds_exons[$i]->start == $exons[$i]->start && $ccds_exons[$i]->end == $exons[$i]->end && $ccds_exons[$i]->strand == $exons[$i]->strand ) { $match++; } #else { # print "no match ".$ccds_exons[$i]->start." != ".$exons[$i]->start." or ". # $ccds_exons[$i]->end." != ".$exons[$i]->end."\n"; } if ( $match == scalar @exons ) { print "MATCH\t" . $trans->stable_id . "\t" . $ccds_id . "\n" if ($verbose); store_ensembl_xref( $outdea, $species, $ccds_trans, $trans->stable_id, $write ); store_ensembl_xref( $outdea, $species, $ccds_trans->translation, $trans->translation->stable_id, $write ); } else { print " no match ($match)\t" . $trans->stable_id . "\t" . $ccds_id . "\n" if ($verbose); } } ## end if ( scalar @exons == ...) } ## end foreach my $trans ( @{ $gene...}) } ## end foreach my $gene ( @{ $slice...}) } ## end foreach my $ccds_trans ( @{...}) } ## end foreach my $ccds_gene ( @{ ...}) } ## end foreach my $chr ( @{ $ccds_sa...}) # report polymorphic pseudogenes if (@<API key>) { for my $display_id (@<API key>) { print STDERR $display_id." matches a polymorphic pseudogene\n"; } } else { print STDERR "Found 0 polymorphic pseudogenes\n"; } sub store_ensembl_xref { my ( $dbea, $species, $ccds_trans, $<API key>, $write ) = @_; if ( ref($ccds_trans) eq "Bio::EnsEMBL::Transcript" ) { my $external_db; if ( $species =~ /^human$/i ) { $external_db = 'Ens_Hs_transcript'; } elsif ( $species =~ /^mouse$/i ) { $external_db = 'Ens_Mm_transcript'; } # make an xref my $entry = new Bio::EnsEMBL::DBEntry( -adaptor => $dbea, -primary_id => $<API key>, -display_id => $<API key>, -version => 0, -dbname => $external_db); # store xref $dbea->store( $entry, $ccds_trans->dbID, 'Transcript' ) if ($write); } elsif ( ref($ccds_trans) eq "Bio::EnsEMBL::Translation" ) { my $external_db; if ( $species =~ /^human$/i ) { $external_db = 'Ens_Hs_translation'; } elsif ( $species =~ /^mouse$/i ) { $external_db = 'Ens_Mm_translation'; } # make an xref my $entry = new Bio::EnsEMBL::DBEntry( -adaptor => $dbea, -primary_id => $<API key>, -display_id => $<API key>, -version => 0, -dbname => $external_db); # store xref $dbea->store( $entry, $ccds_trans->dbID, 'Translation' ) if ($write); } else { throw("Not a Transcript or Translation "); } return; } ## end sub store_ensembl_xref
const NamingMixin = { _name: null, getName() { return this._name; }, _shortName: null, getShortName() { return this._shortName || this.getName(); }, _abbreviation: null, getAbbreviation() { return this._abbreviation || this.getShortName(); }, }; export default NamingMixin;
from mainapp import create_app app = create_app() if __name__ == '__main__': app.run(host='0.0.0.0')
package main import ( "github.com/ActiveState/tail" "github.com/ugorji/go/codec" "io/ioutil" "log" "os" "reflect" "regexp" "strconv" "strings" "time" ) type inputTail struct { path string format string tag string pos_file string offset int64 sync_interval int codec *codec.JsonHandle time_key string } func (self *inputTail) Init(f map[string]string) error { self.sync_interval = 2 value := f["path"] if len(value) > 0 { self.path = value } value = f["format"] if len(value) > 0 { self.format = value if value == "json" { _codec := codec.JsonHandle{} _codec.MapType = reflect.TypeOf(map[string]interface{}(nil)) self.codec = &_codec value = f["time_key"] if len(value) > 0 { self.time_key = value } else { self.time_key = "time" } } } value = f["tag"] if len(value) > 0 { self.tag = value } value = f["pos_file"] if len(value) > 0 { self.pos_file = value str, err := ioutil.ReadFile(self.pos_file) if err != nil { log.Println("ioutil.ReadFile:", err) } f, err := os.Open(self.path) if err != nil { log.Println("os.Open:", err) } info, err := f.Stat() if err != nil { log.Println("f.Stat:", err) self.offset = 0 } else { offset, _ := strconv.Atoi(string(str)) if int64(offset) > info.Size() { self.offset = info.Size() } else { self.offset = int64(offset) } } } value = f["sync_interval"] if len(value) > 0 { sync_interval, err := strconv.Atoi(value) if err != nil { return err } self.sync_interval = sync_interval } return nil } func (self *inputTail) Run(runner InputRunner) error { defer func() { if err := recover(); err != nil { logs.Fatalln("recover panic at err:", err) } }() var seek int if self.offset > 0 { seek = os.SEEK_SET } else { seek = os.SEEK_END } t, err := tail.TailFile(self.path, tail.Config{ Poll: true, ReOpen: true, Follow: true, MustExist: false, Location: &tail.SeekInfo{int64(self.offset), seek}}) if err != nil { return err } f, err := os.OpenFile(self.pos_file, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) if err != nil { log.Fatalln("os.OpenFile", err) } defer f.Close() var re regexp.Regexp if string(self.format[0]) == string("/") || string(self.format[len(self.format)-1]) == string("/") { format := strings.Trim(self.format, "/") trueformat := regexp.MustCompile("\\(\\?<").ReplaceAllString(format, "(?P<") if trueformat != format { log.Printf("pos_file:%s, format:%s", self.path, trueformat) } re = *regexp.MustCompile(trueformat) self.format = "regexp" } else if self.format == "json" { } tick := time.NewTicker(time.Second * time.Duration(self.sync_interval)) count := 0 for { select { case <-tick.C: { if count > 0 { offset, err := t.Tell() if err != nil { log.Println("Tell return error: ", err) continue } str := strconv.Itoa(int(offset)) _, err = f.WriteAt([]byte(str), 0) if err != nil { log.Println("f.WriteAt", err) return err } count = 0 } } case line := <-t.Lines: { pack := <-runner.InChan() pack.MsgBytes = []byte(line.Text) pack.Msg.Tag = self.tag pack.Msg.Timestamp = line.Time.Unix() if self.format == "regexp" { text := re.FindSubmatch([]byte(line.Text)) if text == nil { pack.Recycle() continue } for i, name := range re.SubexpNames() { if len(name) > 0 { pack.Msg.Data[name] = string(text[i]) } } } else if self.format == "json" { dec := codec.NewDecoderBytes([]byte(line.Text), self.codec) err := dec.Decode(&pack.Msg.Data) if err != nil { log.Println("json.Unmarshal", err) pack.Recycle() continue } else { t, ok := pack.Msg.Data[self.time_key] if ok { if time, xx := t.(uint64); xx { pack.Msg.Timestamp = int64(time) delete(pack.Msg.Data, self.time_key) } else if time64, oo := t.(int64); oo { pack.Msg.Timestamp = time64 delete(pack.Msg.Data, self.time_key) } else { log.Println("time is not int64, ", t, " typeof:", reflect.TypeOf(t)) pack.Recycle() continue } } } } count++ runner.RouterChan() <- pack } } } err = t.Wait() if err != nil { return err } return err } func init() { RegisterInput("tail", func() interface{} { return new(inputTail) }) }
<div class="container userContainer"> <div class="row"> <input type="text" ng-model="model.data.search" placeholder="Search user..." ng-change="model.search()" autofocus> </div> <div class="row userContainer-row" ng-click="model.userSelect(user)" ng-show="model.users.length" ng-repeat="user in model.users"> {{user.firstName}} {{user.lastName}} </div> <div class="row userContainer-row" ng-show="!model.users.length"> No user found ... </div> </div>
package testpkg import scala.concurrent.duration._ // starts svr using server-test/completions and perform sbt/completion tests object <API key> extends AbstractServerTest { override val testDirectory: String = "completions" test("return basic completions on request") { _ => val completionStr = """{ "query": "" }""" svr.sendJsonRpc( s"""{ "jsonrpc": "2.0", "id": 15, "method": "sbt/completion", "params": $completionStr }""" ) assert(svr.waitForString(10.seconds) { s => println(s) s contains """"result":{"items":[""" }) } test("return completion for custom tasks") { _ => val completionStr = """{ "query": "hell" }""" svr.sendJsonRpc( s"""{ "jsonrpc": "2.0", "id": 16, "method": "sbt/completion", "params": $completionStr }""" ) assert(svr.waitForString(10.seconds) { s => s contains """"result":{"items":["hello"]""" }) } test("return completions for user classes") { _ => val completionStr = """{ "query": "testOnly org." }""" svr.sendJsonRpc( s"""{ "jsonrpc": "2.0", "id": 17, "method": "sbt/completion", "params": $completionStr }""" ) assert(svr.waitForString(10.seconds) { s => s contains """"result":{"items":["testOnly org.sbt.ExampleSpec"]""" }) } }
registerNpc(1007, { walk_speed = 0, run_speed = 0, scale = 130, r_weapon = 0, l_weapon = 0, level = 10, hp = 100, attack = 100, hit = 100, def = 100, res = 100, avoid = 100, attack_spd = 100, is_magic_damage = 0, ai_type = 0, give_exp = 39, drop_type = 58, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 225, sell_tab0 = 225, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 200, npc_type = 999, hit_material_type = 0, face_icon = 17, summon_mob_type = 17, quest_type = 0, height = 0 }); function OnInit(entity) return true end function OnCreate(entity) return true end function OnDelete(entity) return true end function OnDead(entity) end function OnDamaged(entity) end
{% macro warnings_and_loader() -%} <div ng-cloak> <div class="<API key> toast-top-center"> <div ng-repeat="warning in (alertsService.warnings | limitTo:5) track by $index" class="toast toast-warning oppia-toast"> <button type="button" class="toast-close-button" ng-click="alertsService.deleteWarning(warning)" role="button">&times;</button> <div class="toast-message"> <[warning.content]> </div> </div> </div> <div> <div ng-repeat="message in alertsService.messages track by $index"> <alert-message message-object="message" message-index="$index"></alert-message> </div> </div> <div ng-show="loadingMessage" class="<API key>"> <div class="oppia-align-center"> <span translate="<[loadingMessage]>"></span> <span class="<API key>">.</span> <span class="<API key>">.</span> <span class="<API key>">.</span> </div> </div> <div ng-show="!loadingMessage"> {% block content %}{% endblock %} {% block footer %}{% endblock %} </div> </div> {%- endmacro %} <!DOCTYPE html> <html ng-app="oppia" ng-controller="Base" itemscope itemtype="http://schema.org/Organization"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> <!-- Tiles for Internet Explorer. --> <meta name="application-name" content="{{SITE_NAME}}"> <meta name="<API key>" content="#ffffff"> <meta name="<API key>" content="{{DOMAIN_URL}}/images/logo/msapplication-tiny.png"> <meta name="<API key>" content="{{DOMAIN_URL}}/images/logo/<API key>.png"> <meta name="<API key>" content="{{DOMAIN_URL}}/images/logo/msapplication-wide.png"> <meta name="<API key>" content="{{DOMAIN_URL}}/images/logo/msapplication-large.png"> <!-- The itemprops are for G+ sharing. --> <meta itemprop="name" content="{{meta_name}}"> <meta itemprop="description" content="{{meta_description}}"> <!-- The og tags are for Facebook sharing. --> <meta property="og:title" content="{{meta_name}}"> <meta property="og:site_name" content="Oppia"> <meta property="og:url" content="{{FULL_URL}}"> <meta property="og:description" content="{{meta_description}}"> <meta property="og:type" content="article"> <meta property="og:image" content="{{DOMAIN_URL}}/images/logo/288x288_logo_mint.png"> <link rel="apple-touch-icon" href="/images/logo/favicon.png"> <!-- The title is bound to the rootScope. The content of the block maintitle can be a string or a translation id. If it is a translation it will be replaced by its translation when the page is loading. If it is a string it would be displayed as is. This is the only way to translate the page title because the head of the file is outside the scope of any other controller. <title itemprop="name" translate="{% block maintitle %}Oppia{% endblock maintitle %}"></title> {% block base_url %}{% endblock base_url %} {% block header_css %} {% include 'header_css_libs.html' %} {% endblock header_css %} <script> var GLOBALS = { <API key>: [], csrf_token: JSON.parse('{{csrf_token|js_string}}'), csrf_token_i18n: JSON.parse('{{csrf_token_i18n|js_string}}'), csrf_<API key>: JSON.parse('{{csrf_<API key>|js_string}}'), DEV_MODE: JSON.parse('{{DEV_MODE|js_string}}'), INVALID_NAME_CHARS: JSON.parse('{{INVALID_NAME_CHARS|js_string}}'), <API key>: JSON.parse( '{{<API key>|js_string}}'), <API key>: JSON.parse( '{{<API key>|js_string}}'), <API key>: JSON.parse( '{{<API key>|js_string}}'), ALL_CATEGORIES: JSON.parse('{{ALL_CATEGORIES|js_string}}'), ALL_LANGUAGE_CODES: JSON.parse('{{ALL_LANGUAGE_CODES|js_string}}'), <API key>: JSON.parse( '{{<API key>|js_string}}'), RTE_COMPONENT_SPECS: JSON.parse('{{RTE_COMPONENT_SPECS|js_string}}'), <API key>: JSON.parse( '{{<API key>|js_string}}'), /* A list of functions to be called when an exploration is completed. */ <API key>: [], SYSTEM_USERNAMES: JSON.parse('{{SYSTEM_USERNAMES|js_string}}'), userIsLoggedIn: JSON.parse('{{user_is_logged_in|js_string}}'), <API key>: JSON.parse('{{<API key>|js_string}}'), <API key>: JSON.parse('{{<API key>|js_string}}') }; {% if <API key> %} GLOBALS.<API key> = JSON.parse('{{<API key>|js_string}}'); {% endif %} </script> {% block header_js %} {% include 'header_js_libs.html' %} {% endblock header_js %} {{<API key>}} </head> <body> {% if iframed %} {{ warnings_and_loader() }} {% else %} <div class="<API key>" ng-class="{'<API key>': sidebarIsShown, '<API key>': !sidebarIsShown}"> <div class="<API key>"> <div id="wrapper"> <div class="oppia-main-body"> <!-- Top navigation. --> <nav class="navbar navbar-default oppia-navbar <API key>" role="navigation"> <div class="navbar-container"> <div class="navbar-header <API key> pull-left"> <a ng-if="windowIsNarrow" ng-click="openSidebar()" class="navbar-brand oppia-navbar-menu <API key>"> <i class="material-icons <API key>">&#xE5D2;</i> </a> <a class="<API key> <API key>" href="/" focus-on="<[<API key>]>"> <img src="/images/logo/288x128_logo_white.png" class="oppia-logo" ng-class="windowIsNarrow ? 'oppia-logo-small' : 'oppia-logo-wide'"> </a> <!-- This is needed for the correct image to appear when an exploration is shared using G+. --> <a style="display: none;"> <img src="/images/logo/288x128_logo_mint.png" itemprop="image"> </a> </div> {% if nav_mode != 'signup' %} <div ng-cloak class="navbar-header pull-right"> <ul class="nav oppia-navbar-nav <API key>"> {% if username %} <li class="dropdown pull-right"> <a class="dropdown-toggle <API key>" data-toggle="dropdown" ng-mouseover="<API key>($event)" ng-mouseleave="<API key>($event)"> <div class="<API key>" ng-cloak> {% if <API key> %} <img src="{{<API key>}}" class="<API key> img-circle"> <span class="caret" style="margin-top: 10px;"></span> {% else %} <i class="material-icons md-40" style="margin-top: -1px;">&#xE853;</i> <span class="caret" style="margin-top: -26px;"></span> {% endif %} <div class="<API key> ng-cloak" ng-if="<API key> > 0"> <span class="<API key>"> <[<API key>]> </span> </div> <div style="display: none;" class="oppia-user-email"> {{user_email}} </div> {% if is_admin or is_moderator %} <div class="<API key>"> {% if is_admin %} <!-- "right: 4px;" is necessary here but not in moderator to prevent 'A' from appearing off-center because 'A' is slightly thinner than 'M' in this font --> <span class="<API key>" style="right: 4px;">A</span> {% elif is_moderator %} <span class="<API key>">M</span> {% endif %} </div> {% endif %} </div> </a> <ul class="dropdown-menu ng-cloak <API key>" role="menu" ng-mouseover="<API key>($event)" ng-mouseleave="<API key>($event)" ng-show="<API key>"> <li> <a ng-click="<API key>($event)" href="/profile/{{username}}"> <strong>{{username}}</strong> </a> </li> <hr class="<API key>"> <li> <a ng-click="<API key>($event)" href="/dashboard"> <span translate="<API key>"></span> </a> </li> <li> <a ng-click="<API key>($event)" href="/<API key>"> <span translate="<API key>"></span> <span ng-if="<API key> > 0"> (<[<API key>]>) </span> </a> </li> <li> <a ng-click="<API key>($event)" href="/preferences"> <span translate="<API key>"></span> </a> </li> {% if is_moderator %} <li> <a ng-click="<API key>($event)" href="/moderator" target="_blank"> <span translate="<API key>"></span> </a> </li> {% endif %} {% if is_super_admin %} <li> <a ng-click="<API key>($event)" href="/admin" target="_blank"> <span translate="<API key>"></span> </a> </li> {% endif %} <hr class="<API key>"> <li> <a ng-click="<API key>($event)" href="{{logout_url}}"> <span translate="I18N_TOPNAV_LOGOUT"></span> </a> </li> </ul> </li> {% else %} <li class="dropdown <API key> pull-right"> <div class="<API key>" style="margin-right: 10px;"> <button class="btn oppia-navbar-button" ng-click="<API key>('{{login_url}}')"> <span translate="I18N_TOPNAV_SIGN_IN"></span> <span class="caret"></span> </button> </div> <ul class="dropdown-menu <API key>" role="menu" style="margin-right: 15px; padding: 0;" ng-mouseover="<API key>($event)" ng-mouseleave="<API key>($event)"> <li> <a href style="padding: 0; width: 200px;" ng-click="<API key>('{{login_url}}')"> <img src="/images/signin/<API key>.png"> </a> </li> </ul> </li> {% endif %} </ul> <ul class="nav oppia-navbar-nav"> {% if nav_mode != 'create' and nav_mode != 'explore' %} <ul ng-if="windowIsNarrow" class="nav <API key>"> <<API key>></<API key>> </ul> <ul ng-if="!windowIsNarrow" class="nav oppia-navbar-tabs"> <<API key>></<API key>> {% if SHOW_CUSTOM_PAGES %} <li class="<API key> pull-right"> <a class="oppia-navbar-tab" href="/forum" translate="I18N_TOPNAV_FORUM"> </a> </li> {% endif %} <li class="dropdown <API key> pull-right"> <a class="oppia-navbar-tab"> <span translate="I18N_TOPNAV_ABOUT"></span> <span class="caret"></span> </a> <ul class="dropdown-menu <API key>" ng-mouseover="<API key>($event)" ng-mouseleave="<API key>($event)"> <li><a href="/about" translate="<API key>"></a></li> <li><a href="/teach" translate="<API key>"></a></li> {% for additional_link in <API key> %} <li><a href="{{additional_link['link']}}" target="_blank">{{additional_link['name']}}</a></li> {% endfor %} {% if SHOW_CUSTOM_PAGES %} <li><a href="/terms" translate="<API key>"></a></li> <li><a href="/privacy" translate="<API key>"></a></li> {% endif %} </ul> </li> <li class="<API key> pull-right"> <a class="oppia-navbar-tab" href="/library" translate="I18N_TOPNAV_LIBRARY"></a> </li> </ul> {% endif %} </ul> </div> {% endif %} <div class="collapse navbar-collapse ng-cloak"> {% block navbar_breadcrumb %} {% endblock navbar_breadcrumb %} {% block <API key> %} {% endblock %} </div> </div> </nav> <div class="<API key>"> </div> {{ warnings_and_loader() }} </div> <noscript> <div class="<API key>"> <div class="md-default-theme oppia-page-card oppia-long-text"> <h2> <span translate="<API key>"></span> <i class="material-icons">&#xE811;</i> </h2> <p translate="<API key>" translate-values="{hrefUrl: 'http: <p translate="<API key>"></p> </div> </div> </noscript> {% include 'side_nav.html' %} </div> </div> </div> {% if DEV_MODE %} <div class="oppia-dev-mode"> Dev Mode </div> {% endif %} {% if <API key> %} <a href="{{<API key>}}" target="_blank" class="oppia-site-feedback <API key>"> <i class="material-icons md-18" style="vertical-align: middle;">&#xE87F;</i> <span translate="<API key>"></span> </i> </a> {% endif %} {% endif %} {% include 'directives.html' %} {% include 'forms/<API key>.html' %} {% include 'footer_js_libs.html' %} {% include 'components/<API key>.html' %} {% include 'components/<API key>.html' %} {% include 'components/rating_display.html' %} {% include 'components/<API key>.html' %} {% include 'components/<API key>.html' %} {% include 'components/<API key>.html' %} <script> {{ include_js_file('app.js') }} {{ include_js_file('base.js') }} {{ include_js_file('directives.js') }} {{ include_js_file('filters.js') }} {{ include_js_file('i18n.js') }} {{ include_js_file('forms/formBuilder.js') }} {{ include_js_file('services/alertsService.js') }} {{ include_js_file('services/<API key>.js') }} {{ include_js_file('services/<API key>.js') }} {{ include_js_file('services/searchService.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('components/<API key>.js')}} {{ include_js_file('components/<API key>.js')}} {{ include_js_file('components/<API key>.js') }} {{ include_js_file('domain/utilities/<API key>.js') }} {{ include_js_file('expressions/<API key>.js') }} {{ include_js_file('expressions/evaluator.js') }} {{ include_js_file('expressions/parser.js') }} {{ include_js_file('domain/utilities/<API key>.js') }} {{ OBJECT_EDITORS_JS }} </script> {% block footer_js %} {% endblock footer_js %} {{<API key>}} </body> </html>
<!DOCTYPE html><html lang="en"><head><title>src/Parser</title></head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"><meta name="groc-relative-root" content="../"><meta name="groc-document-path" content="src/Parser.coffee"><meta name="groc-project-path" content="src/Parser.coffee"><meta name="groc-github-url" content="https://github.com/sjorek/goatee-rules.js"><link rel="stylesheet" type="text/css" media="all" href="../assets/style.css"><script type="text/javascript" src="../assets/behavior.js"></script><body><div id="meta"><div class="file-path"><a href="https://github.com/sjorek/goatee-rules.js/blob/master/src/Parser.coffee">src/Parser.coffee</a></div></div><div id="document"><div class="segment"><div class="code folded"><div class="wrapper marker"><span class="c1"> BSD 3-Clause License Copyright (c) 2017, Stephan Jorek All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </span> <span class="hljs-keyword">try</span> exports = <span class="hljs-built_in">require</span> <span class="hljs-string">'./ParserImpl'</span> <span class="hljs-keyword">catch</span> exports = <span class="hljs-literal">null</span> <span class="hljs-keyword">if</span> exports <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span> Grammar = <span class="hljs-built_in">require</span> <span class="hljs-string">'./Grammar'</span> exports = <span class="hljs-built_in">module</span>?.exports ? <span class="hljs-keyword">this</span></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h1 id="parser">Parser</h1> <hr> <p>A thin compatibillity layer providing an “on-the-fly” generated goatee-rules parser.</p></div></div></div><div class="segment"><div class="comments doc-section doc-section-static"><div class="wrapper"><p><span class='doc-section-header'>Static property parser of type <em>Parser</em></span></p> <hr></div></div><div class="code"><div class="wrapper"> exports.parser = parser = Grammar.createParser()</div></div></div><div class="segment"><div class="comments doc-section"><div class="wrapper"><p><span class='doc-section-header'> class Parser and namespace GoateeScript</span></p> <hr></div></div><div class="code"><div class="wrapper"> exports.Parser = parser.Parser</div></div></div><div class="segment"><div class="comments doc-section doc-section-static"><div class="wrapper"><p><span class='doc-section-header'>Static function parse</span></p> <hr></div></div><div class="code"><div class="wrapper"> exports.parse = <span class="hljs-function"><span class="hljs-params">()</span> -&gt;</span> parser.parse.apply(parser, arguments)</div></div></div><div class="segment"><div class="comments doc-section doc-section-static"><div class="wrapper"><p><span class='doc-section-header'>Static function main</span></p> <hr> <p>Parameters:</p> <ul> <li><strong>args must be an Array.</strong></li> </ul></div></div><div class="code"><div class="wrapper"> exports.main = <span class="hljs-function"><span class="hljs-params">(args)</span> -&gt;</span> <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> args[<span class="hljs-number">1</span>] <span class="hljs-built_in">console</span>.log <span class="hljs-string">"Usage: <span class="hljs-subst">#{args[<span class="hljs-number">0</span>]}</span> FILE"</span> process.exit <span class="hljs-number">1</span> source = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>).readFileSync( <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>).normalize(args[<span class="hljs-number">1</span>]), <span class="hljs-string">"utf8"</span> ) parser.parse(source) <span class="hljs-built_in">module</span>.exports = exports</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>execute main automatically</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">if</span> (<span class="hljs-built_in">module</span> <span class="hljs-keyword">isnt</span> <span class="hljs-literal">undefined</span> &amp;&amp; <span class="hljs-built_in">require</span>.main <span class="hljs-keyword">is</span> <span class="hljs-built_in">module</span>) exports.main process.argv.slice(<span class="hljs-number">1</span>)</div></div></div></div></body></html>
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_22) on Wed Sep 14 22:21:32 CEST 2011 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> net.sourceforge.pmd.typeresolution.rules.imports Class Hierarchy (PMD 4.2.6 API) </TITLE> <META NAME="date" CONTENT="2011-09-14"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="net.sourceforge.pmd.typeresolution.rules.imports Class Hierarchy (PMD 4.2.6 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../net/sourceforge/pmd/typeresolution/rules/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../../net/sourceforge/pmd/typeresolution/visitors/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?net/sourceforge/pmd/typeresolution/rules/imports/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> Hierarchy For Package net.sourceforge.pmd.typeresolution.rules.imports </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">net.sourceforge.pmd.<A HREF="../../../../../../net/sourceforge/pmd/CommonAbstractRule.html" title="class in net.sourceforge.pmd"><B>CommonAbstractRule</B></A> (implements net.sourceforge.pmd.<A HREF="../../../../../../net/sourceforge/pmd/Rule.html" title="interface in net.sourceforge.pmd">Rule</A>) <UL> <LI TYPE="circle">net.sourceforge.pmd.<A HREF="../../../../../../net/sourceforge/pmd/AbstractJavaRule.html" title="class in net.sourceforge.pmd"><B>AbstractJavaRule</B></A> (implements net.sourceforge.pmd.ast.<A HREF="../../../../../../net/sourceforge/pmd/ast/JavaParserVisitor.html" title="interface in net.sourceforge.pmd.ast">JavaParserVisitor</A>) <UL> <LI TYPE="circle">net.sourceforge.pmd.<A HREF="../../../../../../net/sourceforge/pmd/AbstractRule.html" title="class in net.sourceforge.pmd"><B>AbstractRule</B></A><UL> <LI TYPE="circle">net.sourceforge.pmd.rules.imports.<A HREF="../../../../../../net/sourceforge/pmd/rules/imports/UnusedImportsRule.html" title="class in net.sourceforge.pmd.rules.imports"><B>UnusedImportsRule</B></A><UL> <LI TYPE="circle">net.sourceforge.pmd.typeresolution.rules.imports.<A HREF="../../../../../../net/sourceforge/pmd/typeresolution/rules/imports/UnusedImports.html" title="class in net.sourceforge.pmd.typeresolution.rules.imports"><B>UnusedImports</B></A></UL> </UL> </UL> </UL> </UL> </UL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../net/sourceforge/pmd/typeresolution/rules/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../../net/sourceforge/pmd/typeresolution/visitors/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?net/sourceforge/pmd/typeresolution/rules/imports/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright &copy; 2002-2011 InfoEther. All Rights Reserved. </BODY> </HTML>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>com.cloudera.oryx.api.serving (Oryx 2.8.0 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../com/cloudera/oryx/api/serving/package-summary.html" target="classFrame">com.cloudera.oryx.api.serving</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="HasCSV.html" title="interface in com.cloudera.oryx.api.serving" target="classFrame"><span class="interfaceName">HasCSV</span></a></li> <li><a href="ServingModel.html" title="interface in com.cloudera.oryx.api.serving" target="classFrame"><span class="interfaceName">ServingModel</span></a></li> <li><a href="ServingModelManager.html" title="interface in com.cloudera.oryx.api.serving" target="classFrame"><span class="interfaceName">ServingModelManager</span></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="<API key>.html" title="class in com.cloudera.oryx.api.serving" target="classFrame"><API key></a></li> <li><a href="OryxResource.html" title="class in com.cloudera.oryx.api.serving" target="classFrame">OryxResource</a></li> </ul> <h2 title="Exceptions">Exceptions</h2> <ul title="Exceptions"> <li><a href="<API key>.html" title="class in com.cloudera.oryx.api.serving" target="classFrame"><API key></a></li> </ul> </div> </body> </html>
package com.senseidb.search.node.impl; import org.json.JSONObject; import com.senseidb.search.node.SenseiQueryBuilder; import com.senseidb.search.node.<API key>; import com.senseidb.search.req.SenseiQuery; import com.senseidb.util.JSONUtil.FastJSONObject; public abstract class <API key> implements <API key> { @Override public SenseiQueryBuilder getQueryBuilder(SenseiQuery query) throws Exception { JSONObject jsonQuery = null; if (query != null) { byte[] bytes = query.toBytes(); jsonQuery = new FastJSONObject(new String(bytes, SenseiQuery.utf8Charset)); } return buildQueryBuilder(jsonQuery); } public abstract SenseiQueryBuilder buildQueryBuilder(JSONObject jsonQuery); }
#include <zephyr.h> #include <misc/printk.h> #include <board.h> #include <gpio.h> #include <i2c.h> #include <spi.h> #include <sensor.h> /* #define ARGONKEY_TEST_LOG 1 */ #define WHOAMI_REG 0x0F #define WHOAMI_ALT_REG 0x4F static inline float out_ev(struct sensor_value *val) { return (val->val1 + (float)val->val2 / 1000000); } static int lsm6dsl_trig_cnt; #ifdef <API key> static void <API key>(struct device *dev, struct sensor_trigger *trig) { #ifdef ARGONKEY_TEST_LOG char out_str[64]; #endif struct sensor_value accel_x, accel_y, accel_z; struct sensor_value gyro_x, gyro_y, gyro_z; #if defined(<API key>) struct sensor_value magn_x, magn_y, magn_z; #endif #if defined(<API key>) struct sensor_value press, temp; #endif lsm6dsl_trig_cnt++; <API key>(dev, <API key>); sensor_channel_get(dev, SENSOR_CHAN_ACCEL_X, &accel_x); sensor_channel_get(dev, SENSOR_CHAN_ACCEL_Y, &accel_y); sensor_channel_get(dev, SENSOR_CHAN_ACCEL_Z, &accel_z); #ifdef ARGONKEY_TEST_LOG sprintf(out_str, "accel (%f %f %f) m/s2", out_ev(&accel_x), out_ev(&accel_y), out_ev(&accel_z)); printk("TRIG %s\n", out_str); #endif /* lsm6dsl gyro */ <API key>(dev, <API key>); sensor_channel_get(dev, SENSOR_CHAN_GYRO_X, &gyro_x); sensor_channel_get(dev, SENSOR_CHAN_GYRO_Y, &gyro_y); sensor_channel_get(dev, SENSOR_CHAN_GYRO_Z, &gyro_z); #ifdef ARGONKEY_TEST_LOG sprintf(out_str, "gyro (%f %f %f) dps", out_ev(&gyro_x), out_ev(&gyro_y), out_ev(&gyro_z)); printk("TRIG %s\n", out_str); #endif #if defined(<API key>) /* lsm6dsl magn */ <API key>(dev, <API key>); sensor_channel_get(dev, SENSOR_CHAN_MAGN_X, &magn_x); sensor_channel_get(dev, SENSOR_CHAN_MAGN_Y, &magn_y); sensor_channel_get(dev, SENSOR_CHAN_MAGN_Z, &magn_z); #ifdef ARGONKEY_TEST_LOG sprintf(out_str, "magn (%f %f %f) gauss", out_ev(&magn_x), out_ev(&magn_y), out_ev(&magn_z)); printk("TRIG %s\n", out_str); #endif #endif #if defined(<API key>) /* lsm6dsl press/temp */ <API key>(dev, SENSOR_CHAN_PRESS); sensor_channel_get(dev, SENSOR_CHAN_PRESS, &press); <API key>(dev, <API key>); sensor_channel_get(dev, <API key>, &temp); #ifdef ARGONKEY_TEST_LOG sprintf(out_str, "press (%f) kPa - temp (%f) deg", out_ev(&press), out_ev(&temp)); printk("%s\n", out_str); #endif #endif } #endif void main(void) { int cnt = 0; char out_str[64]; static struct device *led0, *led1; int i, on = 1; led0 = device_get_binding(<API key>); gpio_pin_configure(led0, LED0_GPIO_PIN, GPIO_DIR_OUT); gpio_pin_write(led0, LED0_GPIO_PIN, 1); led1 = device_get_binding(<API key>); gpio_pin_configure(led1, LED1_GPIO_PIN, GPIO_DIR_OUT); for (i = 0; i < 5; i++) { gpio_pin_write(led1, LED1_GPIO_PIN, on); k_sleep(200); on = (on == 1) ? 0 : 1; } printk("ArgonKey test!!\n"); #ifdef CONFIG_LPS22HB struct device *baro_dev = device_get_binding(<API key>); if (!baro_dev) { printk("Could not get pointer to %s sensor\n", <API key>); return; } #endif #ifdef CONFIG_HTS221 struct device *hum_dev = device_get_binding(CONFIG_HTS221_NAME); if (!hum_dev) { printk("Could not get pointer to %s sensor\n", CONFIG_HTS221_NAME); return; } #endif #ifdef CONFIG_LSM6DSL struct device *accel_dev = device_get_binding(<API key>); if (!accel_dev) { printk("Could not get pointer to %s sensor\n", <API key>); return; } #if defined(<API key>) && (<API key> == 0) struct sensor_value a_odr_attr; /* set sampling frequency to 104Hz for accel */ a_odr_attr.val1 = 104; a_odr_attr.val2 = 0; if (sensor_attr_set(accel_dev, <API key>, <API key>, &a_odr_attr) < 0) { printk("Cannot set sampling frequency for accelerometer.\n"); return; } #endif #if defined(<API key>) && (<API key> == 0) struct sensor_value a_fs_attr; /* set full scale to 16g for accel */ sensor_g_to_ms2(16, &a_fs_attr); if (sensor_attr_set(accel_dev, <API key>, <API key>, &a_fs_attr) < 0) { printk("Cannot set fs for accelerometer.\n"); return; } #endif #if defined(<API key>) && (<API key> == 0) struct sensor_value g_odr_attr; /* set sampling frequency to 104Hz for accel */ g_odr_attr.val1 = 104; g_odr_attr.val2 = 0; if (sensor_attr_set(accel_dev, <API key>, <API key>, &g_odr_attr) < 0) { printk("Cannot set sampling frequency for gyro.\n"); return; } #endif #if defined(<API key>) && (<API key> == 0) struct sensor_value g_fs_attr; /* set full scale to 245dps for accel */ sensor_g_to_ms2(245, &g_fs_attr); if (sensor_attr_set(accel_dev, <API key>, <API key>, &g_fs_attr) < 0) { printk("Cannot set fs for gyroscope.\n"); return; } #endif #endif #ifdef CONFIG_VL53L0X struct device *tof_dev = device_get_binding(CONFIG_VL53L0X_NAME); if (!tof_dev) { printk("Could not get pointer to %s sensor\n", CONFIG_VL53L0X_NAME); return; } #endif #ifdef <API key> struct sensor_trigger trig; trig.type = <API key>; trig.chan = <API key>; sensor_trigger_set(accel_dev, &trig, <API key>); #endif while (1) { #ifdef CONFIG_LPS22HB struct sensor_value temp, press; #endif #ifdef CONFIG_HTS221 struct sensor_value humidity; #endif #ifdef CONFIG_LSM6DSL struct sensor_value accel_x, accel_y, accel_z; struct sensor_value gyro_x, gyro_y, gyro_z; #if defined(<API key>) struct sensor_value magn_x, magn_y, magn_z; #endif #if defined(<API key>) struct sensor_value press, temp; #endif #endif #ifdef CONFIG_VL53L0X struct sensor_value prox; #endif #ifdef CONFIG_VL53L0X sensor_sample_fetch(tof_dev); sensor_channel_get(tof_dev, SENSOR_CHAN_PROX, &prox); printk("proxy: %d ;\n", prox.val1); sensor_channel_get(tof_dev, <API key>, &prox); printk("distance: %d -- %3d mm;\n", prox.val1, prox.val2); #endif #ifdef CONFIG_LPS22HB sensor_sample_fetch(baro_dev); sensor_channel_get(baro_dev, <API key>, &temp); sensor_channel_get(baro_dev, SENSOR_CHAN_PRESS, &press); printk("temp: %d.%02d C; press: %d.%06d\n", temp.val1, temp.val2, press.val1, press.val2); #endif #ifdef CONFIG_HTS221 sensor_sample_fetch(hum_dev); sensor_channel_get(hum_dev, <API key>, &humidity); printk("humidity: %d.%06d\n", humidity.val1, humidity.val2); #endif #ifdef CONFIG_LSM6DSL /* lsm6dsl accel */ <API key>(accel_dev, <API key>); sensor_channel_get(accel_dev, SENSOR_CHAN_ACCEL_X, &accel_x); sensor_channel_get(accel_dev, SENSOR_CHAN_ACCEL_Y, &accel_y); sensor_channel_get(accel_dev, SENSOR_CHAN_ACCEL_Z, &accel_z); sprintf(out_str, "accel (%f %f %f) m/s2", out_ev(&accel_x), out_ev(&accel_y), out_ev(&accel_z)); printk("%s\n", out_str); /* lsm6dsl gyro */ <API key>(accel_dev, <API key>); sensor_channel_get(accel_dev, SENSOR_CHAN_GYRO_X, &gyro_x); sensor_channel_get(accel_dev, SENSOR_CHAN_GYRO_Y, &gyro_y); sensor_channel_get(accel_dev, SENSOR_CHAN_GYRO_Z, &gyro_z); sprintf(out_str, "gyro (%f %f %f) dps", out_ev(&gyro_x), out_ev(&gyro_y), out_ev(&gyro_z)); printk("%s\n", out_str); #if defined(<API key>) /* lsm6dsl magn */ <API key>(accel_dev, <API key>); sensor_channel_get(accel_dev, SENSOR_CHAN_MAGN_X, &magn_x); sensor_channel_get(accel_dev, SENSOR_CHAN_MAGN_Y, &magn_y); sensor_channel_get(accel_dev, SENSOR_CHAN_MAGN_Z, &magn_z); sprintf(out_str, "magn (%f %f %f) gauss", out_ev(&magn_x), out_ev(&magn_y), out_ev(&magn_z)); printk("%s\n", out_str); #endif #if defined(<API key>) /* lsm6dsl press/temp */ <API key>(accel_dev, SENSOR_CHAN_PRESS); sensor_channel_get(accel_dev, SENSOR_CHAN_PRESS, &press); <API key>(accel_dev, <API key>); sensor_channel_get(accel_dev, <API key>, &temp); sprintf(out_str, "press (%f) kPa - temp (%f) deg", out_ev(&press), out_ev(&temp)); printk("%s\n", out_str); #endif #endif /* CONFIG_LSM6DSL */ printk("- (%d) (trig_cnt: %d)\n\n", ++cnt, lsm6dsl_trig_cnt); k_sleep(2000); } }
var searchData= [ ['value',['value',['../<API key>.html#<API key>',1,'guac_pool_int']]], ['<API key>',['vguac_client_abort',['../client_8h.html#<API key>',1,'client.h']]], ['<API key>',['vguac_client_log',['../client_8h.html#<API key>',1,'client.h']]], ['<API key>',['<API key>',['../protocol_8h.html#<API key>',1,'protocol.h']]], ['video_5fmimetypes',['video_mimetypes',['../<API key>.html#<API key>',1,'guac_client_info']]] ];
package org.vertexium.util; import org.vertexium.Authorizations; import org.vertexium.Direction; import org.vertexium.Vertex; import java.util.Iterator; public class <API key> implements Iterable<String> { private final Iterable<? extends Vertex> vertices; private final Authorizations authorizations; public <API key>(Iterable<? extends Vertex> vertices, Authorizations authorizations) { this.vertices = vertices; this.authorizations = authorizations; } @Override public Iterator<String> iterator() { return new SelectManyIterable<Vertex, String>(this.vertices) { @Override public Iterable<String> getIterable(Vertex vertex) { return vertex.getEdgeIds(Direction.BOTH, authorizations); } }.iterator(); } }
package com.kit.db; public class Obj { }
#import "DockSquadImporter.h" @interface <API key> : DockSquadImporter @end
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_51) on Fri Jul 19 02:59:04 EDT 2013 --> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE> Uses of Class org.apache.solr.client.solrj.response.RangeFacet.Count (Solr 4.4.0 API) </TITLE> <META NAME="date" CONTENT="2013-07-19"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.client.solrj.response.RangeFacet.Count (Solr 4.4.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/solr/client/solrj/response/RangeFacet.Count.html" title="class in org.apache.solr.client.solrj.response"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/solr/client/solrj/response//class-useRangeFacet.Count.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="RangeFacet.Count.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.solr.client.solrj.response.RangeFacet.Count</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../../org/apache/solr/client/solrj/response/RangeFacet.Count.html" title="class in org.apache.solr.client.solrj.response">RangeFacet.Count</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.solr.client.solrj.response"><B>org.apache.solr.client.solrj.response</B></A></TD> <TD>Convenience classes for dealing with various types of Solr responses.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.solr.client.solrj.response"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/solr/client/solrj/response/RangeFacet.Count.html" title="class in org.apache.solr.client.solrj.response">RangeFacet.Count</A> in <A HREF="../../../../../../../org/apache/solr/client/solrj/response/package-summary.html">org.apache.solr.client.solrj.response</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/solr/client/solrj/response/package-summary.html">org.apache.solr.client.solrj.response</A> that return types with arguments of type <A HREF="../../../../../../../org/apache/solr/client/solrj/response/RangeFacet.Count.html" title="class in org.apache.solr.client.solrj.response">RangeFacet.Count</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://download.oracle.com/javase/6/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</A>&lt;<A HREF="../../../../../../../org/apache/solr/client/solrj/response/RangeFacet.Count.html" title="class in org.apache.solr.client.solrj.response">RangeFacet.Count</A>&gt;</CODE></FONT></TD> <TD><CODE><B>RangeFacet.</B><B><A HREF="../../../../../../../org/apache/solr/client/solrj/response/RangeFacet.html#getCounts()">getCounts</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/solr/client/solrj/response/RangeFacet.Count.html" title="class in org.apache.solr.client.solrj.response"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/solr/client/solrj/response//class-useRangeFacet.Count.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="RangeFacet.Count.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> <i>Copyright &copy; 2000-2013 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </BODY> </HTML>
external help file: Microsoft.Azure.Commands.HDInsight.dll-Help.xml ms.assetid: <API key> online version: schema: 2.0.0 # <API key> ## SYNOPSIS Creates a Sqoop job object. ## SYNTAX <API key> [-Files <String[]>] [-StatusFolder <String>] [-File <String>] [-Command <String>] [-LibDir <String>] [<CommonParameters>] ## DESCRIPTION The **<API key>** cmdlet defines a Sqoop job object for use with an Azure HDInsight cluster. ## EXAMPLES Example 1: Create a Sqoop job definition PS C:\># Cluster info PS C:\>$clusterName = "your-hadoop-001" PS C:\>$clusterCreds = Get-Credential PS C:\><API key> -StatusFolder $statusFolder ` -Command $sqoopCommand ` | <API key> -ClusterName $clusterName ` -ClusterCredential $clusterCreds This command creates a Sqoop job definition. ## PARAMETERS -Command Specifies the Sqoop command. yaml Type: String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False -File Specifies the path to a file that contains the query to run. The file must be available on the Storage account associated with the cluster. You can use this parameter instead of the *Query* parameter. yaml Type: String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False -Files Specifies a collection of files that are associated with a Hive job. yaml Type: String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False -LibDir Specifies the library directory for the Sqoop job. yaml Type: String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False -StatusFolder Specifies the location of the folder that contains standard outputs and error outputs for a job. yaml Type: String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see <API key> (http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS Microsoft.Azure.Commands.HDInsight.Models.<API key> ## NOTES ## RELATED LINKS [<API key>](./<API key>.md)
""" IP Types """ import logging from ipaddress import ip_address from socket import AF_INET, AF_INET6 from vpp_papi import VppEnum from vpp_object import VppObject try: text_type = unicode except NameError: text_type = str _log = logging.getLogger(__name__) class DpoProto: DPO_PROTO_IP4 = 0 DPO_PROTO_IP6 = 1 DPO_PROTO_MPLS = 2 DPO_PROTO_ETHERNET = 3 DPO_PROTO_BIER = 4 DPO_PROTO_NSH = 5 INVALID_INDEX = 0xffffffff def get_dpo_proto(addr): if ip_address(addr).version == 6: return DpoProto.DPO_PROTO_IP6 else: return DpoProto.DPO_PROTO_IP4 class VppIpAddressUnion(): def __init__(self, addr): self.addr = addr self.ip_addr = ip_address(text_type(self.addr)) def encode(self): if self.version == 6: return {'ip6': self.ip_addr} else: return {'ip4': self.ip_addr} @property def version(self): return self.ip_addr.version @property def address(self): return self.addr @property def length(self): return self.ip_addr.max_prefixlen @property def bytes(self): return self.ip_addr.packed def __eq__(self, other): if isinstance(other, self.__class__): return self.ip_addr == other.ip_addr elif hasattr(other, "ip4") and hasattr(other, "ip6"): # <API key> if 4 == self.version: return self.ip_addr == other.ip4 else: return self.ip_addr == other.ip6 else: raise Exception("Comparing VppIpAddressUnions:%s" " with incomparable type: %s", self, other) def __ne__(self, other): return not (self == other) def __str__(self): return str(self.ip_addr) class VppIpMPrefix(): def __init__(self, saddr, gaddr, glen): self.saddr = saddr self.gaddr = gaddr self.glen = glen if ip_address(self.saddr).version != \ ip_address(self.gaddr).version: raise ValueError('Source and group addresses must be of the ' 'same address family.') def encode(self): return { 'af': ip_address(self.gaddr).vapi_af, 'grp_address': { ip_address(self.gaddr).vapi_af_name: self.gaddr }, 'src_address': { ip_address(self.saddr).vapi_af_name: self.saddr }, 'grp_address_length': self.glen, } @property def length(self): return self.glen @property def version(self): return ip_address(self.gaddr).version def __str__(self): return "(%s,%s)/%d" % (self.saddr, self.gaddr, self.glen) def __eq__(self, other): if isinstance(other, self.__class__): return (self.glen == other.glen and self.saddr == other.gaddr and self.saddr == other.saddr) elif (hasattr(other, "grp_address_length") and hasattr(other, "grp_address") and hasattr(other, "src_address")): # vl_api_mprefix_t if 4 == self.version: return (self.glen == other.grp_address_length and self.gaddr == str(other.grp_address.ip4) and self.saddr == str(other.src_address.ip4)) else: return (self.glen == other.grp_address_length and self.gaddr == str(other.grp_address.ip6) and self.saddr == str(other.src_address.ip6)) return NotImplemented class VppIpPuntPolicer(VppObject): def __init__(self, test, policer_index, is_ip6=False): self._test = test self._policer_index = policer_index self._is_ip6 = is_ip6 def add_vpp_config(self): self._test.vapi.ip_punt_police(policer_index=self._policer_index, is_ip6=self._is_ip6, is_add=True) def remove_vpp_config(self): self._test.vapi.ip_punt_police(policer_index=self._policer_index, is_ip6=self._is_ip6, is_add=False) def query_vpp_config(self): NotImplemented class VppIpPuntRedirect(VppObject): def __init__(self, test, rx_index, tx_index, nh_addr): self._test = test self._rx_index = rx_index self._tx_index = tx_index self._nh_addr = ip_address(nh_addr) def encode(self): return {"rx_sw_if_index": self._rx_index, "tx_sw_if_index": self._tx_index, "nh": self._nh_addr} def add_vpp_config(self): self._test.vapi.ip_punt_redirect(punt=self.encode(), is_add=True) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): self._test.vapi.ip_punt_redirect(punt=self.encode(), is_add=False) def get_vpp_config(self): is_ipv6 = True if self._nh_addr.version == 6 else False return self._test.vapi.<API key>( sw_if_index=self._rx_index, is_ipv6=is_ipv6) def query_vpp_config(self): if self.get_vpp_config(): return True return False class VppIpPathMtu(VppObject): def __init__(self, test, nh, pmtu, table_id=0): self._test = test self.nh = nh self.pmtu = pmtu self.table_id = table_id def add_vpp_config(self): self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, 'table_id': self.table_id, 'path_mtu': self.pmtu}) self._test.registry.register(self, self._test.logger) return self def modify(self, pmtu): self.pmtu = pmtu self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, 'table_id': self.table_id, 'path_mtu': self.pmtu}) return self def remove_vpp_config(self): self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, 'table_id': self.table_id, 'path_mtu': 0}) def query_vpp_config(self): ds = list(self._test.vapi.vpp.details_iter( self._test.vapi.ip_path_mtu_get)) for d in ds: if self.nh == str(d.pmtu.nh) \ and self.table_id == d.pmtu.table_id \ and self.pmtu == d.pmtu.path_mtu: return True return False def object_id(self): return ("ip-path-mtu-%d-%s-%d" % (self.table_id, self.nh, self.pmtu)) def __str__(self): return self.object_id()
package org.plasma.provisioning.rdb.mysql.v5_5.query; import org.plasma.provisioning.rdb.mysql.v5_5.<API key>; import org.plasma.query.DataProperty; import org.plasma.query.Expression; import org.plasma.query.dsl.DataNode; import org.plasma.query.dsl.DomainRoot; import org.plasma.query.dsl.PathNode; import org.plasma.sdo.helper.PlasmaTypeHelper; /** * Generated Domain Specific Language (DSL) implementation class representing * the domain model entity <b><API key></b>. * * <p> * </p> * <b>Data Store Mapping:</b> Corresponds to the physical data store entity * <b><API key></b>. * */ public class <API key> extends DomainRoot { private <API key>() { super(PlasmaTypeHelper.INSTANCE.getType(<API key>.class)); } public <API key>(PathNode source, String sourceProperty) { super(source, sourceProperty); } public <API key>(PathNode source, String sourceProperty, Expression expr) { super(source, sourceProperty, expr); } public static <API key> newQuery() { return new <API key>(); } /** * Returns a DSL data element for property, <b>name</b>. * * @return a DSL data element for property, <b>name</b>. */ public DataProperty name() { return new DataNode(this, <API key>.PROPERTY.name.name()); } /** * Returns a DSL data element for property, <b>owner</b>. * * @return a DSL data element for property, <b>owner</b>. */ public DataProperty owner() { return new DataNode(this, <API key>.PROPERTY.owner.name()); } /** * Returns a DSL query element for reference property, <b>table</b>. * * @return a DSL query element for reference property, <b>table</b>. */ public QTable table() { return new QTable(this, <API key>.PROPERTY.table.name()); } }
// Code generated by protoc-gen-go. DO NOT EDIT. // source: hapi/chart/metadata.proto package chart import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.<API key> // please upgrade the proto package type Metadata_Engine int32 const ( Metadata_UNKNOWN Metadata_Engine = 0 Metadata_GOTPL Metadata_Engine = 1 ) var <API key> = map[int32]string{ 0: "UNKNOWN", 1: "GOTPL", } var <API key> = map[string]int32{ "UNKNOWN": 0, "GOTPL": 1, } func (x Metadata_Engine) String() string { return proto.EnumName(<API key>, int32(x)) } func (Metadata_Engine) EnumDescriptor() ([]byte, []int) { return <API key>, []int{1, 0} } // Maintainer describes a Chart maintainer. type Maintainer struct { // Name is a user name or organization name Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Email is an optional email address to contact the named maintainer Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"` // Url is an optional URL to an address for the named maintainer Url string `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Maintainer) Reset() { *m = Maintainer{} } func (m *Maintainer) String() string { return proto.CompactTextString(m) } func (*Maintainer) ProtoMessage() {} func (*Maintainer) Descriptor() ([]byte, []int) { return <API key>, []int{0} } func (m *Maintainer) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *Maintainer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *Maintainer) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *Maintainer) XXX_Size() int { return <API key>.Size(m) } func (m *Maintainer) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *Maintainer) GetName() string { if m != nil { return m.Name } return "" } func (m *Maintainer) GetEmail() string { if m != nil { return m.Email } return "" } func (m *Maintainer) GetUrl() string { if m != nil { return m.Url } return "" } // Metadata for a Chart file. This models the structure of a Chart.yaml file. // Spec: https://k8s.io/helm/blob/master/docs/design/chart_format.md#the-chart-file type Metadata struct { // The name of the chart Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The URL to a relevant project page, git repo, or contact person Home string `protobuf:"bytes,2,opt,name=home,proto3" json:"home,omitempty"` // Source is the URL to the source code of this chart Sources []string `protobuf:"bytes,3,rep,name=sources,proto3" json:"sources,omitempty"` // A SemVer 2 conformant version string of the chart Version string `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"` // A one-sentence description of the chart Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty"` // A list of string keywords Keywords []string `protobuf:"bytes,6,rep,name=keywords,proto3" json:"keywords,omitempty"` // A list of name and URL/email address combinations for the maintainer(s) Maintainers []*Maintainer `protobuf:"bytes,7,rep,name=maintainers,proto3" json:"maintainers,omitempty"` // The name of the template engine to use. Defaults to 'gotpl'. Engine string `protobuf:"bytes,8,opt,name=engine,proto3" json:"engine,omitempty"` // The URL to an icon file. Icon string `protobuf:"bytes,9,opt,name=icon,proto3" json:"icon,omitempty"` // The API Version of this chart. ApiVersion string `protobuf:"bytes,10,opt,name=apiVersion,proto3" json:"apiVersion,omitempty"` // The condition to check to enable chart Condition string `protobuf:"bytes,11,opt,name=condition,proto3" json:"condition,omitempty"` // The tags to check to enable chart Tags string `protobuf:"bytes,12,opt,name=tags,proto3" json:"tags,omitempty"` // The version of the application enclosed inside of this chart. AppVersion string `protobuf:"bytes,13,opt,name=appVersion,proto3" json:"appVersion,omitempty"` // Whether or not this chart is deprecated Deprecated bool `protobuf:"varint,14,opt,name=deprecated,proto3" json:"deprecated,omitempty"` // TillerVersion is a SemVer constraints on what version of Tiller is required. // See SemVer ranges here: https://github.com/Masterminds/semver#basic-comparisons TillerVersion string `protobuf:"bytes,15,opt,name=tillerVersion,proto3" json:"tillerVersion,omitempty"` // Annotations are additional mappings uninterpreted by Tiller, // made available for inspection by other applications. Annotations map[string]string `protobuf:"bytes,16,rep,name=annotations,proto3" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // KubeVersion is a SemVer constraint specifying the version of Kubernetes required. KubeVersion string `protobuf:"bytes,17,opt,name=kubeVersion,proto3" json:"kubeVersion,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Metadata) Reset() { *m = Metadata{} } func (m *Metadata) String() string { return proto.CompactTextString(m) } func (*Metadata) ProtoMessage() {} func (*Metadata) Descriptor() ([]byte, []int) { return <API key>, []int{1} } func (m *Metadata) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *Metadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *Metadata) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *Metadata) XXX_Size() int { return <API key>.Size(m) } func (m *Metadata) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *Metadata) GetName() string { if m != nil { return m.Name } return "" } func (m *Metadata) GetHome() string { if m != nil { return m.Home } return "" } func (m *Metadata) GetSources() []string { if m != nil { return m.Sources } return nil } func (m *Metadata) GetVersion() string { if m != nil { return m.Version } return "" } func (m *Metadata) GetDescription() string { if m != nil { return m.Description } return "" } func (m *Metadata) GetKeywords() []string { if m != nil { return m.Keywords } return nil } func (m *Metadata) GetMaintainers() []*Maintainer { if m != nil { return m.Maintainers } return nil } func (m *Metadata) GetEngine() string { if m != nil { return m.Engine } return "" } func (m *Metadata) GetIcon() string { if m != nil { return m.Icon } return "" } func (m *Metadata) GetApiVersion() string { if m != nil { return m.ApiVersion } return "" } func (m *Metadata) GetCondition() string { if m != nil { return m.Condition } return "" } func (m *Metadata) GetTags() string { if m != nil { return m.Tags } return "" } func (m *Metadata) GetAppVersion() string { if m != nil { return m.AppVersion } return "" } func (m *Metadata) GetDeprecated() bool { if m != nil { return m.Deprecated } return false } func (m *Metadata) GetTillerVersion() string { if m != nil { return m.TillerVersion } return "" } func (m *Metadata) GetAnnotations() map[string]string { if m != nil { return m.Annotations } return nil } func (m *Metadata) GetKubeVersion() string { if m != nil { return m.KubeVersion } return "" } func init() { proto.RegisterType((*Maintainer)(nil), "hapi.chart.Maintainer") proto.RegisterType((*Metadata)(nil), "hapi.chart.Metadata") proto.RegisterMapType((map[string]string)(nil), "hapi.chart.Metadata.AnnotationsEntry") proto.RegisterEnum("hapi.chart.Metadata_Engine", <API key>, <API key>) } func init() { proto.RegisterFile("hapi/chart/metadata.proto", <API key>) } var <API key> = []byte{ // 435 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x52, 0x5d, 0x6b, 0xd4, 0x40, 0x14, 0x35, 0xcd, 0x66, 0x77, 0x73, 0x63, 0x35, 0x0e, 0x52, 0xc6, 0x22, 0x12, 0x16, 0x85, 0x7d, 0xda, 0x82, 0xbe, 0x14, 0x1f, 0x04, 0x85, 0x52, 0x41, 0xbb, 0x95, 0xe0, 0x07, 0xf8, 0x36, 0x4d, 0x2e, 0xdd, 0x61, 0x93, 0x99, 0x30, 0x99, 0xad, 0xec, 0xaf, 0xf0, 0x2f, 0xcb, 0xdc, 0x64, 0x9a, 0xac, 0xf4, 0xed, 0x9e, 0x73, 0x66, 0xce, 0xcc, 0xbd, 0xf7, 0xc0, 0x8b, 0x8d, 0x68, 0xe4, 0x59, 0xb1, 0x11, 0xc6, 0x9e, 0xd5, 0x68, 0x45, 0x29, 0xac, 0x58, 0x35, 0x46, 0x5b, 0xcd, 0xc0, 0x49, 0x2b, 0x92, 0x16, 0x9f, 0x01, 0xae, 0x84, 0x54, 0x56, 0x48, 0x85, 0x86, 0x31, 0x98, 0x28, 0x51, 0x23, 0x0f, 0xb2, 0x60, 0x19, 0xe7, 0x54, 0xb3, 0xe7, 0x10, 0x61, 0x2d, 0x64, 0xc5, 0x8f, 0x88, 0xec, 0x00, 0x4b, 0x21, 0xdc, 0x99, 0x8a, 0x87, 0xc4, 0xb9, 0x72, 0xf1, 0x37, 0x82, 0xf9, 0x55, 0xff, 0xd0, 0x83, 0x46, 0x0c, 0x26, 0x1b, 0x5d, 0x63, 0xef, 0x43, 0x35, 0xe3, 0x30, 0x6b, 0xf5, 0xce, 0x14, 0xd8, 0xf2, 0x30, 0x0b, 0x97, 0x71, 0xee, 0xa1, 0x53, 0xee, 0xd0, 0xb4, 0x52, 0x2b, 0x3e, 0xa1, 0x0b, 0x1e, 0xb2, 0x0c, 0x92, 0x12, 0xdb, 0xc2, 0xc8, 0xc6, 0x3a, 0x35, 0x22, 0x75, 0x4c, 0xb1, 0x53, 0x98, 0x6f, 0x71, 0xff, 0x47, 0x9b, 0xb2, 0xe5, 0x53, 0xb2, 0xbd, 0xc7, 0xec, 0x1c, 0x92, 0xfa, 0xbe, 0xe1, 0x96, 0xcf, 0xb2, 0x70, 0x99, 0xbc, 0x3d, 0x59, 0x0d, 0x23, 0x59, 0x0d, 0xf3, 0xc8, 0xc7, 0x47, 0xd9, 0x09, 0x4c, 0x51, 0xdd, 0x4a, 0x85, 0x7c, 0x4e, 0x4f, 0xf6, 0xc8, 0xf5, 0x25, 0x0b, 0xad, 0x78, 0xdc, 0xf5, 0xe5, 0x6a, 0xf6, 0x0a, 0x40, 0x34, 0xf2, 0x67, 0xdf, 0x00, 0x90, 0x32, 0x62, 0xd8, 0x4b, 0x88, 0x0b, 0xad, 0x4a, 0x49, 0x1d, 0x24, 0x24, 0x0f, 0x84, 0x73, 0xb4, 0xe2, 0xb6, 0xe5, 0x8f, 0x3b, 0x47, 0x57, 0x77, 0x8e, 0x8d, 0x77, 0x3c, 0xf6, 0x8e, 0x9e, 0x71, 0x7a, 0x89, 0x8d, 0xc1, 0x42, 0x58, 0x2c, 0xf9, 0x93, 0x2c, 0x58, 0xce, 0xf3, 0x11, 0xc3, 0x5e, 0xc3, 0xb1, 0x95, 0x55, 0x85, 0xc6, 0x5b, 0x3c, 0x25, 0x8b, 0x43, 0x92, 0x5d, 0x42, 0x22, 0x94, 0xd2, 0x56, 0xb8, 0x7f, 0xb4, 0x3c, 0xa5, 0xe9, 0xbc, 0x39, 0x98, 0x8e, 0xcf, 0xd2, 0xc7, 0xe1, 0xdc, 0x85, 0xb2, 0x66, 0x9f, 0x8f, 0x6f, 0xba, 0x25, 0x6d, 0x77, 0x37, 0xe8, 0x1f, 0x7b, 0xd6, 0x2d, 0x69, 0x44, 0x9d, 0x7e, 0x80, 0xf4, 0x7f, 0x0b, 0x97, 0xaa, 0x2d, 0xee, 0xfb, 0xd4, 0xb8, 0xd2, 0xa5, 0xef, 0x4e, 0x54, 0x3b, 0x9f, 0x9a, 0x0e, 0xbc, 0x3f, 0x3a, 0x0f, 0x16, 0x19, 0x4c, 0x2f, 0xba, 0x05, 0x24, 0x30, 0xfb, 0xb1, 0xfe, 0xb2, 0xbe, 0xfe, 0xb5, 0x4e, 0x1f, 0xb1, 0x18, 0xa2, 0xcb, 0xeb, 0xef, 0xdf, 0xbe, 0xa6, 0xc1, 0xa7, 0xd9, 0xef, 0x88, 0xfe, 0x7c, 0x33, 0xa5, 0xdc, 0xbf, 0xfb, 0x17, 0x00, 0x00, 0xff, 0xff, 0x36, 0xf9, 0x0d, 0xa6, 0x14, 0x03, 0x00, 0x00, }
'use strict'; /** * @class * Initializes a new instance of the <API key> class. * @constructor * The list data source by workspace operation response. * * @member {string} [nextLink] The link (url) to the next page of datasources. * */ class <API key> extends Array { constructor() { super(); } /** * Defines the metadata of <API key> * * @returns {object} metadata of <API key> * */ mapper() { return { required: false, serializedName: '<API key>', type: { name: 'Composite', className: '<API key>', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: '<API key>', type: { name: 'Composite', className: 'DataSource' } } } }, nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } } } } }; } } module.exports = <API key>;
<link rel="import" href="../../../../../bower_components/paper-spinner/paper-spinner.html"> <dom-module id="nav-level-element"> <style> :host{ display: block; height: 100%; } .circle { width: 25px; height: 25px; -moz-border-radius: 15px; -<API key>: 15px; border-radius: 15px; } .empty{ line-height:25px; } .current{ background: #87CEFA; } .green{ background: #86C67C; } .gray{ border: 1px solid black; } .wrapper{ text-align:center; margin: 7px; } </style> <template> <div class="wrapper" on-click="_onClick"> <div class$="{{divClass}}"> <span class="empty"></span> </div> </div> </template> <script> Polymer({ is: 'nav-level-element', properties:{ divClass: { type: String, notify: true, value: 'circle gray' }, state: { value: 'default' } }, observers: [ '_stateChanged(state)' ], _onClick: function(){ this.fire('task-switch', this.index); }, _stateChanged: function(state){ if(state === 'completed'){ this.divClass = 'circle green'; }else if(state === 'current'){ this.divClass = 'circle current'; }else{ this.divClass = 'circle gray'; } }, setState: function(state){ this.state = state; } }); </script> </dom-module>
package GRNOC::TSDS::DataService::Aggregation; use strict; use warnings; use base 'GRNOC::TSDS::DataService'; use GRNOC::Log; use GRNOC::TSDS::MongoDB; use GRNOC::TSDS::Parser; use Tie::IxHash; use DateTime; use DateTime::Format::Strptime; use Data::Dumper; use JSON qw( decode_json ); constants use constant DEFAULT_COLLECTIONS => ['data', 'measurements', 'metadata', 'aggregate', 'expire']; # this will hold the only actual reference to this object my $singleton; sub new { my $caller = shift; my $class = ref( $caller ); $class = $caller if ( !$class ); # if we've created this object (singleton) before, just return it return $singleton if ( defined( $singleton ) ); my $self = $class->SUPER::new( @_ ); bless( $self, $class ); # store our newly created object as the singleton $singleton = $self; $self->parser( GRNOC::TSDS::Parser->new( @_ ) ); return $self; } # GET METHODS sub get_aggregations { my ( $self, %args ) = @_; my $meta_fields; my @aggregation_fields; my $measurement_type = $args{'measurement_type'}; my $<API key> = $self->mongo_ro()->get_collection($measurement_type, "aggregate"); if (! $<API key> ) { $self->error( 'Invalid Measurement Type.' ); return; } my $aggregates = $<API key>->find(); if (! $aggregates ) { $self->error( 'Invalid Measurement Type: no aggregations found.' ); return; } my @aggregate_results = @{$self->_get_agg_exp_fields($aggregates)}; my @new_results = sort by_blanklast ( @aggregate_results ); return \@new_results; } sub get_expirations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $<API key> = $self->mongo_ro()->get_collection($measurement_type, "expire"); if (! $<API key> ) { $self->error( 'Invalid Measurement Type.' ); return; } my $expirations = $<API key>->find(); if (! $expirations ) { $self->error( 'Invalid Measurement Type: no expirations found.' ); return; } my @expiration_results = @{$self->_get_agg_exp_fields($expirations)}; my @new_results = sort by_blanklast ( @expiration_results ); return \@new_results; } # UPDATE METHOD sub update_aggregations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $meta = $args{'meta'}; my $name = $args{'name'}; my $new_name = $args{'new_name'}; my $max_age = $args{'max_age'}; my $eval_position = $args{'eval_position'}; my $values = $args{'values'}; # convert numeric params to ints $eval_position = int $eval_position if(defined($eval_position)); $max_age = int $max_age if(defined($max_age)); my $query = {'name'=> $name}; if (!defined($name) || $name eq '') { $self->error("You must specify a name to update an aggregation/expiration."); return; } if (exists($args{'new_name'}) && (!defined($new_name) || $new_name eq '')) { $self->error("You must enter text for the new_name field"); return; } if (defined($values)){ return if (!$self->_validate_values($values, $measurement_type)); } # get the aggregate collection my $agg_col = $self->mongo_rw()->get_collection($measurement_type, "aggregate"); if(!$agg_col){ $self->error($self->mongo_rw()->error()); return; } # make sure this aggregate record exists if(!$self->_agg_exp_exists( col => $agg_col, name => $name )){ $self->error("Aggregation named $name doesn't exist"); return; } # reorder eval positions if(defined($eval_position)){ my $position_res = $self-><API key>( collection => $agg_col, name => $name, eval_position => $eval_position ); } my $set = {}; my $id; $set->{'meta'} = $meta if(exists($args{'meta'})); $set->{'values'} = $values if(exists($args{'values'})); $set->{'name'} = $new_name if(exists($args{'new_name'})); if(!%$set && !exists($args{'eval_position'})){ $self->error( "You must pass in at least 1 field to update" ); return; } if(%$set){ $id = $agg_col->update_one($query, { '$set' => $set } ); if(!$id) { $self->error( "Error updating values in aggregate with name $name"); return; } } return [{ 'success' => 1 }]; } sub update_expirations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $meta = $args{'meta'}; my $name = $args{'name'}; my $new_name = $args{'new_name'}; my $max_age = $args{'max_age'}; my $eval_position = $args{'eval_position'}; my $values = $args{'values'}; # convert numeric params to ints $eval_position = int $eval_position if(defined($eval_position)); $max_age = int $max_age if(defined($max_age)); if (!defined($name) || $name eq '') { $self->error("You must specify a name to update an aggregation/expiration."); return; } if (exists($args{'new_name'}) && (!defined($new_name) || $new_name eq '')) { $self->error("You must enter text for the new_name field"); return; } # get the expire collection my $exp_col = $self->mongo_rw()->get_collection($measurement_type, "expire"); if(!$exp_col){ $self->error($self->mongo_rw()->error()); return; } # make sure this aggregate record exists if(!$self->_agg_exp_exists( col => $exp_col, name => $name )){ $self->error("Expiration named $name doesn't exist"); return; } # reorder eval positions if(defined($eval_position)){ my $position_res = $self-><API key>( collection => $exp_col, name => $name, eval_position => $eval_position ); } # figure out which fields were modifying for the expire record my $set = {}; $set->{'meta'} = $meta if(exists($args{'meta'})); $set->{'max_age'} = $max_age if(exists($args{'max_age'})); $set->{'name'} = $new_name if(exists($args{'new_name'})); # if it's the default expire record don't allow them to edit anything but max_age if($name eq 'default'){ foreach my $field (keys %$set){ if($field ne 'max_age'){ $self->error( "You can only edit the max_age on the default expire record"); return; } } } if(%$set){ my $id = $exp_col->update_one({ name => $name }, { '$set' => $set } ); if(!$id) { $self->error( "Error updating values in expiration with name $name"); return; } } return [{ 'success' => 1 }]; } # INSERT METHOD sub add_aggregation { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $interval = $args{'interval'}; my $meta = $args{'meta'}; my $name = $args{'name'}; my $values = $args{'values'}; #sanity checks if (!defined($name) || $name eq '') { $self->error("You must specify a name for the aggregation."); return; } if (defined($values)){ return if (! $self->_validate_values($values, $measurement_type)); } if(!defined($interval)){ $self->error("You must specify an interval to aggregate the data on"); return; } my $set = {}; $set->{'interval'} = int($interval) if(defined($interval)); $set->{'name'} = $name if(defined($name)); $set->{'values'} = $values if(defined($values)); # meta might not be passed in, it needs to be set to empty object to avoid problem with deletion if(defined($meta)) { $set->{'meta'} = $meta; } else { $set->{'meta'} = "{}"; } # get the aggregate collections my $agg_col = $self->mongo_rw()->get_collection($measurement_type, "aggregate"); if(!$agg_col){ $self->error($self->mongo_rw()->error()); return; } # make sure this aggregation doesn't already exists if($self->_agg_exp_exists( col => $agg_col, name => $name )){ $self->error("Aggregation named, $name, already exist"); return; } # figure out the highest eval_position currently used (if any) my $<API key> = $self-><API key>( col => $agg_col ); my $new_eval_position = $<API key> + 10; $set->{'eval_position'} = $new_eval_position; # create the data_[interval] collection if(!$self->mongo_root()-><API key>( $measurement_type, "data_$interval" , $GRNOC::TSDS::MongoDB::DATA_SHARDING )){ $self->error( "Error adding collection shard for data_$interval measurement_type: ".$self->mongo_rw()->error() ); return; } my $agg_data_col = $self->mongo_rw()->get_collection( $measurement_type, "data_$interval", create => 1 ); my $indexes = $agg_data_col->indexes(); $indexes->create_one([start => 1]); $indexes->create_one([end => 1]); $indexes->create_one([updated => 1, identifier => 1]); $indexes->create_one([identifier => 1, start => 1, end => 1]); my $id = $agg_col->insert_one($set); if(!$id) { $self->error( "Error inserting values in aggregate with interval $interval and meta $meta"); return; } return [{ 'success' => 1 }]; } sub add_expiration { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $interval = $args{'interval'}; my $meta = $args{'meta'}; my $name = $args{'name'}; my $max_age = $args{'max_age'}; #sanity checks if (!defined($name) || $name eq '') { $self->error("You must specify a name for the expiration."); return; } if(!defined($max_age)){ $self->error("You must specify the max_age of the data of the expiration."); return; } my $set = {}; $set->{'interval'} = int($interval) if(defined($interval)); $set->{'meta'} = $meta if(defined($meta)); $set->{'name'} = $name if(defined($name)); $set->{'max_age'} = int($max_age) if(defined($max_age)); # if they've set an interval make sure an aggregation with the same interval exists # (we can't expire aggregated data that doesn't exists) if(defined($interval)){ my $found_interval = 0; my $aggregations = $self->get_aggregations( measurement_type => $measurement_type ); foreach my $aggregation (@$aggregations){ next if($aggregation->{'interval'} ne $interval); $found_interval = 1; last; } if(!$found_interval){ $self->error("Can not add expiration at interval $interval. There must be an aggregation at interval, $interval to expire"); return; } } my $exp_col = $self->mongo_rw()->get_collection($measurement_type, "expire"); if(!$exp_col){ $self->error($self->mongo_rw()->error()); return; } # make sure this expiration doesn't already exists if($self->_agg_exp_exists( col => $exp_col, name => $name )){ $self->error("Expiration named, $name, already exist"); return; } # figure out the highest eval_position currently used (if any) my $<API key> = $self-><API key>( col => $exp_col ); my $new_eval_position = $<API key> + 10; $set->{'eval_position'} = $new_eval_position; my $id = $exp_col->insert_one( $set ); if(!$id) { $self->error( "Error inserting values in expiration with interval $interval and meta $meta"); return; } return [{ 'success' => 1 }]; } sub _agg_exp_exists { my ( $self, %args ) = @_; my $col = $args{'col'}; my $name = $args{'name'}; # make sure a agg doesn't already exist with this name my $count = $col->count({ name => $name }); return 1 if $count; return 0; } sub <API key> { my ( $self, %args ) = @_; my $col = $args{'col'}; my @aggregates = $col->find( {} )->all(); my $<API key> = 0; foreach my $aggregate ( @aggregates ) { my $eval_position = $aggregate->{'eval_position'}; if ( $eval_position && $eval_position > $<API key> ) { $<API key> = $eval_position; } } return $<API key>; } # DELETE METHOD sub delete_aggregations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $name = $args{'name'}; # sanity checks if (!defined($name) || $name eq '') { $self->error("You must specify a name to delete an aggregation/expiration."); return; } # get the aggregate collection my $agg_col = $self->mongo_rw()->get_collection($measurement_type, "aggregate"); if(!$agg_col){ $self->error($self->mongo_rw()->error()); return; } # make sure the aggregate rule with this name exists if(!$self->_agg_exp_exists( col => $agg_col, name => $name )){ $self->error("Aggregation named, $name, doesn't exist"); return; } # remove the data_$interval collection my $interval = $agg_col->find({ name => $name })->next()->{'interval'}; my $agg_data_col = $self->mongo_rw()->get_collection($measurement_type, "data_$interval"); # now delete the relevant data from the aggregate data collection and possbilly the whole # collection if no data if left after the delete $self-><API key>( interval => $interval, measurement_type => $measurement_type, agg_col => $agg_col, agg_data_col => $agg_data_col, name => $name ) || return; # remove the aggregate rule from the collection my $id = $agg_col->delete_one({name => $name}); if(!$id) { $self->error( "Error removing aggregate rule for $name."); return; } # get the related expire rule and remove it from the expire collection my $exp_col = $self->mongo_rw()->get_collection($measurement_type, "expire"); if(!$exp_col){ $self->error($self->mongo_rw()->error()); return; } $id = $exp_col->delete_one({ name => $name }); if(!$id) { $self->error( "Error removing values from expiration with name $name."); return; } return [{ 'success' => 1 }]; } sub <API key> { my ( $self, %args ) = @_; my $interval = $args{'interval'}; my $measurement_type = $args{'measurement_type'}; my $agg_col = $args{'agg_col'}; my $agg_data_col = $args{'agg_data_col'}; my $name = $args{'name'}; # the name of the aggregation being deleted # build an array of all of the meta data from the aggregations we're not deleting # within this interval my $nor = []; my $cur = $agg_col->find({}); while (my $agg = $cur->next()) { next if($name ne $agg->{'name'}); next if($interval ne $agg->{'interval'}); my $meta; eval { $meta = decode_json( $agg->{'meta'} ); }; if($@){ $self->error("Problem decoding meta scope for aggregate ".$agg->{'name'}.": $@"); return; } push(@$nor, $meta); } # grab the measurement collection for this measurement_type my $meas_col = $self->mongo_rw()->get_collection($measurement_type, "aggregate"); if(!$meas_col){ $self->error($self->mongo_rw()->error()); return; } # now find all the identifiers that do not match that meta data # of the remaining aggregations my $ids = []; if(@$nor){ $cur = $meas_col->find({ '$nor' => $nor }, { identifier => 1 }); while (my $meas = $cur->next()) { push(@$ids, $meas->{'identifier'}); } } # if there's other aggregations besides the one we are deleting # delete everything in data_$interval that doesn't match their metadata scope if(@$ids){ my $res = $agg_data_col->delete_many({ identifier => { '$in' => $ids } }); if(!$res) { $self->error( "Error removing values from aggregate with name $name."); return; } } # if there's no data left in the agg data cursor drop it if ($agg_data_col->count({}) == 0) { $agg_data_col->drop(); } return 1; } sub delete_expirations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $name = $args{'name'}; # sanity checks if (!defined($name) || $name eq '') { $self->error("You must specify a name to delete an aggregation/expiration."); return; } if ($name eq 'default'){ $self->error("You can not delete the default expire rule."); return; } # get the expire rule and remove it from the expire collection my $exp_col = $self->mongo_rw()->get_collection($measurement_type, "expire"); if(!$exp_col){ $self->error($self->mongo_rw()->error()); return; } # make sure the aggregate rule with this name exists if(!$self->_agg_exp_exists( col => $exp_col, name => $name )){ $self->error("Aggregation named, $name, doesn't exist"); return; } my $id = $exp_col->delete_one({name => $name}); if(!$id) { $self->error( "Error removing values from expiration with name $name."); return; } return [{ 'success' => 1 }]; } sub _get_agg_exp_fields { my ($self, $cursor) = @_; my @results = (); while (my $doc = $cursor->next()) { my %row; foreach my $key (keys %$doc) { next if $key eq '_id'; my $value = $doc->{$key}; $row{$key} = $value; } push @results, \%row; } return \@results; } sub <API key> { my ($self, %args) = @_; my $col = $args{'collection'}; my $name = $args{'name'}; my $new_eval_position = $args{'eval_position'} || 10; my $query = {'name' => $name}; my $old_eval_position = $self->_get_eval_position( col => $col, name => $name); # see if there is another rule with the same eval_position my $same_eval_position = $self-><API key>( 'eval_position' => $new_eval_position, 'name', => $name, 'col' => $col ); # if this eval position isn't in use by another rule if (!$same_eval_position && ($old_eval_position == $new_eval_position)) { return { 'success' => 1 }; } # see if there are values (other than this one) that # lack eval_positions my $has_empty_values = $self-><API key>( 'name' => $name, 'col' => $col ); # if there is no conflict, and there are no other null values, # just update the current rule if (!$same_eval_position && !$has_empty_values) { my $result = $self->_set_eval_position( 'eval_position' => $new_eval_position, 'name' => $name, 'col' => $col ); # if there is a conflict, we need to reorder } else { my $result = $self-><API key>( 'old_eval_position' => $old_eval_position, 'new_eval_position' => $new_eval_position, 'name' => $name, 'col' => $col ); } } sub <API key> { my ($self, %args) = @_; my $name = $args{'name'}; my $col = $args{'col'}; my $query = { 'eval_position' => { '$exists' => 0 }, 'name' => { '$ne' => $name } }; if ($col->count($query)) { return 1; } return 0; } sub <API key> { my ( $self, %args ) = @_; my $new_eval_position = $args{'new_eval_position'}; my $old_eval_position = $args{'old_eval_position'}; my $name = $args{'name'}; my $col = $args{'col'}; my $query = { 'name' => $name }; # these are the other docregations that didn't get updated / aren't getting their position replaced my $other_cur = $col->find( { 'eval_position' => {'$ne' => $new_eval_position}, 'name' => {'$ne' => $name} } ); my $other_docs = []; # detect error return if ( !defined( $other_docs ) ); while (my $doc = $other_cur->next()) { push @$other_docs, $doc; } # get the other docregations in the table that are getting their position replaced my $replaced_docs = []; my $replaced_cur = $col->find( {'eval_position' => $new_eval_position, 'name' => {'$ne' => $name} } ); while (my $doc = $replaced_cur->next()) { my %row = (); push @$replaced_docs, $doc; } # detect error return if ( !defined( $replaced_cur ) ); my $updated_doc = $col->find_one( $query ); $updated_doc->{'eval_position'} = $new_eval_position; return if ( !defined( $updated_doc ) ); # does the updated rule need to go *below* the rule its taking place of? (drdocing down # or there is no old eval position) if (defined($old_eval_position) && $new_eval_position > $old_eval_position ) { push( @$replaced_docs, $updated_doc ); } else { # the update rule needs to go *above* the rule its taking place of. (drdocing up) unshift( @$replaced_docs, $updated_doc ); } # generate the new full list in the correct order my @new_list = sort by_blanklast ( @$other_docs, @$replaced_docs ); # update every rule's eval_position from 10 .. based upon the new order my $i = 10; foreach my $rule ( @new_list ) { #warn 'updating ' . $rule->{'name'} . ' to eval position: ' . $i; my $update_query = { 'name' => $rule->{'name'} }; my $set = { 'eval_position' => $i }; my $exp_res = $col->update_one($update_query, {'$set' => $set }); $i += 10; } } sub _set_eval_position { my ( $self, %args ) = @_; my $eval_position = $args{'eval_position'}; my $name = $args{'name'}; my $col = $args{'col'}; my $query = { 'name' => $name }; my $set = { 'eval_position' => $eval_position }; my $exp_res = $col->update_one($query, { '$set' => $set }); if (!$exp_res) { return 0; } return 1; } sub <API key> { my ( $self, %args ) = @_; my $eval_position = $args{'eval_position'}; my $name = $args{'name'}; my $col = $args{'col'}; my $query = { 'eval_position' => $eval_position, 'name' => {'$ne' => $name} }; my $exp_res = $col->find($query); my $in_use = $col->count(); return $in_use; } sub _get_eval_position {my ( $self, %args ) = @_; my $col = $args{'col'}; my $name = $args{'name'}; # make sure the collection/name exists my $result = $col->find_one({ name => $name }); if(!$result){ return; } my $eval_position = $result->{'eval_position'}; return $eval_position; } sub _validate_values { my $self = shift; my $obj = shift; my $type = shift; if (ref $obj ne 'HASH'){ $self->error("values must be an object"); return; } my $metadata = $self->mongo_rw()->get_collection($type, 'metadata'); if (! $metadata){ $self->error($self->mongo_rw()->error()); return; } $metadata = $metadata->find_one(); # Make sure each value exists and that the values we're passing # in for aggregation configuration make sense foreach my $value_name (keys %$obj){ if (! exists $metadata->{'values'}{$value_name}){ $self->error("Unknown value \"$value_name\""); return; } foreach my $key (keys %{$obj->{$value_name}}){ my $key_value = $obj->{$value_name}{$key}; # Make sure we only passed in keys that we know about if ($key ne 'hist_res' && $key ne 'hist_min_width'){ $self->error("Unknown value field \"$key\" for value \"$value_name\""); return; } # A null value is okay if (! defined $key_value || $key_value eq ''){ $obj->{$value_name}{$key} = undef; } # Make sure they are numbers else { if ($key_value !~ /^\d+(\.\d+)?$/){ $self->error("Value field \"$key\" for value \"$value_name\" must be a number"); return; } # Make sure the fields are sane if ($key eq 'hist_res'){ if ($key_value >= 100 || $key_value <= 0){ $self->error("hist_res for value \"$value_name\" must be between 0 and 100"); return; } } elsif ($key eq 'hist_min_width'){ if ($key_value <= 0){ $self->error("hist_min_width for value \"$value_name\" must be greater than 0"); return; } } } } } return 1; } # sort by eval_position, putting the rows that lack an eval_position # at the bottom sub by_blanklast { # if only one object doesn't have an eval position set put the object # without an eval position at the end if (!exists($a->{'eval_position'}) ^ !exists($b->{'eval_position'})){ return exists($b->{'eval_position'}) - exists($a->{'eval_position'}); } # if both objects don't have an eval position set sort by name elsif(!exists($a->{'eval_position'}) && !exists($b->{'eval_position'})){ return $a->{'name'} cmp $b->{'name'}; } # otherwise just sort by the eval position return $a->{'eval_position'} cmp $b->{'eval_position'}; } 1;
#include "config/config.h" #include <sys/types.h> #include <sys/wait.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/errno.h> #include <string.h> #include "dispatch_test.h" #define _test_print(_file, _line, _desc, \ _expr, _fmt1, _val1, _fmt2, _val2) do { \ const char* _exprstr = _expr ? "PASS" : "FAIL"; \ char _linestr[BUFSIZ]; \ if (!_expr) { \ snprintf(_linestr, sizeof(_linestr), \ " (%s:%ld)", _file, _line); \ } else { \ _linestr[0] = 0; \ } \ if (_fmt2 == 0) { \ printf("\tValue: " _fmt1 "\n" \ "[%s] %s%s\n", \ _val1, \ _exprstr, \ _desc, \ _linestr); \ } else { \ printf("\tActual: " _fmt1 "\n" \ "\tExpected: " _fmt2 "\n" \ "[%s] %s%s\n", \ _val1, \ _val2, \ _exprstr, \ _desc, \ _linestr); \ } \ if (!_expr) { \ printf("\t%s:%ld\n", _file, _line); \ } \ fflush(stdout); \ } while (0); void test_start(const char* desc) { printf("\n==================================================\n"); printf("[TEST] %s\n", desc); printf("[PID] %d\n", getpid()); printf("==================================================\n\n"); usleep(100000); // give 'gdb --waitfor=' a chance to find this proc } #define test_ptr_null(a,b) _test_ptr_null(__FILE__, __LINE__, a, b) void _test_ptr_null(const char* file, long line, const char* desc, const void* ptr) { _test_print(file, line, desc, (ptr == NULL), "%p", ptr, "%p", (void*)0); } #define test_ptr_notnull(a,b) _test_ptr_notnull(__FILE__, __LINE__, a, b) void _test_ptr_notnull(const char* file, long line, const char* desc, const void* ptr) { _test_print(file, line, desc, (ptr != NULL), "%p", ptr, "%p", ptr ?: (void*)~0); } #define test_ptr(a,b,c) _test_ptr(__FILE__, __LINE__, a, b, c) void _test_ptr(const char* file, long line, const char* desc, const void* actual, const void* expected) { _test_print(file, line, desc, (actual == expected), "%p", actual, "%p", expected); } #define test_long(a,b,c) _test_long(__FILE__, __LINE__, a, b, c) void _test_long(const char* file, long line, const char* desc, long actual, long expected) { _test_print(file, line, desc, (actual == expected), "%ld", actual, "%ld", expected); } #define test_long_less_than(a, b, c) <API key>(__FILE__, __LINE__, a, b, c) void <API key>(const char* file, long line, const char* desc, long actual, long expected_max) { _test_print(file, line, desc, (actual < expected_max), "%ld", actual, "<%ld", expected_max); } #define <API key>(d, v, m) <API key>(__FILE__, __LINE__, d, v, m) void <API key>(const char* file, long line, const char* desc, double val, double max_expected) { _test_print(file, line, desc, (val < max_expected), "%f", val, "<%f", max_expected); } #define <API key>(d, v, m) <API key>(__FILE__, __LINE__, d, v, m) void <API key>(const char* file, long line, const char* desc, double val, double max_expected) { _test_print(file, line, desc, (val <= max_expected), "%f", val, "<%f", max_expected); } #define test_errno(a,b,c) _test_errno(__FILE__, __LINE__, a, b, c) void _test_errno(const char* file, long line, const char* desc, long actual, long expected) { char* actual_str; char* expected_str; asprintf(&actual_str, "%ld\t%s", actual, actual ? strerror(actual) : ""); asprintf(&expected_str, "%ld\t%s", expected, expected ? strerror(expected) : ""); _test_print(file, line, desc, (actual == expected), "%s", actual_str, "%s", expected_str); free(actual_str); free(expected_str); } //#include <spawn.h> extern char **environ; void test_stop(void) { <API key>((void *)(intptr_t)0); } void <API key>(void *delay) { #if HAVE_LEAKS int res; pid_t pid; char pidstr[10]; #endif if (delay != NULL) { sleep((int)(intptr_t)delay); } #if HAVE_LEAKS if (getenv("NOLEAKS")) _exit(EXIT_SUCCESS); /* leaks doesn't work against debug variant malloc */ if (getenv("DYLD_IMAGE_SUFFIX")) _exit(EXIT_SUCCESS); snprintf(pidstr, sizeof(pidstr), "%d", getpid()); char* args[] = { "./leaks-wrapper", pidstr, NULL }; res = posix_spawnp(&pid, args[0], NULL, NULL, args, environ); if (res == 0 && pid > 0) { int status; waitpid(pid, &status, 0); test_long("Leaks", status, 0); } else { perror(args[0]); } #endif _exit(EXIT_SUCCESS); }
/* Atmel Microcontroller Software Support */ /* modification, are permitted provided that the following condition is met: */ /* Atmel's name may not be used to endorse or promote products derived from */ /* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE */ /* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */ /* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, */ /* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */ /* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */ /* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, */ /* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef <API key> #define <API key> /** SOFTWARE API DEFINITION FOR High Speed MultiMedia Card Interface */ /** \addtogroup SAM4E_HSMCI High Speed MultiMedia Card Interface */ #if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) /** \brief Hsmci hardware registers */ typedef struct { __O uint32_t HSMCI_CR; /**< \brief (Hsmci Offset: 0x00) Control Register */ __IO uint32_t HSMCI_MR; /**< \brief (Hsmci Offset: 0x04) Mode Register */ __IO uint32_t HSMCI_DTOR; /**< \brief (Hsmci Offset: 0x08) Data Timeout Register */ __IO uint32_t HSMCI_SDCR; /**< \brief (Hsmci Offset: 0x0C) SD/SDIO Card Register */ __IO uint32_t HSMCI_ARGR; /**< \brief (Hsmci Offset: 0x10) Argument Register */ __O uint32_t HSMCI_CMDR; /**< \brief (Hsmci Offset: 0x14) Command Register */ __IO uint32_t HSMCI_BLKR; /**< \brief (Hsmci Offset: 0x18) Block Register */ __IO uint32_t HSMCI_CSTOR; /**< \brief (Hsmci Offset: 0x1C) Completion Signal Timeout Register */ __I uint32_t HSMCI_RSPR[4]; /**< \brief (Hsmci Offset: 0x20) Response Register */ __I uint32_t HSMCI_RDR; /**< \brief (Hsmci Offset: 0x30) Receive Data Register */ __O uint32_t HSMCI_TDR; /**< \brief (Hsmci Offset: 0x34) Transmit Data Register */ __I uint32_t Reserved1[2]; __I uint32_t HSMCI_SR; /**< \brief (Hsmci Offset: 0x40) Status Register */ __O uint32_t HSMCI_IER; /**< \brief (Hsmci Offset: 0x44) Interrupt Enable Register */ __O uint32_t HSMCI_IDR; /**< \brief (Hsmci Offset: 0x48) Interrupt Disable Register */ __I uint32_t HSMCI_IMR; /**< \brief (Hsmci Offset: 0x4C) Interrupt Mask Register */ __I uint32_t Reserved2[1]; __IO uint32_t HSMCI_CFG; /**< \brief (Hsmci Offset: 0x54) Configuration Register */ __I uint32_t Reserved3[35]; __IO uint32_t HSMCI_WPMR; /**< \brief (Hsmci Offset: 0xE4) Write Protection Mode Register */ __I uint32_t HSMCI_WPSR; /**< \brief (Hsmci Offset: 0xE8) Write Protection Status Register */ __I uint32_t Reserved4[5]; __IO uint32_t HSMCI_RPR; /**< \brief (Hsmci Offset: 0x100) Receive Pointer Register */ __IO uint32_t HSMCI_RCR; /**< \brief (Hsmci Offset: 0x104) Receive Counter Register */ __IO uint32_t HSMCI_TPR; /**< \brief (Hsmci Offset: 0x108) Transmit Pointer Register */ __IO uint32_t HSMCI_TCR; /**< \brief (Hsmci Offset: 0x10C) Transmit Counter Register */ __IO uint32_t HSMCI_RNPR; /**< \brief (Hsmci Offset: 0x110) Receive Next Pointer Register */ __IO uint32_t HSMCI_RNCR; /**< \brief (Hsmci Offset: 0x114) Receive Next Counter Register */ __IO uint32_t HSMCI_TNPR; /**< \brief (Hsmci Offset: 0x118) Transmit Next Pointer Register */ __IO uint32_t HSMCI_TNCR; /**< \brief (Hsmci Offset: 0x11C) Transmit Next Counter Register */ __O uint32_t HSMCI_PTCR; /**< \brief (Hsmci Offset: 0x120) Transfer Control Register */ __I uint32_t HSMCI_PTSR; /**< \brief (Hsmci Offset: 0x124) Transfer Status Register */ __I uint32_t Reserved5[54]; __IO uint32_t HSMCI_FIFO[256]; /**< \brief (Hsmci Offset: 0x200) FIFO Memory Aperture0 */ } Hsmci; #endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ #define HSMCI_CR_MCIEN (0x1u << 0) /**< \brief (HSMCI_CR) Multi-Media Interface Enable */ #define HSMCI_CR_MCIDIS (0x1u << 1) /**< \brief (HSMCI_CR) Multi-Media Interface Disable */ #define HSMCI_CR_PWSEN (0x1u << 2) /**< \brief (HSMCI_CR) Power Save Mode Enable */ #define HSMCI_CR_PWSDIS (0x1u << 3) /**< \brief (HSMCI_CR) Power Save Mode Disable */ #define HSMCI_CR_SWRST (0x1u << 7) /**< \brief (HSMCI_CR) Software Reset */ #define HSMCI_MR_CLKDIV_Pos 0 #define HSMCI_MR_CLKDIV_Msk (0xffu << HSMCI_MR_CLKDIV_Pos) /**< \brief (HSMCI_MR) Clock Divider */ #define HSMCI_MR_CLKDIV(value) ((HSMCI_MR_CLKDIV_Msk & ((value) << HSMCI_MR_CLKDIV_Pos))) #define HSMCI_MR_PWSDIV_Pos 8 #define HSMCI_MR_PWSDIV_Msk (0x7u << HSMCI_MR_PWSDIV_Pos) /**< \brief (HSMCI_MR) Power Saving Divider */ #define HSMCI_MR_PWSDIV(value) ((HSMCI_MR_PWSDIV_Msk & ((value) << HSMCI_MR_PWSDIV_Pos))) #define HSMCI_MR_RDPROOF (0x1u << 11) /**< \brief (HSMCI_MR) Read Proof Enable */ #define HSMCI_MR_WRPROOF (0x1u << 12) /**< \brief (HSMCI_MR) Write Proof Enable */ #define HSMCI_MR_FBYTE (0x1u << 13) /**< \brief (HSMCI_MR) Force Byte Transfer */ #define HSMCI_MR_PADV (0x1u << 14) /**< \brief (HSMCI_MR) Padding Value */ #define HSMCI_MR_PDCMODE (0x1u << 15) /**< \brief (HSMCI_MR) PDC-oriented Mode */ #define HSMCI_MR_CLKODD (0x1u << 16) /**< \brief (HSMCI_MR) Clock divider is odd */ #define <API key> 0 #define <API key> (0xfu << <API key>) /**< \brief (HSMCI_DTOR) Data Timeout Cycle Number */ #define HSMCI_DTOR_DTOCYC(value) ((<API key> & ((value) << <API key>))) #define <API key> 4 #define <API key> (0x7u << <API key>) /**< \brief (HSMCI_DTOR) Data Timeout Multiplier */ #define HSMCI_DTOR_DTOMUL_1 (0x0u << 4) /**< \brief (HSMCI_DTOR) DTOCYC */ #define <API key> (0x1u << 4) /**< \brief (HSMCI_DTOR) DTOCYC x 16 */ #define <API key> (0x2u << 4) /**< \brief (HSMCI_DTOR) DTOCYC x 128 */ #define <API key> (0x3u << 4) /**< \brief (HSMCI_DTOR) DTOCYC x 256 */ #define <API key> (0x4u << 4) /**< \brief (HSMCI_DTOR) DTOCYC x 1024 */ #define <API key> (0x5u << 4) /**< \brief (HSMCI_DTOR) DTOCYC x 4096 */ #define <API key> (0x6u << 4) /**< \brief (HSMCI_DTOR) DTOCYC x 65536 */ #define <API key> (0x7u << 4) /**< \brief (HSMCI_DTOR) DTOCYC x 1048576 */ #define <API key> 0 #define <API key> (0x3u << <API key>) /**< \brief (HSMCI_SDCR) SDCard/SDIO Slot */ #define <API key> (0x0u << 0) /**< \brief (HSMCI_SDCR) Slot A is selected. */ #define <API key> (0x1u << 0) /**< \brief (HSMCI_SDCR) - */ #define <API key> (0x2u << 0) /**< \brief (HSMCI_SDCR) - */ #define <API key> (0x3u << 0) /**< \brief (HSMCI_SDCR) - */ #define <API key> 6 #define <API key> (0x3u << <API key>) /**< \brief (HSMCI_SDCR) SDCard/SDIO Bus Width */ #define HSMCI_SDCR_SDCBUS_1 (0x0u << 6) /**< \brief (HSMCI_SDCR) 1 bit */ #define HSMCI_SDCR_SDCBUS_4 (0x2u << 6) /**< \brief (HSMCI_SDCR) 4 bits */ #define HSMCI_SDCR_SDCBUS_8 (0x3u << 6) /**< \brief (HSMCI_SDCR) 8 bits */ #define HSMCI_ARGR_ARG_Pos 0 #define HSMCI_ARGR_ARG_Msk (0xffffffffu << HSMCI_ARGR_ARG_Pos) /**< \brief (HSMCI_ARGR) Command Argument */ #define HSMCI_ARGR_ARG(value) ((HSMCI_ARGR_ARG_Msk & ((value) << HSMCI_ARGR_ARG_Pos))) #define <API key> 0 #define <API key> (0x3fu << <API key>) /**< \brief (HSMCI_CMDR) Command Number */ #define HSMCI_CMDR_CMDNB(value) ((<API key> & ((value) << <API key>))) #define <API key> 6 #define <API key> (0x3u << <API key>) /**< \brief (HSMCI_CMDR) Response Type */ #define <API key> (0x0u << 6) /**< \brief (HSMCI_CMDR) No response */ #define <API key> (0x1u << 6) /**< \brief (HSMCI_CMDR) 48-bit response */ #define <API key> (0x2u << 6) /**< \brief (HSMCI_CMDR) 136-bit response */ #define <API key> (0x3u << 6) /**< \brief (HSMCI_CMDR) R1b response type */ #define <API key> 8 #define <API key> (0x7u << <API key>) /**< \brief (HSMCI_CMDR) Special Command */ #define <API key> (0x0u << 8) /**< \brief (HSMCI_CMDR) Not a special CMD. */ #define <API key> (0x1u << 8) /**< \brief (HSMCI_CMDR) Initialization CMD: 74 clock cycles for initialization sequence. */ #define <API key> (0x2u << 8) /**< \brief (HSMCI_CMDR) Synchronized CMD: Wait for the end of the current data block transfer before sending the pending command. */ #define <API key> (0x3u << 8) /**< \brief (HSMCI_CMDR) CE-ATA Completion Signal disable Command. The host cancels the ability for the device to return a command completion signal on the command line. */ #define <API key> (0x4u << 8) /**< \brief (HSMCI_CMDR) Interrupt command: Corresponds to the Interrupt Mode (CMD40). */ #define <API key> (0x5u << 8) /**< \brief (HSMCI_CMDR) Interrupt response: Corresponds to the Interrupt Mode (CMD40). */ #define <API key> (0x6u << 8) /**< \brief (HSMCI_CMDR) Boot Operation Request. Start a boot operation mode, the host processor can read boot data from the MMC device directly. */ #define <API key> (0x7u << 8) /**< \brief (HSMCI_CMDR) End Boot Operation. This command allows the host processor to terminate the boot operation mode. */ #define HSMCI_CMDR_OPDCMD (0x1u << 11) /**< \brief (HSMCI_CMDR) Open Drain Command */ #define <API key> (0x0u << 11) /**< \brief (HSMCI_CMDR) Push pull command. */ #define <API key> (0x1u << 11) /**< \brief (HSMCI_CMDR) Open drain command. */ #define HSMCI_CMDR_MAXLAT (0x1u << 12) /**< \brief (HSMCI_CMDR) Max Latency for Command to Response */ #define HSMCI_CMDR_MAXLAT_5 (0x0u << 12) /**< \brief (HSMCI_CMDR) 5-cycle max latency. */ #define <API key> (0x1u << 12) /**< \brief (HSMCI_CMDR) 64-cycle max latency. */ #define <API key> 16 #define <API key> (0x3u << <API key>) /**< \brief (HSMCI_CMDR) Transfer Command */ #define <API key> (0x0u << 16) /**< \brief (HSMCI_CMDR) No data transfer */ #define <API key> (0x1u << 16) /**< \brief (HSMCI_CMDR) Start data transfer */ #define <API key> (0x2u << 16) /**< \brief (HSMCI_CMDR) Stop data transfer */ #define HSMCI_CMDR_TRDIR (0x1u << 18) /**< \brief (HSMCI_CMDR) Transfer Direction */ #define <API key> (0x0u << 18) /**< \brief (HSMCI_CMDR) Write. */ #define <API key> (0x1u << 18) /**< \brief (HSMCI_CMDR) Read. */ #define <API key> 19 #define <API key> (0x7u << <API key>) /**< \brief (HSMCI_CMDR) Transfer Type */ #define <API key> (0x0u << 19) /**< \brief (HSMCI_CMDR) MMC/SD Card Single Block */ #define <API key> (0x1u << 19) /**< \brief (HSMCI_CMDR) MMC/SD Card Multiple Block */ #define <API key> (0x2u << 19) /**< \brief (HSMCI_CMDR) MMC Stream */ #define <API key> (0x4u << 19) /**< \brief (HSMCI_CMDR) SDIO Byte */ #define <API key> (0x5u << 19) /**< \brief (HSMCI_CMDR) SDIO Block */ #define <API key> 24 #define <API key> (0x3u << <API key>) /**< \brief (HSMCI_CMDR) SDIO Special Command */ #define <API key> (0x0u << 24) /**< \brief (HSMCI_CMDR) Not an SDIO Special Command */ #define <API key> (0x1u << 24) /**< \brief (HSMCI_CMDR) SDIO Suspend Command */ #define <API key> (0x2u << 24) /**< \brief (HSMCI_CMDR) SDIO Resume Command */ #define HSMCI_CMDR_ATACS (0x1u << 26) /**< \brief (HSMCI_CMDR) ATA with Command Completion Signal */ #define <API key> (0x0u << 26) /**< \brief (HSMCI_CMDR) Normal operation mode. */ #define <API key> (0x1u << 26) /**< \brief (HSMCI_CMDR) This bit indicates that a completion signal is expected within a programmed amount of time (HSMCI_CSTOR). */ #define HSMCI_CMDR_BOOT_ACK (0x1u << 27) /**< \brief (HSMCI_CMDR) Boot Operation Acknowledge */ #define HSMCI_BLKR_BCNT_Pos 0 #define HSMCI_BLKR_BCNT_Msk (0xffffu << HSMCI_BLKR_BCNT_Pos) /**< \brief (HSMCI_BLKR) MMC/SDIO Block Count - SDIO Byte Count */ #define HSMCI_BLKR_BCNT(value) ((HSMCI_BLKR_BCNT_Msk & ((value) << HSMCI_BLKR_BCNT_Pos))) #define <API key> 16 #define <API key> (0xffffu << <API key>) /**< \brief (HSMCI_BLKR) Data Block Length */ #define HSMCI_BLKR_BLKLEN(value) ((<API key> & ((value) << <API key>))) #define <API key> 0 #define <API key> (0xfu << <API key>) /**< \brief (HSMCI_CSTOR) Completion Signal Timeout Cycle Number */ #define HSMCI_CSTOR_CSTOCYC(value) ((<API key> & ((value) << <API key>))) #define <API key> 4 #define <API key> (0x7u << <API key>) /**< \brief (HSMCI_CSTOR) Completion Signal Timeout Multiplier */ #define <API key> (0x0u << 4) /**< \brief (HSMCI_CSTOR) CSTOCYC x 1 */ #define <API key> (0x1u << 4) /**< \brief (HSMCI_CSTOR) CSTOCYC x 16 */ #define <API key> (0x2u << 4) /**< \brief (HSMCI_CSTOR) CSTOCYC x 128 */ #define <API key> (0x3u << 4) /**< \brief (HSMCI_CSTOR) CSTOCYC x 256 */ #define <API key> (0x4u << 4) /**< \brief (HSMCI_CSTOR) CSTOCYC x 1024 */ #define <API key> (0x5u << 4) /**< \brief (HSMCI_CSTOR) CSTOCYC x 4096 */ #define <API key> (0x6u << 4) /**< \brief (HSMCI_CSTOR) CSTOCYC x 65536 */ #define <API key> (0x7u << 4) /**< \brief (HSMCI_CSTOR) CSTOCYC x 1048576 */ #define HSMCI_RSPR_RSP_Pos 0 #define HSMCI_RSPR_RSP_Msk (0xffffffffu << HSMCI_RSPR_RSP_Pos) /**< \brief (HSMCI_RSPR[4]) Response */ #define HSMCI_RDR_DATA_Pos 0 #define HSMCI_RDR_DATA_Msk (0xffffffffu << HSMCI_RDR_DATA_Pos) /**< \brief (HSMCI_RDR) Data to Read */ #define HSMCI_TDR_DATA_Pos 0 #define HSMCI_TDR_DATA_Msk (0xffffffffu << HSMCI_TDR_DATA_Pos) /**< \brief (HSMCI_TDR) Data to Write */ #define HSMCI_TDR_DATA(value) ((HSMCI_TDR_DATA_Msk & ((value) << HSMCI_TDR_DATA_Pos))) #define HSMCI_SR_CMDRDY (0x1u << 0) /**< \brief (HSMCI_SR) Command Ready */ #define HSMCI_SR_RXRDY (0x1u << 1) /**< \brief (HSMCI_SR) Receiver Ready */ #define HSMCI_SR_TXRDY (0x1u << 2) /**< \brief (HSMCI_SR) Transmit Ready */ #define HSMCI_SR_BLKE (0x1u << 3) /**< \brief (HSMCI_SR) Data Block Ended */ #define HSMCI_SR_DTIP (0x1u << 4) /**< \brief (HSMCI_SR) Data Transfer in Progress */ #define HSMCI_SR_NOTBUSY (0x1u << 5) /**< \brief (HSMCI_SR) HSMCI Not Busy */ #define HSMCI_SR_ENDRX (0x1u << 6) /**< \brief (HSMCI_SR) End of RX Buffer */ #define HSMCI_SR_ENDTX (0x1u << 7) /**< \brief (HSMCI_SR) End of TX Buffer */ #define HSMCI_SR_SDIOIRQA (0x1u << 8) /**< \brief (HSMCI_SR) SDIO Interrupt for Slot A */ #define HSMCI_SR_SDIOWAIT (0x1u << 12) /**< \brief (HSMCI_SR) SDIO Read Wait Operation Status */ #define HSMCI_SR_CSRCV (0x1u << 13) /**< \brief (HSMCI_SR) CE-ATA Completion Signal Received */ #define HSMCI_SR_RXBUFF (0x1u << 14) /**< \brief (HSMCI_SR) RX Buffer Full */ #define HSMCI_SR_TXBUFE (0x1u << 15) /**< \brief (HSMCI_SR) TX Buffer Empty */ #define HSMCI_SR_RINDE (0x1u << 16) /**< \brief (HSMCI_SR) Response Index Error */ #define HSMCI_SR_RDIRE (0x1u << 17) /**< \brief (HSMCI_SR) Response Direction Error */ #define HSMCI_SR_RCRCE (0x1u << 18) /**< \brief (HSMCI_SR) Response CRC Error */ #define HSMCI_SR_RENDE (0x1u << 19) /**< \brief (HSMCI_SR) Response End Bit Error */ #define HSMCI_SR_RTOE (0x1u << 20) /**< \brief (HSMCI_SR) Response Time-out Error */ #define HSMCI_SR_DCRCE (0x1u << 21) /**< \brief (HSMCI_SR) Data CRC Error */ #define HSMCI_SR_DTOE (0x1u << 22) /**< \brief (HSMCI_SR) Data Time-out Error */ #define HSMCI_SR_CSTOE (0x1u << 23) /**< \brief (HSMCI_SR) Completion Signal Time-out Error */ #define HSMCI_SR_FIFOEMPTY (0x1u << 26) /**< \brief (HSMCI_SR) FIFO empty flag */ #define HSMCI_SR_XFRDONE (0x1u << 27) /**< \brief (HSMCI_SR) Transfer Done flag */ #define HSMCI_SR_ACKRCV (0x1u << 28) /**< \brief (HSMCI_SR) Boot Operation Acknowledge Received */ #define HSMCI_SR_ACKRCVE (0x1u << 29) /**< \brief (HSMCI_SR) Boot Operation Acknowledge Error */ #define HSMCI_SR_OVRE (0x1u << 30) /**< \brief (HSMCI_SR) Overrun */ #define HSMCI_SR_UNRE (0x1u << 31) /**< \brief (HSMCI_SR) Underrun */ #define HSMCI_IER_CMDRDY (0x1u << 0) /**< \brief (HSMCI_IER) Command Ready Interrupt Enable */ #define HSMCI_IER_RXRDY (0x1u << 1) /**< \brief (HSMCI_IER) Receiver Ready Interrupt Enable */ #define HSMCI_IER_TXRDY (0x1u << 2) /**< \brief (HSMCI_IER) Transmit Ready Interrupt Enable */ #define HSMCI_IER_BLKE (0x1u << 3) /**< \brief (HSMCI_IER) Data Block Ended Interrupt Enable */ #define HSMCI_IER_DTIP (0x1u << 4) /**< \brief (HSMCI_IER) Data Transfer in Progress Interrupt Enable */ #define HSMCI_IER_NOTBUSY (0x1u << 5) /**< \brief (HSMCI_IER) Data Not Busy Interrupt Enable */ #define HSMCI_IER_ENDRX (0x1u << 6) /**< \brief (HSMCI_IER) End of Receive Buffer Interrupt Enable */ #define HSMCI_IER_ENDTX (0x1u << 7) /**< \brief (HSMCI_IER) End of Transmit Buffer Interrupt Enable */ #define HSMCI_IER_SDIOIRQA (0x1u << 8) /**< \brief (HSMCI_IER) SDIO Interrupt for Slot A Interrupt Enable */ #define HSMCI_IER_SDIOWAIT (0x1u << 12) /**< \brief (HSMCI_IER) SDIO Read Wait Operation Status Interrupt Enable */ #define HSMCI_IER_CSRCV (0x1u << 13) /**< \brief (HSMCI_IER) Completion Signal Received Interrupt Enable */ #define HSMCI_IER_RXBUFF (0x1u << 14) /**< \brief (HSMCI_IER) Receive Buffer Full Interrupt Enable */ #define HSMCI_IER_TXBUFE (0x1u << 15) /**< \brief (HSMCI_IER) Transmit Buffer Empty Interrupt Enable */ #define HSMCI_IER_RINDE (0x1u << 16) /**< \brief (HSMCI_IER) Response Index Error Interrupt Enable */ #define HSMCI_IER_RDIRE (0x1u << 17) /**< \brief (HSMCI_IER) Response Direction Error Interrupt Enable */ #define HSMCI_IER_RCRCE (0x1u << 18) /**< \brief (HSMCI_IER) Response CRC Error Interrupt Enable */ #define HSMCI_IER_RENDE (0x1u << 19) /**< \brief (HSMCI_IER) Response End Bit Error Interrupt Enable */ #define HSMCI_IER_RTOE (0x1u << 20) /**< \brief (HSMCI_IER) Response Time-out Error Interrupt Enable */ #define HSMCI_IER_DCRCE (0x1u << 21) /**< \brief (HSMCI_IER) Data CRC Error Interrupt Enable */ #define HSMCI_IER_DTOE (0x1u << 22) /**< \brief (HSMCI_IER) Data Time-out Error Interrupt Enable */ #define HSMCI_IER_CSTOE (0x1u << 23) /**< \brief (HSMCI_IER) Completion Signal Timeout Error Interrupt Enable */ #define HSMCI_IER_FIFOEMPTY (0x1u << 26) /**< \brief (HSMCI_IER) FIFO empty Interrupt enable */ #define HSMCI_IER_XFRDONE (0x1u << 27) /**< \brief (HSMCI_IER) Transfer Done Interrupt enable */ #define HSMCI_IER_ACKRCV (0x1u << 28) /**< \brief (HSMCI_IER) Boot Acknowledge Interrupt Enable */ #define HSMCI_IER_ACKRCVE (0x1u << 29) /**< \brief (HSMCI_IER) Boot Acknowledge Error Interrupt Enable */ #define HSMCI_IER_OVRE (0x1u << 30) /**< \brief (HSMCI_IER) Overrun Interrupt Enable */ #define HSMCI_IER_UNRE (0x1u << 31) /**< \brief (HSMCI_IER) Underrun Interrupt Enable */ #define HSMCI_IDR_CMDRDY (0x1u << 0) /**< \brief (HSMCI_IDR) Command Ready Interrupt Disable */ #define HSMCI_IDR_RXRDY (0x1u << 1) /**< \brief (HSMCI_IDR) Receiver Ready Interrupt Disable */ #define HSMCI_IDR_TXRDY (0x1u << 2) /**< \brief (HSMCI_IDR) Transmit Ready Interrupt Disable */ #define HSMCI_IDR_BLKE (0x1u << 3) /**< \brief (HSMCI_IDR) Data Block Ended Interrupt Disable */ #define HSMCI_IDR_DTIP (0x1u << 4) /**< \brief (HSMCI_IDR) Data Transfer in Progress Interrupt Disable */ #define HSMCI_IDR_NOTBUSY (0x1u << 5) /**< \brief (HSMCI_IDR) Data Not Busy Interrupt Disable */ #define HSMCI_IDR_ENDRX (0x1u << 6) /**< \brief (HSMCI_IDR) End of Receive Buffer Interrupt Disable */ #define HSMCI_IDR_ENDTX (0x1u << 7) /**< \brief (HSMCI_IDR) End of Transmit Buffer Interrupt Disable */ #define HSMCI_IDR_SDIOIRQA (0x1u << 8) /**< \brief (HSMCI_IDR) SDIO Interrupt for Slot A Interrupt Disable */ #define HSMCI_IDR_SDIOWAIT (0x1u << 12) /**< \brief (HSMCI_IDR) SDIO Read Wait Operation Status Interrupt Disable */ #define HSMCI_IDR_CSRCV (0x1u << 13) /**< \brief (HSMCI_IDR) Completion Signal received interrupt Disable */ #define HSMCI_IDR_RXBUFF (0x1u << 14) /**< \brief (HSMCI_IDR) Receive Buffer Full Interrupt Disable */ #define HSMCI_IDR_TXBUFE (0x1u << 15) /**< \brief (HSMCI_IDR) Transmit Buffer Empty Interrupt Disable */ #define HSMCI_IDR_RINDE (0x1u << 16) /**< \brief (HSMCI_IDR) Response Index Error Interrupt Disable */ #define HSMCI_IDR_RDIRE (0x1u << 17) /**< \brief (HSMCI_IDR) Response Direction Error Interrupt Disable */ #define HSMCI_IDR_RCRCE (0x1u << 18) /**< \brief (HSMCI_IDR) Response CRC Error Interrupt Disable */ #define HSMCI_IDR_RENDE (0x1u << 19) /**< \brief (HSMCI_IDR) Response End Bit Error Interrupt Disable */ #define HSMCI_IDR_RTOE (0x1u << 20) /**< \brief (HSMCI_IDR) Response Time-out Error Interrupt Disable */ #define HSMCI_IDR_DCRCE (0x1u << 21) /**< \brief (HSMCI_IDR) Data CRC Error Interrupt Disable */ #define HSMCI_IDR_DTOE (0x1u << 22) /**< \brief (HSMCI_IDR) Data Time-out Error Interrupt Disable */ #define HSMCI_IDR_CSTOE (0x1u << 23) /**< \brief (HSMCI_IDR) Completion Signal Time out Error Interrupt Disable */ #define HSMCI_IDR_FIFOEMPTY (0x1u << 26) /**< \brief (HSMCI_IDR) FIFO empty Interrupt Disable */ #define HSMCI_IDR_XFRDONE (0x1u << 27) /**< \brief (HSMCI_IDR) Transfer Done Interrupt Disable */ #define HSMCI_IDR_ACKRCV (0x1u << 28) /**< \brief (HSMCI_IDR) Boot Acknowledge Interrupt Disable */ #define HSMCI_IDR_ACKRCVE (0x1u << 29) /**< \brief (HSMCI_IDR) Boot Acknowledge Error Interrupt Disable */ #define HSMCI_IDR_OVRE (0x1u << 30) /**< \brief (HSMCI_IDR) Overrun Interrupt Disable */ #define HSMCI_IDR_UNRE (0x1u << 31) /**< \brief (HSMCI_IDR) Underrun Interrupt Disable */ #define HSMCI_IMR_CMDRDY (0x1u << 0) /**< \brief (HSMCI_IMR) Command Ready Interrupt Mask */ #define HSMCI_IMR_RXRDY (0x1u << 1) /**< \brief (HSMCI_IMR) Receiver Ready Interrupt Mask */ #define HSMCI_IMR_TXRDY (0x1u << 2) /**< \brief (HSMCI_IMR) Transmit Ready Interrupt Mask */ #define HSMCI_IMR_BLKE (0x1u << 3) /**< \brief (HSMCI_IMR) Data Block Ended Interrupt Mask */ #define HSMCI_IMR_DTIP (0x1u << 4) /**< \brief (HSMCI_IMR) Data Transfer in Progress Interrupt Mask */ #define HSMCI_IMR_NOTBUSY (0x1u << 5) /**< \brief (HSMCI_IMR) Data Not Busy Interrupt Mask */ #define HSMCI_IMR_ENDRX (0x1u << 6) /**< \brief (HSMCI_IMR) End of Receive Buffer Interrupt Mask */ #define HSMCI_IMR_ENDTX (0x1u << 7) /**< \brief (HSMCI_IMR) End of Transmit Buffer Interrupt Mask */ #define HSMCI_IMR_SDIOIRQA (0x1u << 8) /**< \brief (HSMCI_IMR) SDIO Interrupt for Slot A Interrupt Mask */ #define HSMCI_IMR_SDIOWAIT (0x1u << 12) /**< \brief (HSMCI_IMR) SDIO Read Wait Operation Status Interrupt Mask */ #define HSMCI_IMR_CSRCV (0x1u << 13) /**< \brief (HSMCI_IMR) Completion Signal Received Interrupt Mask */ #define HSMCI_IMR_RXBUFF (0x1u << 14) /**< \brief (HSMCI_IMR) Receive Buffer Full Interrupt Mask */ #define HSMCI_IMR_TXBUFE (0x1u << 15) /**< \brief (HSMCI_IMR) Transmit Buffer Empty Interrupt Mask */ #define HSMCI_IMR_RINDE (0x1u << 16) /**< \brief (HSMCI_IMR) Response Index Error Interrupt Mask */ #define HSMCI_IMR_RDIRE (0x1u << 17) /**< \brief (HSMCI_IMR) Response Direction Error Interrupt Mask */ #define HSMCI_IMR_RCRCE (0x1u << 18) /**< \brief (HSMCI_IMR) Response CRC Error Interrupt Mask */ #define HSMCI_IMR_RENDE (0x1u << 19) /**< \brief (HSMCI_IMR) Response End Bit Error Interrupt Mask */ #define HSMCI_IMR_RTOE (0x1u << 20) /**< \brief (HSMCI_IMR) Response Time-out Error Interrupt Mask */ #define HSMCI_IMR_DCRCE (0x1u << 21) /**< \brief (HSMCI_IMR) Data CRC Error Interrupt Mask */ #define HSMCI_IMR_DTOE (0x1u << 22) /**< \brief (HSMCI_IMR) Data Time-out Error Interrupt Mask */ #define HSMCI_IMR_CSTOE (0x1u << 23) /**< \brief (HSMCI_IMR) Completion Signal Time-out Error Interrupt Mask */ #define HSMCI_IMR_FIFOEMPTY (0x1u << 26) /**< \brief (HSMCI_IMR) FIFO Empty Interrupt Mask */ #define HSMCI_IMR_XFRDONE (0x1u << 27) /**< \brief (HSMCI_IMR) Transfer Done Interrupt Mask */ #define HSMCI_IMR_ACKRCV (0x1u << 28) /**< \brief (HSMCI_IMR) Boot Operation Acknowledge Received Interrupt Mask */ #define HSMCI_IMR_ACKRCVE (0x1u << 29) /**< \brief (HSMCI_IMR) Boot Operation Acknowledge Error Interrupt Mask */ #define HSMCI_IMR_OVRE (0x1u << 30) /**< \brief (HSMCI_IMR) Overrun Interrupt Mask */ #define HSMCI_IMR_UNRE (0x1u << 31) /**< \brief (HSMCI_IMR) Underrun Interrupt Mask */ #define HSMCI_CFG_FIFOMODE (0x1u << 0) /**< \brief (HSMCI_CFG) HSMCI Internal FIFO control mode */ #define HSMCI_CFG_FERRCTRL (0x1u << 4) /**< \brief (HSMCI_CFG) Flow Error flag reset control mode */ #define HSMCI_CFG_HSMODE (0x1u << 8) /**< \brief (HSMCI_CFG) High Speed Mode */ #define HSMCI_CFG_LSYNC (0x1u << 12) /**< \brief (HSMCI_CFG) Synchronize on the last block */ #define HSMCI_WPMR_WPEN (0x1u << 0) /**< \brief (HSMCI_WPMR) Write Protect Enable */ #define <API key> 8 #define <API key> (0xffffffu << <API key>) /**< \brief (HSMCI_WPMR) Write Protect Key */ #define <API key> (0x4D4349u << 8) /**< \brief (HSMCI_WPMR) Writing any other value in this field aborts the write operation of the WPEN bit.Always reads as 0. */ #define HSMCI_WPSR_WPVS (0x1u << 0) /**< \brief (HSMCI_WPSR) Write Protection Violation Status */ #define <API key> 8 #define <API key> (0xffffu << <API key>) /**< \brief (HSMCI_WPSR) Write Protection Violation Source */ #define HSMCI_RPR_RXPTR_Pos 0 #define HSMCI_RPR_RXPTR_Msk (0xffffffffu << HSMCI_RPR_RXPTR_Pos) /**< \brief (HSMCI_RPR) Receive Pointer Register */ #define HSMCI_RPR_RXPTR(value) ((HSMCI_RPR_RXPTR_Msk & ((value) << HSMCI_RPR_RXPTR_Pos))) #define HSMCI_RCR_RXCTR_Pos 0 #define HSMCI_RCR_RXCTR_Msk (0xffffu << HSMCI_RCR_RXCTR_Pos) /**< \brief (HSMCI_RCR) Receive Counter Register */ #define HSMCI_RCR_RXCTR(value) ((HSMCI_RCR_RXCTR_Msk & ((value) << HSMCI_RCR_RXCTR_Pos))) #define HSMCI_TPR_TXPTR_Pos 0 #define HSMCI_TPR_TXPTR_Msk (0xffffffffu << HSMCI_TPR_TXPTR_Pos) /**< \brief (HSMCI_TPR) Transmit Counter Register */ #define HSMCI_TPR_TXPTR(value) ((HSMCI_TPR_TXPTR_Msk & ((value) << HSMCI_TPR_TXPTR_Pos))) #define HSMCI_TCR_TXCTR_Pos 0 #define HSMCI_TCR_TXCTR_Msk (0xffffu << HSMCI_TCR_TXCTR_Pos) /**< \brief (HSMCI_TCR) Transmit Counter Register */ #define HSMCI_TCR_TXCTR(value) ((HSMCI_TCR_TXCTR_Msk & ((value) << HSMCI_TCR_TXCTR_Pos))) #define <API key> 0 #define <API key> (0xffffffffu << <API key>) /**< \brief (HSMCI_RNPR) Receive Next Pointer */ #define HSMCI_RNPR_RXNPTR(value) ((<API key> & ((value) << <API key>))) #define <API key> 0 #define <API key> (0xffffu << <API key>) /**< \brief (HSMCI_RNCR) Receive Next Counter */ #define HSMCI_RNCR_RXNCTR(value) ((<API key> & ((value) << <API key>))) #define <API key> 0 #define <API key> (0xffffffffu << <API key>) /**< \brief (HSMCI_TNPR) Transmit Next Pointer */ #define HSMCI_TNPR_TXNPTR(value) ((<API key> & ((value) << <API key>))) #define <API key> 0 #define <API key> (0xffffu << <API key>) /**< \brief (HSMCI_TNCR) Transmit Counter Next */ #define HSMCI_TNCR_TXNCTR(value) ((<API key> & ((value) << <API key>))) #define HSMCI_PTCR_RXTEN (0x1u << 0) /**< \brief (HSMCI_PTCR) Receiver Transfer Enable */ #define HSMCI_PTCR_RXTDIS (0x1u << 1) /**< \brief (HSMCI_PTCR) Receiver Transfer Disable */ #define HSMCI_PTCR_TXTEN (0x1u << 8) /**< \brief (HSMCI_PTCR) Transmitter Transfer Enable */ #define HSMCI_PTCR_TXTDIS (0x1u << 9) /**< \brief (HSMCI_PTCR) Transmitter Transfer Disable */ #define HSMCI_PTSR_RXTEN (0x1u << 0) /**< \brief (HSMCI_PTSR) Receiver Transfer Enable */ #define HSMCI_PTSR_TXTEN (0x1u << 8) /**< \brief (HSMCI_PTSR) Transmitter Transfer Enable */ #endif /* <API key> */