diff --git a/doc/stdlib/arrays.rst b/doc/stdlib/arrays.rst index ead0d7d5ec3f1..ac37b479c02a8 100644 --- a/doc/stdlib/arrays.rst +++ b/doc/stdlib/arrays.rst @@ -9,46 +9,26 @@ Basic functions .. function:: ndims(A) -> Integer - :: - - ndims(A) -> Integer - Returns the number of dimensions of A -.. function:: size(A, [dim...]) +.. function:: size(A[, dim...]) - :: - - size(A[, dim...]) - Returns a tuple containing the dimensions of A. Optionally you can specify the dimension(s) you want the length of, and get the length of that dimension, or a tuple of the lengths of dimensions you asked for.: -.. function:: iseltype(A,T) +.. function:: iseltype(A, T) - :: - - iseltype(A, T) - Tests whether A or its elements are of type T -.. function:: length(A) -> Integer +.. function:: length(s) - :: - - length(s) - The number of characters in string ``s``. .. function:: eachindex(A...) - :: - - eachindex(A...) - Creates an iterable object for visiting each index of an AbstractArray ``A`` in an efficient manner. For array types that have opted into fast linear indexing (like ``Array``), this is simply the range ``1:length(A)``. For other array types, this returns a specialized Cartesian range to efficiently index into the array with indices specified for every dimension. Example for a sparse 2-d array: @@ -69,64 +49,36 @@ largest range along each dimension. .. function:: countnz(A) - :: - - countnz(A) - Counts the number of nonzero values in array A (dense or sparse). Note that this is not a constant-time operation. For sparse matrices, one should usually use ``nnz``, which returns the number of stored values. .. function:: conj!(A) - :: - - conj!(A) - Convert an array to its complex conjugate in-place .. function:: stride(A, k) - :: - - stride(A, k) - Returns the distance in memory (in number of elements) between adjacent elements in dimension k .. function:: strides(A) - :: - - strides(A) - Returns a tuple of the memory strides in each dimension -.. function:: ind2sub(dims, index) -> subscripts +.. function:: ind2sub(a, index) -> subscripts - :: - - ind2sub(a, index) -> subscripts - Returns a tuple of subscripts into array ``a`` corresponding to the linear index ``index`` .. function:: ind2sub(a, index) -> subscripts - :: - - ind2sub(a, index) -> subscripts - Returns a tuple of subscripts into array ``a`` corresponding to the linear index ``index`` .. function:: sub2ind(dims, i, j, k...) -> index - :: - - sub2ind(dims, i, j, k...) -> index - The inverse of ``ind2sub``, returns the linear index corresponding to the provided subscripts @@ -135,172 +87,96 @@ Constructors .. function:: Array(dims) - :: - - Array(dims) - element type ``T``. ``dims`` may be a tuple or a series of integer arguments. The syntax ``Array(T, dims)`` is also available, but deprecated. -.. function:: getindex(type[, elements...]) +.. function:: getindex(collection, key...) - :: - - getindex(collection, key...) - Retrieve the value(s) stored at the given key or index within a collection. The syntax ``a[i,j,...]`` is converted by the compiler to ``getindex(a, i, j, ...)``. .. function:: cell(dims) - :: - - cell(dims) - Construct an uninitialized cell array (heterogeneous array). -.. function:: zeros(type, dims) +.. function:: zeros(A) - :: - - zeros(A) - Create an array of all zeros with the same element type and shape as A. .. function:: zeros(A) - :: - - zeros(A) - Create an array of all zeros with the same element type and shape as A. -.. function:: ones(type, dims) +.. function:: ones(A) - :: - - ones(A) - Create an array of all ones with the same element type and shape as A. .. function:: ones(A) - :: - - ones(A) - Create an array of all ones with the same element type and shape as A. .. function:: trues(dims) - :: - - trues(dims) - Create a ``BitArray`` with all values set to true .. function:: falses(dims) - :: - - falses(dims) - Create a ``BitArray`` with all values set to false .. function:: fill(x, dims) - :: - - fill(x, dims) - Create an array filled with the value ``x``. For example, element initialized to 1.0. If ``x`` is an object reference, all elements will refer to the same object. ``fill(Foo(), dims)`` will return an array filled with the result of evaluating ``Foo()`` once. .. function:: fill!(A, x) - :: - - fill!(A, x) - Fill array ``A`` with the value ``x``. If ``x`` is an object reference, all elements will refer to the same object. ``fill!(A, Foo())`` will return ``A`` filled with the result of evaluating .. function:: reshape(A, dims) - :: - - reshape(A, dims) - Create an array with the same data as the given array, but with different dimensions. An implementation for a particular type of array may choose whether the data is copied or shared. .. function:: similar(array, element_type, dims) - :: - - similar(array, element_type, dims) - Create an uninitialized array of the same type as the given array, but with the specified element type and dimensions. The second and third arguments are both optional. The ``dims`` argument may be a tuple or a series of integer arguments. For some special ranges), this function returns a standard ``Array`` to allow operating on elements. .. function:: reinterpret(type, A) - :: - - reinterpret(type, A) - Change the type-interpretation of a block of memory. For example, corresponding to ``UInt32(7)`` as a ``Float32``. For arrays, this constructs an array with the same binary data as the given array, but with the specified element type. -.. function:: eye(n) +.. function:: eye(A) - :: - - eye(A) - Constructs an identity matrix of the same dimensions and type as -.. function:: eye(m, n) +.. function:: eye(A) - :: - - eye(A) - Constructs an identity matrix of the same dimensions and type as .. function:: eye(A) - :: - - eye(A) - Constructs an identity matrix of the same dimensions and type as .. function:: linspace(start, stop, n=100) - :: - - linspace(start, stop, n=100) - Construct a range of ``n`` linearly spaced elements from ``start`` to ``stop``. .. function:: logspace(start, stop, n=50) - :: - - logspace(start, stop, n=50) - Construct a vector of ``n`` logarithmically spaced numbers from @@ -311,859 +187,483 @@ All mathematical operations and functions are supported for arrays .. function:: broadcast(f, As...) - :: - - broadcast(f, As...) - Broadcasts the arrays ``As`` to a common size by expanding singleton dimensions, and returns an array of the results .. function:: broadcast!(f, dest, As...) - :: - - broadcast!(f, dest, As...) - Like ``broadcast``, but store the result of ``broadcast(f, As...)`` in the ``dest`` array. Note that ``dest`` is only used to store the result, and does not supply arguments to ``f`` unless it is also listed in the ``As``, as in ``broadcast!(f, A, A, B)`` to perform .. function:: bitbroadcast(f, As...) - :: - - bitbroadcast(f, As...) - Like ``broadcast``, but allocates a ``BitArray`` to store the result, rather then an ``Array``. .. function:: broadcast_function(f) - :: - - broadcast_function(f) - Returns a function ``broadcast_f`` such that useful in the form ``const broadcast_f = broadcast_function(f)``. .. function:: broadcast!_function(f) - :: - - broadcast!_function(f) - Like ``broadcast_function``, but for ``broadcast!``. Indexing, Assignment, and Concatenation --------------------------------------- -.. function:: getindex(A, inds...) +.. function:: getindex(collection, key...) - :: - - getindex(collection, key...) - Retrieve the value(s) stored at the given key or index within a collection. The syntax ``a[i,j,...]`` is converted by the compiler to ``getindex(a, i, j, ...)``. .. function:: sub(A, inds...) - :: - - sub(A, inds...) - Like ``getindex()``, but returns a view into the parent array ``A`` with the given indices instead of making a copy. Calling computes the indices to the parent array on the fly without checking bounds. .. function:: parent(A) - :: - - parent(A) - Returns the ``parent array`` of an array view type (e.g., SubArray), or the array itself if it is not a view .. function:: parentindexes(A) - :: - - parentindexes(A) - From an array view ``A``, returns the corresponding indexes in the parent .. function:: slicedim(A, d, i) - :: - - slicedim(A, d, i) - Return all the data of ``A`` where the index for dimension ``d`` equals ``i``. Equivalent to ``A[:,:,...,i,:,:,...]`` where ``i`` is in position ``d``. .. function:: slice(A, inds...) - :: - - slice(A, inds...) - Returns a view of array ``A`` with the given indices like -.. function:: setindex!(A, X, inds...) +.. function:: setindex!(collection, value, key...) - :: - - setindex!(collection, value, key...) - Store the given value at the given key or index within a collection. The syntax ``a[i,j,...] = x`` is converted by the compiler to ``setindex!(a, x, i, j, ...)``. .. function:: broadcast_getindex(A, inds...) - :: - - broadcast_getindex(A, inds...) - Broadcasts the ``inds`` arrays to a common size like ``broadcast``, and returns an array of the results ``A[ks...]``, where ``ks`` goes over the positions in the broadcast. .. function:: broadcast_setindex!(A, X, inds...) - :: - - broadcast_setindex!(A, X, inds...) - Broadcasts the ``X`` and ``inds`` arrays to a common size and stores the value from each position in ``X`` at the indices given by the same positions in ``inds``. .. function:: cat(dims, A...) - :: - - cat(dims, A...) - Concatenate the input arrays along the specified dimensions in the iterable ``dims``. For dimensions not in ``dims``, all input arrays should have the same size, which will also be the size of the output array along that dimension. For dimensions in ``dims``, the size of the output array is the sum of the sizes of the input arrays along that dimension. If ``dims`` is a single number, the different arrays are tightly stacked along that dimension. If to construct block diagonal matrices and their higher-dimensional analogues by simultaneously increasing several dimensions for every new input array and putting zero blocks elsewhere. For example, block matrix with *matrices[1]*, *matrices[2]*, ... as diagonal blocks and matching zero blocks away from the diagonal. .. function:: vcat(A...) - :: - - vcat(A...) - Concatenate along dimension 1 .. function:: hcat(A...) - :: - - hcat(A...) - Concatenate along dimension 2 .. function:: hvcat(rows::Tuple{Vararg{Int}}, values...) - :: - - hvcat(rows::Tuple{Vararg{Int}}, values...) - Horizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row. For example, If the first argument is a single integer ``n``, then all block rows are assumed to have ``n`` block columns. .. function:: flipdim(A, d) - :: - - flipdim(A, d) - Reverse ``A`` in dimension ``d``. -.. function:: circshift(A,shifts) +.. function:: circshift(A, shifts) - :: - - circshift(A, shifts) - Circularly shift the data in an array. The second argument is a vector giving the amount to shift in each dimension. -.. function:: find(A) +.. function:: find(f, A) - :: - - find(f, A) - Return a vector of the linear indexes of ``A`` where ``f`` returns true. -.. function:: find(f,A) +.. function:: find(f, A) - :: - - find(f, A) - Return a vector of the linear indexes of ``A`` where ``f`` returns true. .. function:: findn(A) - :: - - findn(A) - Return a vector of indexes for each dimension giving the locations of the non-zeros in ``A`` (determined by ``A[i]!=0``). .. function:: findnz(A) - :: - - findnz(A) - Return a tuple ``(I, J, V)`` where ``I`` and ``J`` are the row and column indexes of the non-zero values in matrix ``A``, and ``V`` is a vector of the non-zero values. -.. function:: findfirst(A) +.. function:: findfirst(predicate, A) - :: - - findfirst(predicate, A) - Return the index of the first element of ``A`` for which -.. function:: findfirst(A,v) +.. function:: findfirst(predicate, A) - :: - - findfirst(predicate, A) - Return the index of the first element of ``A`` for which .. function:: findfirst(predicate, A) - :: - - findfirst(predicate, A) - Return the index of the first element of ``A`` for which -.. function:: findlast(A) +.. function:: findlast(predicate, A) - :: - - findlast(predicate, A) - Return the index of the last element of ``A`` for which -.. function:: findlast(A, v) +.. function:: findlast(predicate, A) - :: - - findlast(predicate, A) - Return the index of the last element of ``A`` for which .. function:: findlast(predicate, A) - :: - - findlast(predicate, A) - Return the index of the last element of ``A`` for which -.. function:: findnext(A, i) +.. function:: findnext(A, v, i) - :: - - findnext(A, v, i) - Find the next index >= ``i`` of an element of ``A`` equal to ``v`` -.. function:: findnext(predicate, A, i) +.. function:: findnext(A, v, i) - :: - - findnext(A, v, i) - Find the next index >= ``i`` of an element of ``A`` equal to ``v`` .. function:: findnext(A, v, i) - :: - - findnext(A, v, i) - Find the next index >= ``i`` of an element of ``A`` equal to ``v`` -.. function:: findprev(A, i) +.. function:: findprev(A, v, i) - :: - - findprev(A, v, i) - Find the previous index <= ``i`` of an element of ``A`` equal to -.. function:: findprev(predicate, A, i) +.. function:: findprev(A, v, i) - :: - - findprev(A, v, i) - Find the previous index <= ``i`` of an element of ``A`` equal to .. function:: findprev(A, v, i) - :: - - findprev(A, v, i) - Find the previous index <= ``i`` of an element of ``A`` equal to .. function:: permutedims(A, perm) - :: - - permutedims(A, perm) - Permute the dimensions of array ``A``. ``perm`` is a vector specifying a permutation of length ``ndims(A)``. This is a generalization of transpose for multi-dimensional arrays. Transpose is equivalent to ``permutedims(A, [2,1])``. .. function:: ipermutedims(A, perm) - :: - - ipermutedims(A, perm) - Like ``permutedims()``, except the inverse of the given permutation is applied. .. function:: permutedims!(dest, src, perm) - :: - - permutedims!(dest, src, perm) - Permute the dimensions of array ``src`` and store the result in the array ``dest``. ``perm`` is a vector specifying a permutation of length ``ndims(src)``. The preallocated array ``dest`` should have in-place permutation is supported and unexpected results will happen if *src* and *dest* have overlapping memory regions. .. function:: squeeze(A, dims) - :: - - squeeze(A, dims) - Remove the dimensions specified by ``dims`` from array ``A``. Elements of ``dims`` must be unique and within the range .. function:: vec(Array) -> Vector - :: - - vec(Array) -> Vector - Vectorize an array using column-major convention. .. function:: promote_shape(s1, s2) - :: - - promote_shape(s1, s2) - Check two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions. .. function:: checkbounds(array, indexes...) - :: - - checkbounds(array, indexes...) - Throw an error if the specified indexes are not in bounds for the given array. .. function:: randsubseq(A, p) -> Vector - :: - - randsubseq(A, p) -> Vector - Return a vector consisting of a random subsequence of the given array ``A``, where each element of ``A`` is included (in order) with independent probability ``p``. (Complexity is linear in small and ``A`` is large.) Technically, this process is known as .. function:: randsubseq!(S, A, p) - :: - - randsubseq!(S, A, p) - Like ``randsubseq``, but the results are stored in ``S`` (which is resized as needed). Array functions --------------- -.. function:: cumprod(A, [dim]) +.. function:: cumprod(A[, dim]) - :: - - cumprod(A[, dim]) - Cumulative product along a dimension ``dim`` (defaults to 1). See also ``cumprod!()`` to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow). -.. function:: cumprod!(B, A, [dim]) +.. function:: cumprod!(B, A[, dim]) - :: - - cumprod!(B, A[, dim]) - Cumulative product of ``A`` along a dimension, storing the result in ``B``. The dimension defaults to 1. -.. function:: cumsum(A, [dim]) +.. function:: cumsum(A[, dim]) - :: - - cumsum(A[, dim]) - Cumulative sum along a dimension ``dim`` (defaults to 1). See also performance and to control the precision of the output (e.g. to avoid overflow). -.. function:: cumsum!(B, A, [dim]) +.. function:: cumsum!(B, A[, dim]) - :: - - cumsum!(B, A[, dim]) - Cumulative sum of ``A`` along a dimension, storing the result in -.. function:: cumsum_kbn(A, [dim]) +.. function:: cumsum_kbn(A[, dim]) - :: - - cumsum_kbn(A[, dim]) - Cumulative sum along a dimension, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy. The dimension defaults to 1. -.. function:: cummin(A, [dim]) +.. function:: cummin(A[, dim]) - :: - - cummin(A[, dim]) - Cumulative minimum along a dimension. The dimension defaults to 1. -.. function:: cummax(A, [dim]) +.. function:: cummax(A[, dim]) - :: - - cummax(A[, dim]) - Cumulative maximum along a dimension. The dimension defaults to 1. -.. function:: diff(A, [dim]) +.. function:: diff(A[, dim]) - :: - - diff(A[, dim]) - Finite difference operator of matrix or vector. -.. function:: gradient(F, [h]) +.. function:: gradient(F[, h]) - :: - - gradient(F[, h]) - Compute differences along vector ``F``, using ``h`` as the spacing between points. The default spacing is one. -.. function:: rot180(A) +.. function:: rot180(A, k) - :: - - rot180(A, k) - Rotate matrix ``A`` 180 degrees an integer ``k`` number of times. If ``k`` is even, this is equivalent to a ``copy``. .. function:: rot180(A, k) - :: - - rot180(A, k) - Rotate matrix ``A`` 180 degrees an integer ``k`` number of times. If ``k`` is even, this is equivalent to a ``copy``. -.. function:: rotl90(A) +.. function:: rotl90(A, k) - :: - - rotl90(A, k) - Rotate matrix ``A`` left 90 degrees an integer ``k`` number of times. If ``k`` is zero or a multiple of four, this is equivalent to a ``copy``. .. function:: rotl90(A, k) - :: - - rotl90(A, k) - Rotate matrix ``A`` left 90 degrees an integer ``k`` number of times. If ``k`` is zero or a multiple of four, this is equivalent to a ``copy``. -.. function:: rotr90(A) +.. function:: rotr90(A, k) - :: - - rotr90(A, k) - Rotate matrix ``A`` right 90 degrees an integer ``k`` number of times. If ``k`` is zero or a multiple of four, this is equivalent to a ``copy``. .. function:: rotr90(A, k) - :: - - rotr90(A, k) - Rotate matrix ``A`` right 90 degrees an integer ``k`` number of times. If ``k`` is zero or a multiple of four, this is equivalent to a ``copy``. .. function:: reducedim(f, A, dims[, initial]) - :: - - reducedim(f, A, dims[, initial]) - Reduce 2-argument function ``f`` along dimensions of ``A``. The associativity of the reduction is implementation-dependent; if you need a particular associativity, e.g. left-to-right, you should write your own loop. See documentation for ``reduce``. .. function:: mapreducedim(f, op, A, dims[, initial]) - :: - - mapreducedim(f, op, A, dims[, initial]) - Evaluates to the same as *reducedim(op, map(f, A), dims, f(initial))*, but is generally faster because the intermediate array is avoided. .. function:: mapslices(f, A, dims) - :: - - mapslices(f, A, dims) - Transform the given dimensions of array ``A`` using function ``f``. where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, if .. function:: sum_kbn(A) - :: - - sum_kbn(A) - Returns the sum of all array elements, using the Kahan-Babuska- Neumaier compensated summation algorithm for additional accuracy. .. function:: cartesianmap(f, dims) - :: - - cartesianmap(f, dims) - Given a ``dims`` tuple of integers ``(m, n, ...)``, call ``f`` on all combinations of integers in the ranges ``1:m``, ``1:n``, etc. Combinatorics ------------- -.. function:: nthperm(v, k) +.. function:: nthperm(p) - :: - - nthperm(p) - Return the ``k`` that generated permutation ``p``. Note that .. function:: nthperm(p) - :: - - nthperm(p) - Return the ``k`` that generated permutation ``p``. Note that .. function:: nthperm!(v, k) - :: - - nthperm!(v, k) - In-place version of ``nthperm()``. -.. function:: randperm([rng,] n) +.. function:: randperm([rng], n) - :: - - randperm([rng], n) - Construct a random permutation of length ``n``. The optional Numbers*. .. function:: invperm(v) - :: - - invperm(v) - Return the inverse permutation of v. .. function:: isperm(v) -> Bool - :: - - isperm(v) -> Bool - Returns true if v is a valid permutation. .. function:: permute!(v, p) - :: - - permute!(v, p) - Permute vector ``v`` in-place, according to permutation ``p``. No checking is done to verify that ``p`` is a permutation. To return a new permutation, use ``v[p]``. Note that this is generally faster than ``permute!(v,p)`` for large vectors. .. function:: ipermute!(v, p) - :: - - ipermute!(v, p) - Like permute!, but the inverse of the given permutation is applied. -.. function:: randcycle([rng,] n) +.. function:: randcycle([rng], n) - :: - - randcycle([rng], n) - Construct a random cyclic permutation of length ``n``. The optional Numbers*. -.. function:: shuffle([rng,] v) +.. function:: shuffle([rng], v) - :: - - shuffle([rng], v) - Return a randomly permuted copy of ``v``. The optional ``rng`` argument specifies a random number generator, see *Random Numbers*. -.. function:: shuffle!([rng,] v) +.. function:: shuffle!([rng], v) - :: - - shuffle!([rng], v) - In-place version of ``shuffle()``. -.. function:: reverse(v [, start=1 [, stop=length(v) ]] ) +.. function:: reverse(v[, start=1[, stop=length(v)]]) - :: - - reverse(v[, start=1[, stop=length(v)]]) - Return a copy of ``v`` reversed from start to stop. .. function:: reverseind(v, i) - :: - - reverseind(v, i) - Given an index ``i`` in ``reverse(v)``, return the corresponding index in ``v`` so that ``v[reverseind(v,i)] == reverse(v)[i]``. string.) -.. function:: reverse!(v [, start=1 [, stop=length(v) ]]) -> v +.. function:: reverse!(v[, start=1[, stop=length(v)]]) -> v - :: - - reverse!(v[, start=1[, stop=length(v)]]) -> v - In-place version of ``reverse()``. .. function:: combinations(array, n) - :: - - combinations(array, n) - Generate all combinations of ``n`` elements from an indexable object. Because the number of combinations can be very large, this function returns an iterator object. Use combinations. .. function:: permutations(array) - :: - - permutations(array) - Generate all permutations of an indexable object. Because the number of permutations can be very large, this function returns an iterator object. Use ``collect(permutations(array))`` to get an array of all permutations. -.. function:: partitions(n) +.. function:: partitions(array, m) - :: - - partitions(array, m) - Generate all set partitions of the elements of an array into exactly m subsets, represented as arrays of arrays. Because the number of partitions can be very large, this function returns an iterator object. Use ``collect(partitions(array,m))`` to get an array of all partitions. The number of partitions into m subsets is equal to the Stirling number of the second kind and can be efficiently computed using ``length(partitions(array,m))``. -.. function:: partitions(n, m) +.. function:: partitions(array, m) - :: - - partitions(array, m) - Generate all set partitions of the elements of an array into exactly m subsets, represented as arrays of arrays. Because the number of partitions can be very large, this function returns an iterator object. Use ``collect(partitions(array,m))`` to get an array of all partitions. The number of partitions into m subsets is equal to the Stirling number of the second kind and can be efficiently computed using ``length(partitions(array,m))``. -.. function:: partitions(array) +.. function:: partitions(array, m) - :: - - partitions(array, m) - Generate all set partitions of the elements of an array into exactly m subsets, represented as arrays of arrays. Because the number of partitions can be very large, this function returns an iterator object. Use ``collect(partitions(array,m))`` to get an array of all partitions. The number of partitions into m subsets is equal to the Stirling number of the second kind and can be efficiently computed using ``length(partitions(array,m))``. .. function:: partitions(array, m) - :: - - partitions(array, m) - Generate all set partitions of the elements of an array into exactly m subsets, represented as arrays of arrays. Because the number of partitions can be very large, this function returns an iterator object. Use ``collect(partitions(array,m))`` to get an array of all partitions. The number of partitions into m subsets is equal to the Stirling number of the second kind and can be efficiently computed using ``length(partitions(array,m))``. BitArrays --------- -.. function:: bitpack(A::AbstractArray{T,N}) -> BitArray +.. function:: bitpack(A::AbstractArray{T, N}) -> BitArray - :: - - bitpack(A::AbstractArray{T, N}) -> BitArray - Converts a numeric array to a packed boolean array .. function:: bitunpack(B::BitArray{N}) -> Array{Bool,N} - :: - - bitunpack(B::BitArray{N}) -> Array{Bool,N} - Converts a packed boolean array to an array of booleans .. function:: flipbits!(B::BitArray{N}) -> BitArray{N} - :: - - flipbits!(B::BitArray{N}) -> BitArray{N} - Performs a bitwise not operation on B. See *~ operator*. -.. function:: rol!(dest::BitArray{1}, src::BitArray{1}, i::Integer) -> BitArray{1} +.. function:: rol!(B::BitArray{1}, i::Integer) -> BitArray{1} - :: - - rol!(B::BitArray{1}, i::Integer) -> BitArray{1} - Performs a left rotation operation on B. .. function:: rol!(B::BitArray{1}, i::Integer) -> BitArray{1} - :: - - rol!(B::BitArray{1}, i::Integer) -> BitArray{1} - Performs a left rotation operation on B. .. function:: rol(B::BitArray{1}, i::Integer) -> BitArray{1} - :: - - rol(B::BitArray{1}, i::Integer) -> BitArray{1} - Performs a left rotation operation. -.. function:: ror!(dest::BitArray{1}, src::BitArray{1}, i::Integer) -> BitArray{1} +.. function:: ror!(B::BitArray{1}, i::Integer) -> BitArray{1} - :: - - ror!(B::BitArray{1}, i::Integer) -> BitArray{1} - Performs a right rotation operation on B. .. function:: ror!(B::BitArray{1}, i::Integer) -> BitArray{1} - :: - - ror!(B::BitArray{1}, i::Integer) -> BitArray{1} - Performs a right rotation operation on B. .. function:: ror(B::BitArray{1}, i::Integer) -> BitArray{1} - :: - - ror(B::BitArray{1}, i::Integer) -> BitArray{1} - Performs a right rotation operation. @@ -1174,183 +674,103 @@ Sparse Matrices Sparse matrices support much of the same set of operations as dense matrices. The following functions are specific to sparse matrices. -.. function:: sparse(I,J,V,[m,n,combine]) +.. function:: sparse(A) - :: - - sparse(A) - Convert an AbstractMatrix ``A`` into a sparse matrix. -.. function:: sparsevec(I, V, [m, combine]) +.. function:: sparsevec(A) - :: - - sparsevec(A) - Convert a dense vector ``A`` into a sparse matrix of size ``m x 1``. In julia, sparse vectors are really just sparse matrices with one column. -.. function:: sparsevec(D::Dict, [m]) +.. function:: sparsevec(A) - :: - - sparsevec(A) - Convert a dense vector ``A`` into a sparse matrix of size ``m x 1``. In julia, sparse vectors are really just sparse matrices with one column. .. function:: issparse(S) - :: - - issparse(S) - Returns ``true`` if ``S`` is sparse, and ``false`` otherwise. .. function:: sparse(A) - :: - - sparse(A) - Convert an AbstractMatrix ``A`` into a sparse matrix. .. function:: sparsevec(A) - :: - - sparsevec(A) - Convert a dense vector ``A`` into a sparse matrix of size ``m x 1``. In julia, sparse vectors are really just sparse matrices with one column. -.. function:: full(S) +.. function:: full(QRCompactWYQ[, thin=true]) -> Matrix - :: - - full(QRCompactWYQ[, thin=true]) -> Matrix - Converts an orthogonal or unitary matrix stored as a Optionally takes a ``thin`` Boolean argument, which if ``true`` omits the columns that span the rows of ``R`` in the QR factorization that are zero. The resulting matrix is the ``Q`` in a thin QR factorization (sometimes called the reduced QR factorization). If ``false``, returns a ``Q`` that spans all rows of ``R`` in its corresponding QR factorization. .. function:: nnz(A) - :: - - nnz(A) - Returns the number of stored (filled) elements in a sparse matrix. -.. function:: spzeros(m,n) +.. function:: spzeros(m, n) - :: - - spzeros(m, n) - Create a sparse matrix of size ``m x n``. This sparse matrix will not contain any nonzero values. No storage will be allocated for nonzero values during construction. .. function:: spones(S) - :: - - spones(S) - Create a sparse matrix with the same structure as that of ``S``, but with every nonzero element having the value ``1.0``. -.. function:: speye(type,m[,n]) +.. function:: speye(type, m[, n]) - :: - - speye(type, m[, n]) - Create a sparse identity matrix of specified type of size ``m x m``. In case ``n`` is supplied, create a sparse identity matrix of size ``m x n``. .. function:: spdiagm(B, d[, m, n]) - :: - - spdiagm(B, d[, m, n]) - Construct a sparse diagonal matrix. ``B`` is a tuple of vectors containing the diagonals and ``d`` is a tuple containing the positions of the diagonals. In the case the input contains only one diagonaly, ``B`` can be a vector (instead of a tuple) and ``d`` can be the diagonal position (instead of a tuple), defaulting to 0 resulting sparse matrix. -.. function:: sprand([rng,] m,n,p [,rfn]) +.. function:: sprand([rng], m, n, p[, rfn]) - :: - - sprand([rng], m, n, p[, rfn]) - Create a random ``m`` by ``n`` sparse matrix, in which the probability of any element being nonzero is independently given by by ``rfn``. The uniform distribution is used in case ``rfn`` is not specified. The optional ``rng`` argument specifies a random number generator, see *Random Numbers*. -.. function:: sprandn(m,n,p) +.. function:: sprandn(m, n, p) - :: - - sprandn(m, n, p) - Create a random ``m`` by ``n`` sparse matrix with the specified nonzero values are sampled from the normal distribution. -.. function:: sprandbool(m,n,p) +.. function:: sprandbool(m, n, p) - :: - - sprandbool(m, n, p) - Create a random ``m`` by ``n`` sparse boolean matrix with the specified (independent) probability ``p`` of any entry being .. function:: etree(A[, post]) - :: - - etree(A[, post]) - Compute the elimination tree of a symmetric sparse matrix ``A`` from ``triu(A)`` and, optionally, its post-ordering permutation. .. function:: symperm(A, p) - :: - - symperm(A, p) - Return the symmetric permutation of A, which is ``A[p,p]``. A should be symmetric and sparse, where only the upper triangular part of the matrix is stored. This algorithm ignores the lower triangular part of the matrix. Only the upper triangular part of the result is returned as well. .. function:: nonzeros(A) - :: - - nonzeros(A) - Return a vector of the structural nonzero values in sparse matrix matrix. The returned vector points directly to the internal nonzero storage of ``A``, and any modifications to the returned vector will mutate ``A`` as well. See ``rowvals(A)`` and ``nzrange(A, col)``. .. function:: rowvals(A) - :: - - rowvals(A) - Return a vector of the row indices of ``A``, and any modifications to the returned vector will mutate ``A`` as well. Given the internal storage format of sparse matrices, providing access to how the row indices are stored internally can be useful in conjuction with iterating over structural nonzero values. See ``nonzeros(A)`` and ``nzrange(A, col)``. .. function:: nzrange(A, col) - :: - - nzrange(A, col) - Return the range of indices to the structural nonzero values of a sparse matrix column. In conjunction with ``nonzeros(A)`` and matrix diff --git a/doc/stdlib/base.rst b/doc/stdlib/base.rst index 743019e3bf5ed..80546bcec5d31 100644 --- a/doc/stdlib/base.rst +++ b/doc/stdlib/base.rst @@ -22,163 +22,91 @@ Getting Around .. function:: exit([code]) - :: - - exit([code]) - Quit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully. .. function:: quit() - :: - - quit() - Quit the program indicating that the processes completed successfully. This function calls ``exit(0)`` (see ``exit()``). .. function:: atexit(f) - :: - - atexit(f) - Register a zero-argument function to be called at exit. .. function:: atreplinit(f) - :: - - atreplinit(f) - Register a one-argument function to be called before the REPL interface is initialized in interactive sessions; this is useful to customize the interface. The argument of ``f`` is the REPL object. This function should be called from within the ``.juliarc.jl`` initialization file. .. function:: isinteractive() -> Bool - :: - - isinteractive() -> Bool - Determine whether Julia is running an interactive session. .. function:: whos([Module,] [pattern::Regex]) - :: - - whos([Module,] [pattern::Regex]) - Print information about exported global variables in a module, optionally restricted to those matching ``pattern``. -.. function:: edit(file::AbstractString, [line]) +.. function:: edit(function[, types]) - :: - - edit(function[, types]) - Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit. -.. function:: edit(function, [types]) +.. function:: edit(function[, types]) - :: - - edit(function[, types]) - Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit. -.. function:: @edit +.. function:: @edit() - :: - - @edit() - Evaluates the arguments to the function call, determines their types, and calls the ``edit`` function on the resulting expression -.. function:: less(file::AbstractString, [line]) +.. function:: less(function[, types]) - :: - - less(function[, types]) - Show the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see. -.. function:: less(function, [types]) +.. function:: less(function[, types]) - :: - - less(function[, types]) - Show the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see. -.. function:: @less +.. function:: @less() - :: - - @less() - Evaluates the arguments to the function call, determines their types, and calls the ``less`` function on the resulting expression -.. function:: clipboard(x) +.. function:: clipboard() -> AbstractString - :: - - clipboard() -> AbstractString - Return a string with the contents of the operating system clipboard .. function:: clipboard() -> AbstractString - :: - - clipboard() -> AbstractString - Return a string with the contents of the operating system clipboard .. function:: require(file::AbstractString...) - :: - - require(file::AbstractString...) - Load source files once, in the context of the ``Main`` module, on every active node, searching standard locations for files. current ``include`` path but does not use it to search for files library code, and is implicitly called by ``using`` to load packages. When searching for files, ``require`` first looks in the current working directory, then looks for package code under ``Pkg.dir()``, then tries paths in the global array ``LOAD_PATH``. .. function:: reload(file::AbstractString) - :: - - reload(file::AbstractString) - Like ``require``, except forces loading of files regardless of whether they have been loaded before. Typically used when interactively developing libraries. -.. function:: include(path::AbstractString) +.. function:: include("file.jl") - :: - - include("file.jl") - Evaluate the contents of a source file in the current context. During including, a task-local include path is set to the directory containing the file. Nested calls to ``include`` will search relative to that path. All paths refer to files on node 1 when running in parallel, and files will be fetched from node 1. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files. .. function:: include_string(code::AbstractString) - :: - - include_string(code::AbstractString) - Like ``include``, except reads code from the given string rather than from a file. Since there is no file path involved, no path processing or fetching from node 1 is done. @@ -190,75 +118,43 @@ Getting Around Search documentation for functions related to ``string``. -.. function:: which(f, types) +.. function:: which(symbol) - :: - - which(symbol) - Return the module in which the binding for the variable referenced by ``symbol`` was created. .. function:: which(symbol) - :: - - which(symbol) - Return the module in which the binding for the variable referenced by ``symbol`` was created. -.. function:: @which +.. function:: @which() - :: - - @which() - Applied to a function call, it evaluates the arguments to the specified function call, and returns the ``Method`` object for the method that would be called for those arguments. Applied to a variable, it returns the module in which the variable was bound. It calls out to the ``which`` function. -.. function:: methods(f, [types]) +.. function:: methods(f[, types]) - :: - - methods(f[, types]) - Returns the method table for ``f``. If ``types`` is specified, returns an array of methods whose types match. .. function:: methodswith(typ[, module or function][, showparents]) - :: - - methodswith(typ[, module or function][, showparents]) - Return an array of methods with an argument of type ``typ``. If optional ``showparents`` is ``true``, also return arguments with a parent type of ``typ``, excluding type ``Any``. The optional second argument restricts the search to a particular module or function. -.. function:: @show +.. function:: @show() - :: - - @show() - Show an expression and result, returning the result .. function:: versioninfo([verbose::Bool]) - :: - - versioninfo([verbose::Bool]) - Print information about the version of Julia in use. If the as well. .. function:: workspace() - :: - - workspace() - Replace the top-level module (``Main``) with a new one, providing a clean workspace. The previous ``Main`` module is made available as statement such as ``using LastMain.Package``. This function should only be used interactively. @@ -270,201 +166,113 @@ Getting Around All Objects ----------- -.. function:: is(x, y) -> Bool +.. function:: ===(x, y) - :: - - ===(x, y) - See the ``is()`` operator .. function:: isa(x, type) -> Bool - :: - - isa(x, type) -> Bool - Determine whether ``x`` is of the given ``type``. .. function:: isequal(x, y) - :: - - isequal(x, y) - Similar to ``==``, except treats all floating-point ``NaN`` values as equal to each other, and treats ``-0.0`` as unequal to ``0.0``. The default implementation of ``isequal`` calls ``==``, so if you have a type that doesn't have these floating-point subtleties then you probably only need to define ``==``. hash(y)``. This typically means that if you define your own `==`` function then you must define a corresponding ``hash`` (and vice versa). Collections typically implement ``isequal`` by calling ``isequal`` recursively on all contents. Scalar types generally do not need to implement ``isequal`` separate from ``==``, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on ``isnan``, ``signbit``, and ``==``). .. function:: isless(x, y) - :: - - isless(x, y) - Test whether ``x`` is less than ``y``, according to a canonical total order. Values that are normally unordered, such as ``NaN``, are ordered in an arbitrary but consistent fashion. This is the default comparison used by ``sort``. Non-numeric types with a canonical total order should implement this function. Numeric types only need to implement it if they have special values such as .. function:: ifelse(condition::Bool, x, y) - :: - - ifelse(condition::Bool, x, y) - Return ``x`` if ``condition`` is true, otherwise return ``y``. This differs from ``?`` or ``if`` in that it is an ordinary function, so all the arguments are evaluated first. In some cases, using in generated code and provide higher performance in tight loops. .. function:: lexcmp(x, y) - :: - - lexcmp(x, y) - Compare ``x`` and ``y`` lexicographically and return -1, 0, or 1 depending on whether ``x`` is less than, equal to, or greater than lexicographically comparable types, and ``lexless`` will call .. function:: lexless(x, y) - :: - - lexless(x, y) - Determine whether ``x`` is lexicographically less than ``y``. .. function:: typeof(x) - :: - - typeof(x) - Get the concrete type of ``x``. .. function:: tuple(xs...) - :: - - tuple(xs...) - Construct a tuple of the given objects. .. function:: ntuple(f::Function, n) - :: - - ntuple(f::Function, n) - Create a tuple of length ``n``, computing each element as ``f(i)``, where ``i`` is the index of the element. .. function:: object_id(x) - :: - - object_id(x) - Get a unique integer id for ``x``. ``object_id(x)==object_id(y)`` if and only if ``is(x,y)``. .. function:: hash(x[, h]) - :: - - hash(x[, h]) - Compute an integer hash code such that ``isequal(x,y)`` implies code to be mixed with the result. New types should implement the 2-argument form, typically by calling the 2-argument ``hash`` method recursively in order to mix hashes of the contents with each other (and with ``h``). Typically, any type that implements ``hash`` should also implement its own ``==`` (hence ``isequal``) to guarantee the property mentioned above. .. function:: finalizer(x, function) - :: - - finalizer(x, function) - Register a function ``f(x)`` to be called when there are no program-accessible references to ``x``. The behavior of this function is unpredictable if ``x`` is of a bits type. .. function:: finalize(x) - :: - - finalize(x) - Immediately run finalizers registered for object ``x``. .. function:: copy(x) - :: - - copy(x) - Create a shallow copy of ``x``: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original. .. function:: deepcopy(x) - :: - - deepcopy(x) - Create a deep copy of ``x``: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling *deepcopy* on an object should generally have the same effect as serializing and then deserializing it. As a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied. The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal references. While it isn't normally necessary, user-defined types can override the default ``deepcopy`` behavior by defining a specialized version of the function ``deepcopy_internal(x::T, dict::ObjectIdDict)`` specialized for, and ``dict`` keeps track of objects copied so far within the recursion. Within the definition, ``deepcopy_internal`` should be used in place of ``deepcopy``, and the ``dict`` variable should be updated as appropriate before returning. -.. function:: isdefined([object,] index | symbol) +.. function:: isdefined([object], index | symbol) - :: - - isdefined([object], index | symbol) - Tests whether an assignable location is defined. The arguments can be an array and index, a composite object and field name (as a symbol), or a module and a symbol. With a single symbol argument, tests whether a global variable with that name is defined in .. function:: convert(T, x) - :: - - convert(T, x) - Convert ``x`` to a value of type ``T``. If ``T`` is an ``Integer`` type, an ``InexactError`` will be raised if ``x`` is not representable by ``T``, for example if ``x`` is not integer-valued, or is outside the range supported by ``T``. If ``T`` is a ``FloatingPoint`` or ``Rational`` type, then it will return the closest value to ``x`` representable by ``T``. .. function:: promote(xs...) - :: - - promote(xs...) - Convert all arguments to their common promotion type (if any), and return them all (as a tuple). .. function:: oftype(x, y) - :: - - oftype(x, y) - Convert ``y`` to the type of ``x`` (``convert(typeof(x), y)``). .. function:: widen(type | x) - :: - - widen(type | x) - If the argument is a type, return a ``larger`` type (for numeric types, this will be a type with at least as much range and precision as the argument, and usually more). Otherwise the argument ``x`` is converted to ``widen(typeof(x))``. .. function:: identity(x) - :: - - identity(x) - The identity function. Returns its argument. @@ -473,208 +281,116 @@ Types .. function:: super(T::DataType) - :: - - super(T::DataType) - Return the supertype of DataType T -.. function:: issubtype(type1, type2) +.. function:: <:(T1, T2) - :: - - <:(T1, T2) - Subtype operator, equivalent to ``issubtype(T1,T2)``. .. function:: <:(T1, T2) - :: - - <:(T1, T2) - Subtype operator, equivalent to ``issubtype(T1,T2)``. .. function:: subtypes(T::DataType) - :: - - subtypes(T::DataType) - Return a list of immediate subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module. .. function:: typemin(type) - :: - - typemin(type) - The lowest value representable by the given (real) numeric type. .. function:: typemax(type) - :: - - typemax(type) - The highest value representable by the given (real) numeric type. .. function:: realmin(type) - :: - - realmin(type) - The smallest in absolute value non-subnormal value representable by the given floating-point type .. function:: realmax(type) - :: - - realmax(type) - The highest finite value representable by the given floating-point type .. function:: maxintfloat(type) - :: - - maxintfloat(type) - The largest integer losslessly representable by the given floating- point type -.. function:: sizeof(type) +.. function:: sizeof(s::AbstractString) - :: - - sizeof(s::AbstractString) - The number of bytes in string ``s``. -.. function:: eps([type]) +.. function:: eps(::DateTime) -> Millisecond - :: - - eps(::DateTime) -> Millisecond - Returns ``Millisecond(1)`` for ``DateTime`` values and ``Day(1)`` for ``Date`` values. -.. function:: eps(x) +.. function:: eps(::DateTime) -> Millisecond - :: - - eps(::DateTime) -> Millisecond - Returns ``Millisecond(1)`` for ``DateTime`` values and ``Day(1)`` for ``Date`` values. .. function:: promote_type(type1, type2) - :: - - promote_type(type1, type2) - Determine a type big enough to hold values of each argument type without loss, whenever possible. In some cases, where no type exists to which both types can be promoted losslessly, some loss is tolerated; for example, ``promote_type(Int64,Float64)`` returns represented exactly as ``Float64`` values. .. function:: promote_rule(type1, type2) - :: - - promote_rule(type1, type2) - Specifies what type should be used by ``promote`` when given values of types ``type1`` and ``type2``. This function should not be called directly, but should have definitions added to it for new types as appropriate. .. function:: getfield(value, name::Symbol) - :: - - getfield(value, name::Symbol) - Extract a named field from a value of composite type. The syntax .. function:: setfield!(value, name::Symbol, x) - :: - - setfield!(value, name::Symbol, x) - Assign ``x`` to a named field in ``value`` of composite type. The syntax ``a.b = c`` calls ``setfield!(a, :b, c)``, and the syntax .. function:: fieldoffsets(type) - :: - - fieldoffsets(type) - The byte offset of each field of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct type: .. function:: fieldtype(type, name::Symbol | index::Int) - :: - - fieldtype(type, name::Symbol | index::Int) - Determine the declared type of a field (specified by name or index) in a composite type. .. function:: isimmutable(v) - :: - - isimmutable(v) - True if value ``v`` is immutable. See *Immutable Composite Types* for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value of .. function:: isbits(T) - :: - - isbits(T) - True if ``T`` is a ``plain data`` type, meaning it is immutable and contains no references to other values. Typical examples are numeric types such as ``UInt8``, ``Float64``, and .. function:: isleaftype(T) - :: - - isleaftype(T) - Determine whether ``T`` is a concrete type that can have instances, meaning its only subtypes are itself and ``None`` (but ``T`` itself is not ``None``). .. function:: typejoin(T, S) - :: - - typejoin(T, S) - Compute a type that contains both ``T`` and ``S``. .. function:: typeintersect(T, S) - :: - - typeintersect(T, S) - Compute a type that contains the intersection of ``T`` and ``S``. Usually this will be the smallest such type or one close to it. @@ -702,10 +418,6 @@ Types .. function:: instances(T::Type) - :: - - instances(T::Type) - Return a collection of all instances of the given type, if applicable. Mostly used for enumerated types (see ``@enum``). @@ -714,46 +426,26 @@ Generic Functions .. function:: method_exists(f, Tuple type) -> Bool - :: - - method_exists(f, Tuple type) -> Bool - Determine whether the given generic function has a method matching the given ``Tuple`` of argument types. .. function:: applicable(f, args...) -> Bool - :: - - applicable(f, args...) -> Bool - Determine whether the given generic function has a method applicable to the given arguments. .. function:: invoke(f, (types...), args...) - :: - - invoke(f, (types...), args...) - Invoke a method for the given generic function matching the specified types (as a tuple), on the specified arguments. The arguments must be compatible with the specified types. This allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function). .. function:: |>(x, f) - :: - - |>(x, f) - Applies a function to the preceding argument. This allows for easy function chaining. .. function:: call(x, args...) - :: - - call(x, args...) - If ``x`` is not a ``Function``, then ``x(args...)`` is equivalent to ``call(x, args...)``. This means that function-like behavior can be added to any type by defining new ``call`` methods. @@ -762,73 +454,41 @@ Syntax .. function:: eval([m::Module], expr::Expr) - :: - - eval([m::Module], expr::Expr) - Evaluate an expression in the given module and return the result. Every module (except those defined with ``baremodule``) has its own 1-argument definition of ``eval``, which evaluates expressions in that module. -.. function:: @eval +.. function:: @eval() - :: - - @eval() - Evaluate an expression and return the value. .. function:: evalfile(path::AbstractString) - :: - - evalfile(path::AbstractString) - Load the file using ``include``, evaluate all expressions, and return the value of the last one. .. function:: esc(e::ANY) - :: - - esc(e::ANY) - Only valid in the context of an Expr returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See the *Macros* section of the Metaprogramming chapter of the manual for more details and examples. .. function:: gensym([tag]) - :: - - gensym([tag]) - Generates a symbol which will not conflict with other variable names. -.. function:: @gensym +.. function:: @gensym() - :: - - @gensym() - Generates a gensym symbol for a variable. For example, ``@gensym x y`` is transformed into ``x = gensym(``x``); y = gensym(``y``)``. -.. function:: parse(str, start; greedy=true, raise=true) +.. function:: parse(type, str[, base]) - :: - - parse(type, str[, base]) - Parse a string as a number. If the type is an integer type, then a base can be specified (the default is 10). If the type is a floating point type, the string is parsed as a decimal floating point number. If the string does not contain a valid number, an error is raised. -.. function:: parse(str; raise=true) +.. function:: parse(type, str[, base]) - :: - - parse(type, str[, base]) - Parse a string as a number. If the type is an integer type, then a base can be specified (the default is 10). If the type is a floating point type, the string is parsed as a decimal floating point number. If the string does not contain a valid number, an error is raised. @@ -837,37 +497,21 @@ Nullables .. function:: Nullable(x) - :: - - Nullable(x) - Wrap value ``x`` in an object of type ``Nullable``, which indicates whether a value is present. ``Nullable(x)`` yields a non-empty wrapper, and ``Nullable{T}()`` yields an empty instance of a wrapper that might contain a value of type ``T``. -.. function:: get(x) +.. function:: get(f::Function, collection, key) - :: - - get(f::Function, collection, key) - Return the value stored for the given key, or if no mapping for the key is present, return ``f()``. Use ``get!()`` to also store the default value in the dictionary. This is intended to be called using ``do`` block syntax: -.. function:: get(x, y) +.. function:: get(f::Function, collection, key) - :: - - get(f::Function, collection, key) - Return the value stored for the given key, or if no mapping for the key is present, return ``f()``. Use ``get!()`` to also store the default value in the dictionary. This is intended to be called using ``do`` block syntax: .. function:: isnull(x) - :: - - isnull(x) - Is the ``Nullable`` object ``x`` null, i.e. missing a value? @@ -876,19 +520,11 @@ System .. function:: run(command) - :: - - run(command) - Run a command object, constructed with backticks. Throws an error if anything goes wrong, including the process exiting with a non- zero status. .. function:: spawn(command) - :: - - spawn(command) - Run a command object asynchronously, returning the resulting @@ -899,55 +535,31 @@ System .. function:: success(command) - :: - - success(command) - Run a command object, constructed with backticks, and tell whether it was successful (exited with a code of 0). An exception is raised if the process cannot be started. .. function:: process_running(p::Process) - :: - - process_running(p::Process) - Determine whether a process is currently running. .. function:: process_exited(p::Process) - :: - - process_exited(p::Process) - Determine whether a process has exited. -.. function:: kill(p::Process, signum=SIGTERM) +.. function:: kill(manager::FooManager, pid::Int, config::WorkerConfig) - :: - - kill(manager::FooManager, pid::Int, config::WorkerConfig) - Implemented by cluster managers. It is called on the master process, by ``rmprocs``. It should cause the remote worker specified by ``pid`` to exit. -.. function:: open(command, mode::AbstractString="r", stdio=DevNull) +.. function:: open(f::function, args...) - :: - - open(f::function, args...) - Apply the function ``f`` to the result of ``open(args...)`` and close the resulting file descriptor upon completion. -.. function:: open(f::Function, command, mode::AbstractString="r", stdio=DevNull) +.. function:: open(f::function, args...) - :: - - open(f::function, args...) - Apply the function ``f`` to the result of ``open(args...)`` and close the resulting file descriptor upon completion. @@ -961,190 +573,106 @@ System .. function:: readandwrite(command) - :: - - readandwrite(command) - Starts running a command asynchronously, and returns a tuple process, and the process object itself. .. function:: ignorestatus(command) - :: - - ignorestatus(command) - Mark a command object so that running it will not throw an error if the result code is non-zero. .. function:: detach(command) - :: - - detach(command) - Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it. .. function:: setenv(command, env; dir=working_dir) - :: - - setenv(command, env; dir=working_dir) - Set environment variables to use when running the given command. of strings of the form ``var=val``, or zero or more replace) the existing environment, create ``env`` by ``copy(ENV)`` and then setting ``env[``var``]=val`` as desired, or use The ``dir`` keyword argument can be used to specify a working directory for the command. .. function:: withenv(f::Function, kv::Pair...) - :: - - withenv(f::Function, kv::Pair...) - - Execute ``f()`` in an environment that is temporarily modified (not replaced as in ``setenv``) by zero or more ``var``=>val`` arguments ``kv``. ``withenv`` is generally used via the be used to temporarily unset an environment variable (if it is set). When ``withenv`` returns, the original environment has been restored. + Execute ``f()`` in an environment that is temporarily modified (not replaced as in ``setenv``) by zero or more ``var``=>val` arguments ``kv``. ``withenv`` is generally used via the be used to temporarily unset an environment variable (if it is set). When ``withenv`` returns, the original environment has been restored. -.. function:: pipe(from, to, ...) +.. function:: pipe(command; stdin, stdout, stderr, append=false) - :: - - pipe(command; stdin, stdout, stderr, append=false) - Redirect I/O to or from the given ``command``. Keyword arguments specify which of the command's streams should be redirected. is a more general version of the 2-argument ``pipe`` function. .. function:: pipe(command; stdin, stdout, stderr, append=false) - :: - - pipe(command; stdin, stdout, stderr, append=false) - Redirect I/O to or from the given ``command``. Keyword arguments specify which of the command's streams should be redirected. is a more general version of the 2-argument ``pipe`` function. .. function:: gethostname() -> AbstractString - :: - - gethostname() -> AbstractString - Get the local machine's host name. .. function:: getipaddr() -> AbstractString - :: - - getipaddr() -> AbstractString - Get the IP address of the local machine, as a string of the form .. function:: getpid() -> Int32 - :: - - getpid() -> Int32 - Get julia's process ID. -.. function:: time() +.. function:: time(t::TmStruct) - :: - - time(t::TmStruct) - Converts a ``TmStruct`` struct to a number of seconds since the epoch. .. function:: time_ns() - :: - - time_ns() - Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years. .. function:: tic() - :: - - tic() - Set a timer to be read by the next call to ``toc()`` or ``toq()``. The macro call ``@time expr`` can also be used to time evaluation. .. function:: toc() - :: - - toc() - Print and return the time elapsed since the last ``tic()``. .. function:: toq() - :: - - toq() - Return, but do not print, the time elapsed since the last -.. function:: @time +.. function:: @time() - :: - - @time() - A macro to execute an expression, printing the time it took to execute, the number of allocations, and the total number of bytes its execution caused to be allocated, before returning the value of the expression. -.. function:: @timev +.. function:: @timev() - :: - - @timev() - This is a verbose version of the ``@time`` macro, it first prints the same information as ``@time``, then any non-zero memory allocation counters, and then returns the value of the expression. -.. function:: @timed +.. function:: @timed() - :: - - @timed() - A macro to execute an expression, and return the value of the expression, elapsed time, total bytes allocated, garbage collection time, and an object with various memory allocation counters. -.. function:: @elapsed +.. function:: @elapsed() - :: - - @elapsed() - A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number. -.. function:: @allocated +.. function:: @allocated() - :: - - @allocated() - A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression. Note: the expression is evaluated inside a local function, instead of the current context, in order to eliminate the effects of compilation, however, there still may be some allocations due to JIT compilation. This also makes the results inconsistent with the ``@time`` macros, which do not try to adjust for the effects of compilation. .. function:: EnvHash() -> EnvHash - :: - - EnvHash() -> EnvHash - A singleton of this type provides a hash table interface to environment variables. @@ -1152,39 +680,23 @@ System Reference to the singleton ``EnvHash``, providing a dictionary interface to system environment variables. -.. function:: @unix +.. function:: @unix() - :: - - @unix() - Given ``@unix? a : b``, do ``a`` on Unix systems (including Linux and OS X) and ``b`` elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual. -.. function:: @osx +.. function:: @osx() - :: - - @osx() - Given ``@osx? a : b``, do ``a`` on OS X and ``b`` elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual. -.. function:: @linux +.. function:: @linux() - :: - - @linux() - Given ``@linux? a : b``, do ``a`` on Linux and ``b`` elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual. -.. function:: @windows +.. function:: @windows() - :: - - @windows() - Given ``@windows? a : b``, do ``a`` on Windows and ``b`` elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual. @@ -1193,55 +705,31 @@ Errors .. function:: error(message::AbstractString) - :: - - error(message::AbstractString) - Raise an ``ErrorException`` with the given message .. function:: throw(e) - :: - - throw(e) - Throw an object as an exception .. function:: rethrow([e]) - :: - - rethrow([e]) - Throw an object without changing the current exception backtrace. The default argument is the current exception (if called within a .. function:: backtrace() - :: - - backtrace() - Get a backtrace object for the current program point. .. function:: catch_backtrace() - :: - - catch_backtrace() - Get the backtrace of the current exception, for use within .. function:: assert(cond) - :: - - assert(cond) - Throw an ``AssertionError`` if ``cond`` is false. Also available as the macro ``@assert expr``. @@ -1251,238 +739,134 @@ Errors .. function:: ArgumentError(msg) - :: - - ArgumentError(msg) - The parameters to a function call do not match a valid signature. .. function:: AssertionError([msg]) - :: - - AssertionError([msg]) - The asserted condition did not evalutate to ``true``. -.. function:: BoundsError([a],[i]) +.. function:: BoundsError([a][, i]) - :: - - BoundsError([a][, i]) - An indexing operation into an array, ``a``, tried to access an out- of-bounds element, ``i``. .. function:: DimensionMismatch([msg]) - :: - - DimensionMismatch([msg]) - The objects called do not have matching dimensionality. .. function:: DivideError() - :: - - DivideError() - Integer division was attempted with a denominator value of 0. .. function:: DomainError() - :: - - DomainError() - The arguments to a function or constructor are outside the valid domain. .. function:: EOFError() - :: - - EOFError() - No more data was available to read from a file or stream. .. function:: ErrorException(msg) - :: - - ErrorException(msg) - Generic error type. The error message, in the *.msg* field, may provide more specific details. .. function:: InexactError() - :: - - InexactError() - Type conversion cannot be done exactly. .. function:: InterruptException() - :: - - InterruptException() - The process was stopped by a terminal interrupt (CTRL+C). .. function:: KeyError(key) - :: - - KeyError(key) - An indexing operation into an ``Associative`` (``Dict``) or ``Set`` like object tried to access or delete a non-existent element. .. function:: LoadError(file::AbstractString, line::Int, error) - :: - - LoadError(file::AbstractString, line::Int, error) - An error occurred while *including*, *requiring*, or *using* a file. The error specifics should be available in the *.error* field. .. function:: MethodError(f, args) - :: - - MethodError(f, args) - A method with the required type signature does not exist in the given generic function. .. function:: NullException() - :: - - NullException() - An attempted access to a ``Nullable`` with no defined value. .. function:: OutOfMemoryError() - :: - - OutOfMemoryError() - An operation allocated too much memory for either the system or the garbage collector to handle properly. .. function:: ReadOnlyMemoryError() - :: - - ReadOnlyMemoryError() - An operation tried to write to memory that is read-only. .. function:: OverflowError() - :: - - OverflowError() - The result of an expression is too large for the specified type and will cause a wraparound. .. function:: ParseError(msg) - :: - - ParseError(msg) - The expression passed to the *parse* function could not be interpreted as a valid Julia expression. .. function:: ProcessExitedException() - :: - - ProcessExitedException() - After a client Julia process has exited, further attempts to reference the dead child will throw this exception. .. function:: StackOverflowError() - :: - - StackOverflowError() - The function call grew beyond the size of the call stack. This usually happens when a call recurses infinitely. -.. function:: SystemError(prefix::AbstractString, [errnum::Int32]) +.. function:: SystemError(prefix::AbstractString[, errnum::Int32]) - :: - - SystemError(prefix::AbstractString[, errnum::Int32]) - A system call failed with an error code (in the ``errno`` global variable). .. function:: TypeError(func::Symbol, context::AbstractString, expected::Type, got) - :: - - TypeError(func::Symbol, context::AbstractString, expected::Type, got) - A type assertion failure, or calling an intrinsic function with an incorrect argument type. .. function:: UndefRefError() - :: - - UndefRefError() - The item or field is not defined for the given object. .. function:: UndefVarError(var::Symbol) - :: - - UndefVarError(var::Symbol) - A symbol in the current scope is not defined. Events ------ -.. function:: Timer(callback::Function, delay, repeat=0) +.. function:: Timer(delay, repeat=0) - :: - - Timer(delay, repeat=0) - Create a timer that wakes up tasks waiting for it (by calling .. function:: Timer(delay, repeat=0) - :: - - Timer(delay, repeat=0) - Create a timer that wakes up tasks waiting for it (by calling @@ -1491,118 +875,66 @@ Reflection .. function:: module_name(m::Module) -> Symbol - :: - - module_name(m::Module) -> Symbol - Get the name of a module as a symbol. .. function:: module_parent(m::Module) -> Module - :: - - module_parent(m::Module) -> Module - Get a module's enclosing module. ``Main`` is its own parent. .. function:: current_module() -> Module - :: - - current_module() -> Module - Get the *dynamically* current module, which is the module code is currently being read from. In general, this is not the same as the module containing the call to this function. .. function:: fullname(m::Module) - :: - - fullname(m::Module) - Get the fully-qualified name of a module as a tuple of symbols. For example, ``fullname(Base.Pkg)`` gives ``(:Base,:Pkg)``, and .. function:: names(x::Module[, all=false[, imported=false]]) - :: - - names(x::Module[, all=false[, imported=false]]) - Get an array of the names exported by a module, with optionally more module globals according to the additional parameters. .. function:: nfields(x::DataType) -> Int - :: - - nfields(x::DataType) -> Int - Get the number of fields of a data type. .. function:: fieldnames(x::DataType) - :: - - fieldnames(x::DataType) - Get an array of the fields of a data type. .. function:: isconst([m::Module], s::Symbol) -> Bool - :: - - isconst([m::Module], s::Symbol) -> Bool - Determine whether a global is declared ``const`` in a given module. The default module argument is ``current_module()``. .. function:: isgeneric(f::Function) -> Bool - :: - - isgeneric(f::Function) -> Bool - Determine whether a function is generic. .. function:: function_name(f::Function) -> Symbol - :: - - function_name(f::Function) -> Symbol - Get the name of a generic function as a symbol, or ``:anonymous``. .. function:: function_module(f::Function, types) -> Module - :: - - function_module(f::Function, types) -> Module - Determine the module containing a given definition of a generic function. -.. function:: functionloc(f::Function, types) +.. function:: functionloc(m::Method) - :: - - functionloc(m::Method) - Returns a tuple ``(filename,line)`` giving the location of a method definition. .. function:: functionloc(m::Method) - :: - - functionloc(m::Method) - Returns a tuple ``(filename,line)`` giving the location of a method definition. @@ -1611,136 +943,76 @@ Internals .. function:: gc() - :: - - gc() - Perform garbage collection. This should not generally be used. .. function:: gc_enable(on::Bool) - :: - - gc_enable(on::Bool) - Control whether garbage collection is enabled using a boolean argument (true for enabled, false for disabled). Returns previous GC state. Disabling garbage collection should be used only with extreme caution, as it can cause memory use to grow without bound. .. function:: macroexpand(x) - :: - - macroexpand(x) - Takes the expression x and returns an equivalent expression with all macros removed (expanded). .. function:: expand(x) - :: - - expand(x) - Takes the expression x and returns an equivalent expression in lowered form .. function:: code_lowered(f, types) - :: - - code_lowered(f, types) - Returns an array of lowered ASTs for the methods matching the given generic function and type signature. -.. function:: @code_lowered +.. function:: @code_lowered() - :: - - @code_lowered() - Evaluates the arguments to the function call, determines their types, and calls ``code_lowered()`` on the resulting expression .. function:: code_typed(f, types; optimize=true) - :: - - code_typed(f, types; optimize=true) - Returns an array of lowered and type-inferred ASTs for the methods matching the given generic function and type signature. The keyword argument ``optimize`` controls whether additional optimizations, such as inlining, are also applied. -.. function:: @code_typed +.. function:: @code_typed() - :: - - @code_typed() - Evaluates the arguments to the function call, determines their types, and calls ``code_typed()`` on the resulting expression .. function:: code_warntype(f, types) - :: - - code_warntype(f, types) - Displays lowered and type-inferred ASTs for the methods matching the given generic function and type signature. The ASTs are annotated in such a way as to cause ``non-leaf`` types to be emphasized (if color is available, displayed in red). This serves as a warning of potential type instability. Not all non-leaf types are particularly problematic for performance, so the results need to be used judiciously. See *@code_warntype* for more information. -.. function:: @code_warntype +.. function:: @code_warntype() - :: - - @code_warntype() - Evaluates the arguments to the function call, determines their types, and calls ``code_warntype()`` on the resulting expression .. function:: code_llvm(f, types) - :: - - code_llvm(f, types) - Prints the LLVM bitcodes generated for running the method matching the given generic function and type signature to ``STDOUT``. All metadata and dbg.* calls are removed from the printed bitcode. Use code_llvm_raw for the full IR. -.. function:: @code_llvm +.. function:: @code_llvm() - :: - - @code_llvm() - Evaluates the arguments to the function call, determines their types, and calls ``code_llvm()`` on the resulting expression .. function:: code_native(f, types) - :: - - code_native(f, types) - Prints the native assembly instructions generated for running the method matching the given generic function and type signature to STDOUT. -.. function:: @code_native +.. function:: @code_native() - :: - - @code_native() - Evaluates the arguments to the function call, determines their types, and calls ``code_native()`` on the resulting expression -.. function:: precompile(f,args::Tuple{Vararg{Any}}) +.. function:: precompile(f, args::Tuple{Vararg{Any}}) - :: - - precompile(f, args::Tuple{Vararg{Any}}) - Compile the given function ``f`` for the argument tuple (of types) diff --git a/doc/stdlib/c.rst b/doc/stdlib/c.rst index e2c3e2b0019ce..5b67f29eb50ec 100644 --- a/doc/stdlib/c.rst +++ b/doc/stdlib/c.rst @@ -6,163 +6,91 @@ .. function:: ccall((symbol, library) or function_pointer, ReturnType, (ArgumentType1, ...), ArgumentValue1, ...) - :: - - ccall((symbol, library) or function_pointer, ReturnType, (ArgumentType1, ...), ArgumentValue1, ...) - Call function in C-exported shared library, specified by AbstractString or :Symbol. Note that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression. Alternatively, ccall may also be used to call a function pointer, such as one returned by dlsym. Each ``ArgumentValue`` to the ``ccall`` will be converted to the corresponding ``ArgumentType``, by automatic insertion of calls to ArgumentValue))``. (see also the documentation for each of these functions for further details). In most cases, this simply results in a call to `convert(ArgumentType, ArgumentValue)`` -.. function:: cglobal((symbol, library) [, type=Void]) +.. function:: cglobal((symbol, library)[, type=Void]) - :: - - cglobal((symbol, library)[, type=Void]) - Obtain a pointer to a global variable in a C-exported shared library, specified exactly as in ``ccall``. Returns a supplied. The values can be read or written by ``unsafe_load`` or .. function:: cfunction(function::Function, ReturnType::Type, (ArgumentTypes...)) - :: - - cfunction(function::Function, ReturnType::Type, (ArgumentTypes...)) - Generate C-callable function pointer from Julia function. Type annotation of the return value in the callback function is a must for situations where Julia cannot infer the return type automatically. For example: -.. function:: unsafe_convert(T,x) +.. function:: unsafe_convert(T, x) - :: - - unsafe_convert(T, x) - Convert ``x`` to a value of type ``T`` In cases where ``convert`` would need to take a Julia object and turn it into a ``Ptr``, this function should be used to define and perform that conversion. Be careful to ensure that a julia reference to ``x`` exists as long as the result of this function will be used. Accordingly, the argument ``x`` to this function should never be an expression, only a variable name or field reference. For example, ``x=a.b.c`` is acceptable, but ``x=[a,b,c]`` is not. The ``unsafe`` prefix on this function indicates that using the result of this function after the ``x`` argument to this function is no longer accessible to the program may cause undefined behavior, including program corruption or segfaults, at any later time. -.. function:: cconvert(T,x) +.. function:: cconvert(T, x) - :: - - cconvert(T, x) - Convert ``x`` to a value of type ``T``, typically by calling In cases where ``x`` cannot be safely converted to ``T``, unlike from ``T``, which however is suitable for ``unsafe_convert`` to handle. Neither ``convert`` nor ``cconvert`` should take a Julia object and turn it into a ``Ptr``. -.. function:: unsafe_load(p::Ptr{T},i::Integer) +.. function:: unsafe_load(p::Ptr{T}, i::Integer) - :: - - unsafe_load(p::Ptr{T}, i::Integer) - Load a value of type ``T`` from the address of the ith element expression ``p[i-1]``. The ``unsafe`` prefix on this function indicates that no validation is performed on the pointer ``p`` to ensure that it is valid. Incorrect usage may segfault your program or return garbage answers, in the same manner as C. -.. function:: unsafe_store!(p::Ptr{T},x,i::Integer) +.. function:: unsafe_store!(p::Ptr{T}, x, i::Integer) - :: - - unsafe_store!(p::Ptr{T}, x, i::Integer) - Store a value of type ``T`` to the address of the ith element expression ``p[i-1] = x``. The ``unsafe`` prefix on this function indicates that no validation is performed on the pointer ``p`` to ensure that it is valid. Incorrect usage may corrupt or segfault your program, in the same manner as C. -.. function:: unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, N) +.. function:: unsafe_copy!(dest::Array, do, src::Array, so, N) - :: - - unsafe_copy!(dest::Array, do, src::Array, so, N) - Copy ``N`` elements from a source array to a destination, starting at offset ``so`` in the source and ``do`` in the destination The ``unsafe`` prefix on this function indicates that no validation is performed to ensure that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in the same manner as C. .. function:: unsafe_copy!(dest::Array, do, src::Array, so, N) - :: - - unsafe_copy!(dest::Array, do, src::Array, so, N) - Copy ``N`` elements from a source array to a destination, starting at offset ``so`` in the source and ``do`` in the destination The ``unsafe`` prefix on this function indicates that no validation is performed to ensure that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in the same manner as C. -.. function:: copy!(dest, src) +.. function:: copy!(dest, do, src, so, N) - :: - - copy!(dest, do, src, so, N) - Copy ``N`` elements from collection ``src`` starting at offset .. function:: copy!(dest, do, src, so, N) - :: - - copy!(dest, do, src, so, N) - Copy ``N`` elements from collection ``src`` starting at offset -.. function:: pointer(array [, index]) +.. function:: pointer(array[, index]) - :: - - pointer(array[, index]) - Get the native address of an array or string element. Be careful to ensure that a julia reference to ``a`` exists as long as this pointer will be used. This function is ``unsafe`` like Calling ``Ref(array[, index])`` is generally preferable to this function. .. function:: pointer_to_array(pointer, dims[, take_ownership::Bool]) - :: - - pointer_to_array(pointer, dims[, take_ownership::Bool]) - Wrap a native pointer as a Julia Array object. The pointer element type determines the array element type. ``own`` optionally specifies whether Julia should take ownership of the memory, calling ``free`` on the pointer when the array is no longer referenced. .. function:: pointer_from_objref(object_instance) - :: - - pointer_from_objref(object_instance) - Get the memory address of a Julia object as a ``Ptr``. The existence of the resulting ``Ptr`` will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the ``Ptr`` will be used. .. function:: unsafe_pointer_to_objref(p::Ptr) - :: - - unsafe_pointer_to_objref(p::Ptr) - Convert a ``Ptr`` to an object reference. Assumes the pointer refers to a valid heap-allocated Julia object. If this is not the case, undefined behavior results, hence this function is considered .. function:: disable_sigint(f::Function) - :: - - disable_sigint(f::Function) - Disable Ctrl-C handler during execution of a function, for calling external code that is not interrupt safe. Intended to be called using ``do`` block syntax as follows: .. function:: reenable_sigint(f::Function) - :: - - reenable_sigint(f::Function) - Re-enable Ctrl-C handler during execution of a function. Temporarily reverses the effect of ``disable_sigint``. .. function:: systemerror(sysfunc, iftrue) - :: - - systemerror(sysfunc, iftrue) - Raises a ``SystemError`` for ``errno`` with the descriptive string diff --git a/doc/stdlib/collections.rst b/doc/stdlib/collections.rst index 8d685ef990d38..a21ab57d193f7 100644 --- a/doc/stdlib/collections.rst +++ b/doc/stdlib/collections.rst @@ -26,100 +26,56 @@ The ``state`` object may be anything, and should be chosen appropriately for eac .. function:: start(iter) -> state - :: - - start(iter) -> state - Get initial iteration state for an iterable object .. function:: done(iter, state) -> Bool - :: - - done(iter, state) -> Bool - Test whether we are done iterating .. function:: next(iter, state) -> item, state - :: - - next(iter, state) -> item, state - For a given iterable object and iteration state, return the current item and the next iteration state .. function:: zip(iters...) - :: - - zip(iters...) - For a set of iterable objects, returns an iterable of tuples, where the ``i``th tuple contains the ``i``th component of each input iterable. Note that ``zip()`` is its own inverse: .. function:: enumerate(iter) - :: - - enumerate(iter) - An iterator that yields ``(i, x)`` where ``i`` is an index starting at 1, and ``x`` is the ``i``th value from the given iterator. It's useful when you need not only the values ``x`` over which you are iterating, but also the index ``i`` of the iterations. .. function:: rest(iter, state) - :: - - rest(iter, state) - An iterator that yields the same elements as ``iter``, but starting at the given ``state``. .. function:: countfrom(start=1, step=1) - :: - - countfrom(start=1, step=1) - An iterator that counts forever, starting at ``start`` and incrementing by ``step``. .. function:: take(iter, n) - :: - - take(iter, n) - An iterator that generates at most the first ``n`` elements of .. function:: drop(iter, n) - :: - - drop(iter, n) - An iterator that generates all but the first ``n`` elements of .. function:: cycle(iter) - :: - - cycle(iter) - An iterator that cycles through ``iter`` forever. .. function:: repeated(x[, n::Int]) - :: - - repeated(x[, n::Int]) - An iterator that generates the value ``x`` forever. If ``n`` is specified, generates ``x`` that many times (equivalent to @@ -145,37 +101,21 @@ General Collections .. function:: isempty(collection) -> Bool - :: - - isempty(collection) -> Bool - Determine whether a collection is empty (has no elements). .. function:: empty!(collection) -> collection - :: - - empty!(collection) -> collection - Remove all elements from a ``collection``. -.. function:: length(collection) -> Integer +.. function:: length(s) - :: - - length(s) - The number of characters in string ``s``. .. function:: endof(collection) -> Integer - :: - - endof(collection) -> Integer - Returns the last index of the collection. @@ -197,622 +137,346 @@ Iterable Collections .. function:: in(item, collection) -> Bool - :: - - in(item, collection) -> Bool - Determine whether an item is in the given collection, in the sense that it is ``==`` to one of the values generated by iterating over the collection. Some collections need a slightly different definition; for example ``Set``s check whether the item To test for the presence of a key in a dictionary, use ``haskey()`` or ``k in keys(dict)``. .. function:: eltype(type) - :: - - eltype(type) - Determine the type of the elements generated by iterating a collection of the given ``type``. For associative collection types, this will be a ``(key,value)`` tuple type. The definition that instances can be passed instead of types. However the form that accepts a type argument should be defined for new types. .. function:: indexin(a, b) - :: - - indexin(a, b) - Returns a vector containing the highest index in ``b`` for each value in ``a`` that is a member of ``b`` . The output vector contains 0 wherever ``a`` is not a member of ``b``. .. function:: findin(a, b) - :: - - findin(a, b) - Returns the indices of elements in collection ``a`` that appear in collection ``b`` .. function:: unique(itr[, dim]) - :: - - unique(itr[, dim]) - Returns an array containing only the unique elements of the iterable ``itr``, in the order that the first of each set of equivalent elements originally appears. If ``dim`` is specified, returns unique regions of the array ``itr`` along ``dim``. -.. function:: reduce(op, v0, itr) +.. function:: reduce(op, itr) - :: - - reduce(op, itr) - Like ``reduce(op, v0, itr)``. This cannot be used with empty collections, except for some special cases (e.g. when ``op`` is one of ``+``, ``*``, ``max``, ``min``, ``&``, ``|``) when Julia can determine the neutral element of ``op``. .. function:: reduce(op, itr) - :: - - reduce(op, itr) - Like ``reduce(op, v0, itr)``. This cannot be used with empty collections, except for some special cases (e.g. when ``op`` is one of ``+``, ``*``, ``max``, ``min``, ``&``, ``|``) when Julia can determine the neutral element of ``op``. -.. function:: foldl(op, v0, itr) +.. function:: foldl(op, itr) - :: - - foldl(op, itr) - Like ``foldl(op, v0, itr)``, but using the first element of ``itr`` as ``v0``. In general, this cannot be used with empty collections .. function:: foldl(op, itr) - :: - - foldl(op, itr) - Like ``foldl(op, v0, itr)``, but using the first element of ``itr`` as ``v0``. In general, this cannot be used with empty collections -.. function:: foldr(op, v0, itr) +.. function:: foldr(op, itr) - :: - - foldr(op, itr) - Like ``foldr(op, v0, itr)``, but using the last element of ``itr`` as ``v0``. In general, this cannot be used with empty collections .. function:: foldr(op, itr) - :: - - foldr(op, itr) - Like ``foldr(op, v0, itr)``, but using the last element of ``itr`` as ``v0``. In general, this cannot be used with empty collections -.. function:: maximum(itr) +.. function:: maximum(A, dims) - :: - - maximum(A, dims) - Compute the maximum value of an array over the given dimensions. .. function:: maximum(A, dims) - :: - - maximum(A, dims) - Compute the maximum value of an array over the given dimensions. .. function:: maximum!(r, A) - :: - - maximum!(r, A) - Compute the maximum value of ``A`` over the singleton dimensions of -.. function:: minimum(itr) +.. function:: minimum(A, dims) - :: - - minimum(A, dims) - Compute the minimum value of an array over the given dimensions. .. function:: minimum(A, dims) - :: - - minimum(A, dims) - Compute the minimum value of an array over the given dimensions. .. function:: minimum!(r, A) - :: - - minimum!(r, A) - Compute the minimum value of ``A`` over the singleton dimensions of .. function:: extrema(itr) - :: - - extrema(itr) - Compute both the minimum and maximum element in a single pass, and return them as a 2-tuple. .. function:: indmax(itr) -> Integer - :: - - indmax(itr) -> Integer - Returns the index of the maximum element in a collection. .. function:: indmin(itr) -> Integer - :: - - indmin(itr) -> Integer - Returns the index of the minimum element in a collection. -.. function:: findmax(itr) -> (x, index) +.. function:: findmax(A, dims) -> (maxval, index) - :: - - findmax(A, dims) -> (maxval, index) - For an array input, returns the value and index of the maximum over the given dimensions. .. function:: findmax(A, dims) -> (maxval, index) - :: - - findmax(A, dims) -> (maxval, index) - For an array input, returns the value and index of the maximum over the given dimensions. -.. function:: findmin(itr) -> (x, index) +.. function:: findmin(A, dims) -> (minval, index) - :: - - findmin(A, dims) -> (minval, index) - For an array input, returns the value and index of the minimum over the given dimensions. .. function:: findmin(A, dims) -> (minval, index) - :: - - findmin(A, dims) -> (minval, index) - For an array input, returns the value and index of the minimum over the given dimensions. -.. function:: maxabs(itr) +.. function:: maxabs(A, dims) - :: - - maxabs(A, dims) - Compute the maximum absolute values over given dimensions. .. function:: maxabs(A, dims) - :: - - maxabs(A, dims) - Compute the maximum absolute values over given dimensions. .. function:: maxabs!(r, A) - :: - - maxabs!(r, A) - Compute the maximum absolute values over the singleton dimensions of ``r``, and write values to ``r``. -.. function:: minabs(itr) +.. function:: minabs(A, dims) - :: - - minabs(A, dims) - Compute the minimum absolute values over given dimensions. .. function:: minabs(A, dims) - :: - - minabs(A, dims) - Compute the minimum absolute values over given dimensions. .. function:: minabs!(r, A) - :: - - minabs!(r, A) - Compute the minimum absolute values over the singleton dimensions of ``r``, and write values to ``r``. -.. function:: sum(itr) +.. function:: sum(f, itr) - :: - - sum(f, itr) - Sum the results of calling function ``f`` on each element of -.. function:: sum(A, dims) +.. function:: sum(f, itr) - :: - - sum(f, itr) - Sum the results of calling function ``f`` on each element of .. function:: sum!(r, A) - :: - - sum!(r, A) - Sum elements of ``A`` over the singleton dimensions of ``r``, and write results to ``r``. .. function:: sum(f, itr) - :: - - sum(f, itr) - Sum the results of calling function ``f`` on each element of -.. function:: sumabs(itr) +.. function:: sumabs(A, dims) - :: - - sumabs(A, dims) - Sum absolute values of elements of an array over the given dimensions. .. function:: sumabs(A, dims) - :: - - sumabs(A, dims) - Sum absolute values of elements of an array over the given dimensions. .. function:: sumabs!(r, A) - :: - - sumabs!(r, A) - Sum absolute values of elements of ``A`` over the singleton dimensions of ``r``, and write results to ``r``. -.. function:: sumabs2(itr) +.. function:: sumabs2(A, dims) - :: - - sumabs2(A, dims) - Sum squared absolute values of elements of an array over the given dimensions. .. function:: sumabs2(A, dims) - :: - - sumabs2(A, dims) - Sum squared absolute values of elements of an array over the given dimensions. .. function:: sumabs2!(r, A) - :: - - sumabs2!(r, A) - Sum squared absolute values of elements of ``A`` over the singleton dimensions of ``r``, and write results to ``r``. -.. function:: prod(itr) +.. function:: prod(A, dims) - :: - - prod(A, dims) - Multiply elements of an array over the given dimensions. .. function:: prod(A, dims) - :: - - prod(A, dims) - Multiply elements of an array over the given dimensions. .. function:: prod!(r, A) - :: - - prod!(r, A) - Multiply elements of ``A`` over the singleton dimensions of ``r``, and write results to ``r``. -.. function:: any(itr) -> Bool +.. function:: any(p, itr) -> Bool - :: - - any(p, itr) -> Bool - Determine whether predicate ``p`` returns true for any elements of -.. function:: any(A, dims) +.. function:: any(p, itr) -> Bool - :: - - any(p, itr) -> Bool - Determine whether predicate ``p`` returns true for any elements of .. function:: any!(r, A) - :: - - any!(r, A) - Test whether any values in ``A`` along the singleton dimensions of -.. function:: all(itr) -> Bool +.. function:: all(p, itr) -> Bool - :: - - all(p, itr) -> Bool - Determine whether predicate ``p`` returns true for all elements of -.. function:: all(A, dims) +.. function:: all(p, itr) -> Bool - :: - - all(p, itr) -> Bool - Determine whether predicate ``p`` returns true for all elements of .. function:: all!(r, A) - :: - - all!(r, A) - Test whether all values in ``A`` along the singleton dimensions of .. function:: count(p, itr) -> Integer - :: - - count(p, itr) -> Integer - Count the number of elements in ``itr`` for which predicate ``p`` returns true. .. function:: any(p, itr) -> Bool - :: - - any(p, itr) -> Bool - Determine whether predicate ``p`` returns true for any elements of .. function:: all(p, itr) -> Bool - :: - - all(p, itr) -> Bool - Determine whether predicate ``p`` returns true for all elements of .. function:: map(f, c...) -> collection - :: - - map(f, c...) -> collection - Transform collection ``c`` by applying ``f`` to each element. For multiple collection arguments, apply ``f`` elementwise. -.. function:: map!(function, collection) +.. function:: map!(function, destination, collection...) - :: - - map!(function, destination, collection...) - Like ``map()``, but stores the result in ``destination`` rather than a new collection. ``destination`` must be at least as large as the first collection. .. function:: map!(function, destination, collection...) - :: - - map!(function, destination, collection...) - Like ``map()``, but stores the result in ``destination`` rather than a new collection. ``destination`` must be at least as large as the first collection. -.. function:: mapreduce(f, op, v0, itr) +.. function:: mapreduce(f, op, itr) - :: - - mapreduce(f, op, itr) - Like ``mapreduce(f, op, v0, itr)``. In general, this cannot be used with empty collections (see ``reduce(op, itr)``). .. function:: mapreduce(f, op, itr) - :: - - mapreduce(f, op, itr) - Like ``mapreduce(f, op, v0, itr)``. In general, this cannot be used with empty collections (see ``reduce(op, itr)``). -.. function:: mapfoldl(f, op, v0, itr) +.. function:: mapfoldl(f, op, itr) - :: - - mapfoldl(f, op, itr) - Like ``mapfoldl(f, op, v0, itr)``, but using the first element of collections (see ``reduce(op, itr)``). .. function:: mapfoldl(f, op, itr) - :: - - mapfoldl(f, op, itr) - Like ``mapfoldl(f, op, v0, itr)``, but using the first element of collections (see ``reduce(op, itr)``). -.. function:: mapfoldr(f, op, v0, itr) +.. function:: mapfoldr(f, op, itr) - :: - - mapfoldr(f, op, itr) - Like ``mapfoldr(f, op, v0, itr)``, but using the first element of collections (see ``reduce(op, itr)``). .. function:: mapfoldr(f, op, itr) - :: - - mapfoldr(f, op, itr) - Like ``mapfoldr(f, op, v0, itr)``, but using the first element of collections (see ``reduce(op, itr)``). .. function:: first(coll) - :: - - first(coll) - Get the first element of an iterable collection. Returns the start point of a ``Range`` even if it is empty. .. function:: last(coll) - :: - - last(coll) - Get the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by calling ``endof()`` to get the last index. Returns the end point of a ``Range`` even if it is empty. .. function:: step(r) - :: - - step(r) - Get the step size of a ``Range`` object. -.. function:: collect(collection) +.. function:: collect(element_type, collection) - :: - - collect(element_type, collection) - Return an array of type ``Array{element_type,1}`` of all items in a collection. .. function:: collect(element_type, collection) - :: - - collect(element_type, collection) - Return an array of type ``Array{element_type,1}`` of all items in a collection. -.. function:: issubset(a, b) +.. function:: issubset(A, S) -> Bool - :: - - issubset(A, S) -> Bool - True if A is a subset of or equal to S. .. function:: filter(function, collection) - :: - - filter(function, collection) - Return a copy of ``collection``, removing elements for which passed two arguments (key and value). .. function:: filter!(function, collection) - :: - - filter!(function, collection) - Update ``collection``, removing elements for which ``function`` is false. For associative collections, the function is passed two arguments (key and value). @@ -821,19 +485,11 @@ Indexable Collections .. function:: getindex(collection, key...) - :: - - getindex(collection, key...) - Retrieve the value(s) stored at the given key or index within a collection. The syntax ``a[i,j,...]`` is converted by the compiler to ``getindex(a, i, j, ...)``. .. function:: setindex!(collection, value, key...) - :: - - setindex!(collection, value, key...) - Store the given value at the given key or index within a collection. The syntax ``a[i,j,...] = x`` is converted by the compiler to ``setindex!(a, x, i, j, ...)``. @@ -874,58 +530,34 @@ Given a dictionary ``D``, the syntax ``D[x]`` returns the value of key ``x`` (if .. function:: Dict([itr]) - :: - - Dict([itr]) - values of type ``V``. Given a single iterable argument, constructs a ``Dict`` whose key- value pairs are taken from 2-tuples ``(key,value)`` generated by the argument. Alternatively, a sequence of pair arguments may be passed. .. function:: haskey(collection, key) -> Bool - :: - - haskey(collection, key) -> Bool - Determine whether a collection has a mapping for a given key. -.. function:: get(collection, key, default) +.. function:: get(f::Function, collection, key) - :: - - get(f::Function, collection, key) - Return the value stored for the given key, or if no mapping for the key is present, return ``f()``. Use ``get!()`` to also store the default value in the dictionary. This is intended to be called using ``do`` block syntax: .. function:: get(f::Function, collection, key) - :: - - get(f::Function, collection, key) - Return the value stored for the given key, or if no mapping for the key is present, return ``f()``. Use ``get!()`` to also store the default value in the dictionary. This is intended to be called using ``do`` block syntax: time() end -.. function:: get!(collection, key, default) +.. function:: get!(f::Function, collection, key) - :: - - get!(f::Function, collection, key) - Return the value stored for the given key, or if no mapping for the key is present, store ``key => f()``, and return ``f()``. This is intended to be called using ``do`` block syntax: .. function:: get!(f::Function, collection, key) - :: - - get!(f::Function, collection, key) - Return the value stored for the given key, or if no mapping for the key is present, store ``key => f()``, and return ``f()``. This is intended to be called using ``do`` block syntax: @@ -934,73 +566,41 @@ Given a dictionary ``D``, the syntax ``D[x]`` returns the value of key ``x`` (if .. function:: getkey(collection, key, default) - :: - - getkey(collection, key, default) - Return the key matching argument ``key`` if one exists in .. function:: delete!(collection, key) - :: - - delete!(collection, key) - Delete the mapping for the given key in a collection, and return the collection. -.. function:: pop!(collection, key[, default]) +.. function:: pop!(collection) -> item - :: - - pop!(collection) -> item - Remove the last item in ``collection`` and return it. .. function:: keys(collection) - :: - - keys(collection) - Return an iterator over all keys in a collection. .. function:: values(collection) - :: - - values(collection) - Return an iterator over all values in a collection. .. function:: merge(collection, others...) - :: - - merge(collection, others...) - Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. .. function:: merge!(collection, others...) - :: - - merge!(collection, others...) - Update collection with pairs from the other collections .. function:: sizehint!(s, n) - :: - - sizehint!(s, n) - Suggest that collection ``s`` reserve capacity for at least ``n`` elements. This can improve performance. @@ -1023,136 +623,76 @@ Set-Like Collections .. function:: Set([itr]) - :: - - Set([itr]) - Construct a ``Set`` of the values generated by the given iterable object, or an empty set. Should be used instead of ``IntSet`` for sparse integer sets, or for sets of arbitrary objects. .. function:: IntSet([itr]) - :: - - IntSet([itr]) - Construct a sorted set of the integers generated by the given iterable object, or an empty set. Implemented as a bit string, and therefore designed for dense integer sets. Only non-negative integers can be stored. If the set will be sparse (for example holding a single very large integer), use ``Set`` instead. -.. function:: union(s1,s2...) +.. function:: union(s1, s2...) - :: - - union(s1, s2...) - Construct the union of two or more sets. Maintains order with arrays. .. function:: union!(s, iterable) - :: - - union!(s, iterable) - Union each element of ``iterable`` into set ``s`` in-place. -.. function:: intersect(s1,s2...) +.. function:: intersect(s1, s2...) - :: - - intersect(s1, s2...) - Construct the intersection of two or more sets. Maintains order and multiplicity of the first argument for arrays and ranges. -.. function:: setdiff(s1,s2) +.. function:: setdiff(s1, s2) - :: - - setdiff(s1, s2) - Construct the set of elements in ``s1`` but not ``s2``. Maintains order with arrays. Note that both arguments must be collections, and both will be iterated over. In particular, .. function:: setdiff!(s, iterable) - :: - - setdiff!(s, iterable) - Remove each element of ``iterable`` from set ``s`` in-place. -.. function:: symdiff(s1,s2...) +.. function:: symdiff(s1, s2...) - :: - - symdiff(s1, s2...) - Construct the symmetric difference of elements in the passed in sets or arrays. Maintains order with arrays. -.. function:: symdiff!(s, n) +.. function:: symdiff!(s1, s2) - :: - - symdiff!(s1, s2) - Construct the symmetric difference of sets ``s1`` and ``s2``, storing the result in ``s1``. -.. function:: symdiff!(s, itr) +.. function:: symdiff!(s1, s2) - :: - - symdiff!(s1, s2) - Construct the symmetric difference of sets ``s1`` and ``s2``, storing the result in ``s1``. .. function:: symdiff!(s1, s2) - :: - - symdiff!(s1, s2) - Construct the symmetric difference of sets ``s1`` and ``s2``, storing the result in ``s1``. .. function:: complement(s) - :: - - complement(s) - Returns the set-complement of ``IntSet`` ``s``. .. function:: complement!(s) - :: - - complement!(s) - Mutates ``IntSet`` ``s`` into its set-complement. .. function:: intersect!(s1, s2) - :: - - intersect!(s1, s2) - Intersects sets ``s1`` and ``s2`` and overwrites the set ``s1`` with the result. If needed, ``s1`` will be expanded to the size of .. function:: issubset(A, S) -> Bool - :: - - issubset(A, S) -> Bool - True if A is a subset of or equal to S. @@ -1170,109 +710,61 @@ Dequeues .. function:: push!(collection, items...) -> collection - :: - - push!(collection, items...) -> collection - Insert one or more ``items`` at the end of ``collection``. Use ``append!()`` to add all the elements of another collection to to ``append!([1, 2, 3], [4, 5, 6])``. .. function:: pop!(collection) -> item - :: - - pop!(collection) -> item - Remove the last item in ``collection`` and return it. .. function:: unshift!(collection, items...) -> collection - :: - - unshift!(collection, items...) -> collection - Insert one or more ``items`` at the beginning of ``collection``. .. function:: shift!(collection) -> item - :: - - shift!(collection) -> item - Remove the first ``item`` from ``collection``. .. function:: insert!(collection, index, item) - :: - - insert!(collection, index, item) - Insert an ``item`` into ``collection`` at the given ``index``. -.. function:: deleteat!(collection, index) +.. function:: deleteat!(collection, itr) - :: - - deleteat!(collection, itr) - Remove the items at the indices given by ``itr``, and return the modified ``collection``. Subsequent items are shifted to fill the resulting gap. ``itr`` must be sorted and unique. .. function:: deleteat!(collection, itr) - :: - - deleteat!(collection, itr) - Remove the items at the indices given by ``itr``, and return the modified ``collection``. Subsequent items are shifted to fill the resulting gap. ``itr`` must be sorted and unique. -.. function:: splice!(collection, index, [replacement]) -> item +.. function:: splice!(collection, range[, replacement]) -> items - :: - - splice!(collection, range[, replacement]) -> items - Remove items in the specified index range, and return a collection containing the removed items. Subsequent items are shifted down to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed items. To insert ``replacement`` before an index ``n`` without removing any items, use ``splice!(collection, n:n-1, replacement)``. -.. function:: splice!(collection, range, [replacement]) -> items +.. function:: splice!(collection, range[, replacement]) -> items - :: - - splice!(collection, range[, replacement]) -> items - Remove items in the specified index range, and return a collection containing the removed items. Subsequent items are shifted down to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed items. To insert ``replacement`` before an index ``n`` without removing any items, use ``splice!(collection, n:n-1, replacement)``. .. function:: resize!(collection, n) -> collection - :: - - resize!(collection, n) -> collection - Resize ``collection`` to contain ``n`` elements. If ``n`` is smaller than the current collection length, the first ``n`` elements will be retained. If ``n`` is larger, the new elements are not guaranteed to be initialized. .. function:: append!(collection, collection2) -> collection. - :: - - append!(collection, collection2) -> collection. - Add the elements of ``collection2`` to the end of ``collection``. Use ``push!()`` to add individual items to ``collection`` which are not already themselves in another collection. The result is of the preceding example is equivalent to ``push!([1, 2, 3], 4, 5, 6)``. .. function:: prepend!(collection, items) -> collection - :: - - prepend!(collection, items) -> collection - Insert the elements of ``items`` to the beginning of @@ -1291,39 +783,23 @@ a basic priority queue implementation allowing for arbitrary key and priority ty Multiple identical keys are not permitted, but the priority of existing keys can be changed efficiently. -.. function:: PriorityQueue(K, V, [ord]) +.. function:: PriorityQueue(K, V[, ord]) - :: - - PriorityQueue(K, V[, ord]) - Construct a new ``PriorityQueue``, with keys of type ``K`` and values/priorites of type ``V``. If an order is not given, the priority queue is min-ordered using the default comparison for .. function:: enqueue!(pq, k, v) - :: - - enqueue!(pq, k, v) - Insert the a key ``k`` into a priority queue ``pq`` with priority .. function:: dequeue!(pq) - :: - - dequeue!(pq) - Remove and return the lowest priority key from a priority queue. .. function:: peek(pq) - :: - - peek(pq) - Return the lowest priority key from a priority queue without removing that key from the queue. @@ -1357,48 +833,28 @@ lower level functions for performing binary heap operations on arrays. Each function takes an optional ordering argument. If not given, default ordering is used, so that elements popped from the heap are given in ascending order. -.. function:: heapify(v, [ord]) +.. function:: heapify(v[, ord]) - :: - - heapify(v[, ord]) - Return a new vector in binary heap order, optionally using the given ordering. -.. function:: heapify!(v, [ord]) +.. function:: heapify!(v[, ord]) - :: - - heapify!(v[, ord]) - In-place ``heapify()``. -.. function:: isheap(v, [ord]) +.. function:: isheap(v[, ord]) - :: - - isheap(v[, ord]) - Return true iff an array is heap-ordered according to the given order. -.. function:: heappush!(v, x, [ord]) +.. function:: heappush!(v, x[, ord]) - :: - - heappush!(v, x[, ord]) - Given a binary heap-ordered array, push a new element ``x``, preserving the heap property. For efficiency, this function does not check that the array is indeed heap-ordered. -.. function:: heappop!(v, [ord]) +.. function:: heappop!(v[, ord]) - :: - - heappop!(v[, ord]) - Given a binary heap-ordered array, remove and return the lowest ordered element. For efficiency, this function does not check that the array is indeed heap-ordered. diff --git a/doc/stdlib/dates.rst b/doc/stdlib/dates.rst index 24a7de2709efc..24260a383a1f0 100644 --- a/doc/stdlib/dates.rst +++ b/doc/stdlib/dates.rst @@ -47,48 +47,28 @@ to use all other ``Dates`` functions, you'll need to prefix each function call w alternatively, you could call ``using Dates`` to bring all exported functions into ``Main`` to be used without the ``Dates.`` prefix. -.. function:: DateTime(y, [m, d, h, mi, s, ms]) -> DateTime +.. function:: DateTime(dt::AbstractString, df::DateFormat) -> DateTime - :: - - DateTime(dt::AbstractString, df::DateFormat) -> DateTime - Similar form as above for parsing a ``DateTime``, but passes a more efficient if similarly formatted date strings will be parsed repeatedly to first create a ``DateFormat`` object then use this method for parsing. -.. function:: DateTime(periods::Period...) -> DateTime +.. function:: DateTime(dt::AbstractString, df::DateFormat) -> DateTime - :: - - DateTime(dt::AbstractString, df::DateFormat) -> DateTime - Similar form as above for parsing a ``DateTime``, but passes a more efficient if similarly formatted date strings will be parsed repeatedly to first create a ``DateFormat`` object then use this method for parsing. -.. function:: DateTime(f::Function, y[, m, d, h, mi, s]; step=Day(1), negate=false, limit=10000) -> DateTime +.. function:: DateTime(dt::AbstractString, df::DateFormat) -> DateTime - :: - - DateTime(dt::AbstractString, df::DateFormat) -> DateTime - Similar form as above for parsing a ``DateTime``, but passes a more efficient if similarly formatted date strings will be parsed repeatedly to first create a ``DateFormat`` object then use this method for parsing. -.. function:: DateTime(dt::Date) -> DateTime +.. function:: DateTime(dt::AbstractString, df::DateFormat) -> DateTime - :: - - DateTime(dt::AbstractString, df::DateFormat) -> DateTime - Similar form as above for parsing a ``DateTime``, but passes a more efficient if similarly formatted date strings will be parsed repeatedly to first create a ``DateFormat`` object then use this method for parsing. -.. function:: DateTime(dt::AbstractString, format::AbstractString; locale="english") -> DateTime +.. function:: DateTime(dt::AbstractString, df::DateFormat) -> DateTime - :: - - DateTime(dt::AbstractString, df::DateFormat) -> DateTime - Similar form as above for parsing a ``DateTime``, but passes a more efficient if similarly formatted date strings will be parsed repeatedly to first create a ``DateFormat`` object then use this method for parsing. @@ -98,91 +78,51 @@ alternatively, you could call ``using Dates`` to bring all exported functions in .. function:: DateTime(dt::AbstractString, df::DateFormat) -> DateTime - :: - - DateTime(dt::AbstractString, df::DateFormat) -> DateTime - Similar form as above for parsing a ``DateTime``, but passes a more efficient if similarly formatted date strings will be parsed repeatedly to first create a ``DateFormat`` object then use this method for parsing. -.. function:: Date(y, [m, d]) -> Date +.. function:: Date(dt::AbstractString, df::DateFormat) -> Date - :: - - Date(dt::AbstractString, df::DateFormat) -> Date - Parse a date from a date string ``dt`` using a ``DateFormat`` object ``df``. -.. function:: Date(period::Period...) -> Date +.. function:: Date(dt::AbstractString, df::DateFormat) -> Date - :: - - Date(dt::AbstractString, df::DateFormat) -> Date - Parse a date from a date string ``dt`` using a ``DateFormat`` object ``df``. -.. function:: Date(f::Function, y[, m]; step=Day(1), negate=false, limit=10000) -> Date +.. function:: Date(dt::AbstractString, df::DateFormat) -> Date - :: - - Date(dt::AbstractString, df::DateFormat) -> Date - Parse a date from a date string ``dt`` using a ``DateFormat`` object ``df``. -.. function:: Date(dt::DateTime) -> Date +.. function:: Date(dt::AbstractString, df::DateFormat) -> Date - :: - - Date(dt::AbstractString, df::DateFormat) -> Date - Parse a date from a date string ``dt`` using a ``DateFormat`` object ``df``. -.. function:: Date(dt::AbstractString, format::AbstractString; locale="english") -> Date +.. function:: Date(dt::AbstractString, df::DateFormat) -> Date - :: - - Date(dt::AbstractString, df::DateFormat) -> Date - Parse a date from a date string ``dt`` using a ``DateFormat`` object ``df``. .. function:: Date(dt::AbstractString, df::DateFormat) -> Date - :: - - Date(dt::AbstractString, df::DateFormat) -> Date - Parse a date from a date string ``dt`` using a ``DateFormat`` object ``df``. -.. function:: now() -> DateTime +.. function:: now(::Type{UTC}) -> DateTime - :: - - now(::Type{UTC}) -> DateTime - Returns a DateTime corresponding to the user's system time as UTC/GMT. .. function:: now(::Type{UTC}) -> DateTime - :: - - now(::Type{UTC}) -> DateTime - Returns a DateTime corresponding to the user's system time as UTC/GMT. .. function:: eps(::DateTime) -> Millisecond - :: - - eps(::DateTime) -> Millisecond - Returns ``Millisecond(1)`` for ``DateTime`` values and ``Day(1)`` for ``Date`` values. @@ -191,46 +131,26 @@ Accessor Functions .. function:: year(dt::TimeType) -> Int64 - :: - - year(dt::TimeType) -> Int64 - Return the field part of a Date or DateTime as an ``Int64``. -.. function:: Year(dt::TimeType) -> Year +.. function:: Year(v) - :: - - Year(v) - Construct a ``Period`` type with the given ``v`` value. Input must be losslessly convertible to an ``Int64``. .. function:: yearmonth(dt::TimeType) -> (Int64, Int64) - :: - - yearmonth(dt::TimeType) -> (Int64, Int64) - Simultaneously return the year and month parts of a Date or DateTime. .. function:: monthday(dt::TimeType) -> (Int64, Int64) - :: - - monthday(dt::TimeType) -> (Int64, Int64) - Simultaneously return the month and day parts of a Date or DateTime. .. function:: yearmonthday(dt::TimeType) -> (Int64, Int64, Int64) - :: - - yearmonthday(dt::TimeType) -> (Int64, Int64, Int64) - Simultaneously return the year, month, and day parts of a Date or DateTime. @@ -239,254 +159,143 @@ Query Functions .. function:: dayname(dt::TimeType; locale="english") -> AbstractString - :: - - dayname(dt::TimeType; locale="english") -> AbstractString - Return the full day name corresponding to the day of the week of the Date or DateTime in the given ``locale``. .. function:: dayabbr(dt::TimeType; locale="english") -> AbstractString - :: - - dayabbr(dt::TimeType; locale="english") -> AbstractString - Return the abbreviated name corresponding to the day of the week of the Date or DateTime in the given ``locale``. .. function:: dayofweek(dt::TimeType) -> Int64 - :: - - dayofweek(dt::TimeType) -> Int64 - Returns the day of the week as an ``Int64`` with ``1 = Monday, 2 = Tuesday, etc.``. .. function:: dayofweekofmonth(dt::TimeType) -> Int - :: - - dayofweekofmonth(dt::TimeType) -> Int - For the day of week of ``dt``, returns which number it is in etc.` In the range 1:5. .. function:: daysofweekinmonth(dt::TimeType) -> Int - :: - - daysofweekinmonth(dt::TimeType) -> Int - For the day of week of ``dt``, returns the total number of that day of the week in ``dt``'s month. Returns 4 or 5. Useful in temporal expressions for specifying the last day of a week in a month by including ``dayofweekofmonth(dt) == daysofweekinmonth(dt)`` in the adjuster function. .. function:: monthname(dt::TimeType; locale="english") -> AbstractString - :: - - monthname(dt::TimeType; locale="english") -> AbstractString - Return the full name of the month of the Date or DateTime in the given ``locale``. .. function:: monthabbr(dt::TimeType; locale="english") -> AbstractString - :: - - monthabbr(dt::TimeType; locale="english") -> AbstractString - Return the abbreviated month name of the Date or DateTime in the given ``locale``. .. function:: daysinmonth(dt::TimeType) -> Int - :: - - daysinmonth(dt::TimeType) -> Int - Returns the number of days in the month of ``dt``. Value will be 28, 29, 30, or 31. .. function:: isleapyear(dt::TimeType) -> Bool - :: - - isleapyear(dt::TimeType) -> Bool - Returns true if the year of ``dt`` is a leap year. .. function:: dayofyear(dt::TimeType) -> Int - :: - - dayofyear(dt::TimeType) -> Int - Returns the day of the year for ``dt`` with January 1st being day 1. .. function:: daysinyear(dt::TimeType) -> Int - :: - - daysinyear(dt::TimeType) -> Int - Returns 366 if the year of ``dt`` is a leap year, otherwise returns 365. .. function:: quarterofyear(dt::TimeType) -> Int - :: - - quarterofyear(dt::TimeType) -> Int - Returns the quarter that ``dt`` resides in. Range of value is 1:4. .. function:: dayofquarter(dt::TimeType) -> Int - :: - - dayofquarter(dt::TimeType) -> Int - Returns the day of the current quarter of ``dt``. Range of value is 1:92. Adjuster Functions ~~~~~~~~~~~~~~~~~~ -.. function:: trunc(dt::TimeType, ::Type{Period}) -> TimeType +.. function:: trunc([T], x[, digits[, base]]) - :: - - trunc([T], x[, digits[, base]]) .. function:: firstdayofweek(dt::TimeType) -> TimeType - :: - - firstdayofweek(dt::TimeType) -> TimeType - Adjusts ``dt`` to the Monday of its week. .. function:: lastdayofweek(dt::TimeType) -> TimeType - :: - - lastdayofweek(dt::TimeType) -> TimeType - Adjusts ``dt`` to the Sunday of its week. .. function:: firstdayofmonth(dt::TimeType) -> TimeType - :: - - firstdayofmonth(dt::TimeType) -> TimeType - Adjusts ``dt`` to the first day of its month. .. function:: lastdayofmonth(dt::TimeType) -> TimeType - :: - - lastdayofmonth(dt::TimeType) -> TimeType - Adjusts ``dt`` to the last day of its month. .. function:: firstdayofyear(dt::TimeType) -> TimeType - :: - - firstdayofyear(dt::TimeType) -> TimeType - Adjusts ``dt`` to the first day of its year. .. function:: lastdayofyear(dt::TimeType) -> TimeType - :: - - lastdayofyear(dt::TimeType) -> TimeType - Adjusts ``dt`` to the last day of its year. .. function:: firstdayofquarter(dt::TimeType) -> TimeType - :: - - firstdayofquarter(dt::TimeType) -> TimeType - Adjusts ``dt`` to the first day of its quarter. .. function:: lastdayofquarter(dt::TimeType) -> TimeType - :: - - lastdayofquarter(dt::TimeType) -> TimeType - Adjusts ``dt`` to the last day of its quarter. -.. function:: tonext(dt::TimeType,dow::Int;same::Bool=false) -> TimeType +.. function:: tonext(func::Function, dt::TimeType;step=Day(1), negate=false, limit=10000, same=false) -> TimeType - :: - - tonext(func::Function, dt::TimeType;step=Day(1), negate=false, limit=10000, same=false) -> TimeType - Adjusts ``dt`` by iterating at most ``limit`` iterations by a single ``TimeType`` argument and return a ``Bool``. ``same`` allows ``dt`` to be considered in satisfying ``func``. ``negate`` will make the adjustment process terminate when ``func`` returns false instead of true. -.. function:: toprev(dt::TimeType,dow::Int;same::Bool=false) -> TimeType +.. function:: toprev(func::Function, dt::TimeType;step=Day(-1), negate=false, limit=10000, same=false) -> TimeType - :: - - toprev(func::Function, dt::TimeType;step=Day(-1), negate=false, limit=10000, same=false) -> TimeType - Adjusts ``dt`` by iterating at most ``limit`` iterations by a single ``TimeType`` argument and return a ``Bool``. ``same`` allows ``dt`` to be considered in satisfying ``func``. ``negate`` will make the adjustment process terminate when ``func`` returns false instead of true. -.. function:: tofirst(dt::TimeType,dow::Int;of=Month) -> TimeType +.. function:: tofirst(dt::TimeType, dow::Int;of=Month) -> TimeType - :: - - tofirst(dt::TimeType, dow::Int;of=Month) -> TimeType - Adjusts ``dt`` to the first ``dow`` of its month. Alternatively, -.. function:: tolast(dt::TimeType,dow::Int;of=Month) -> TimeType +.. function:: tolast(dt::TimeType, dow::Int;of=Month) -> TimeType - :: - - tolast(dt::TimeType, dow::Int;of=Month) -> TimeType - Adjusts ``dt`` to the last ``dow`` of its month. Alternatively, -.. function:: tonext(func::Function,dt::TimeType;step=Day(1),negate=false,limit=10000,same=false) -> TimeType +.. function:: tonext(func::Function, dt::TimeType;step=Day(1), negate=false, limit=10000, same=false) -> TimeType - :: - - tonext(func::Function, dt::TimeType;step=Day(1), negate=false, limit=10000, same=false) -> TimeType - Adjusts ``dt`` by iterating at most ``limit`` iterations by a single ``TimeType`` argument and return a ``Bool``. ``same`` allows ``dt`` to be considered in satisfying ``func``. ``negate`` will make the adjustment process terminate when ``func`` returns false instead of true. -.. function:: toprev(func::Function,dt::TimeType;step=Day(-1),negate=false,limit=10000,same=false) -> TimeType +.. function:: toprev(func::Function, dt::TimeType;step=Day(-1), negate=false, limit=10000, same=false) -> TimeType - :: - - toprev(func::Function, dt::TimeType;step=Day(-1), negate=false, limit=10000, same=false) -> TimeType - Adjusts ``dt`` by iterating at most ``limit`` iterations by a single ``TimeType`` argument and return a ``Bool``. ``same`` allows ``dt`` to be considered in satisfying ``func``. ``negate`` will make the adjustment process terminate when ``func`` returns false instead of true. @@ -503,19 +312,11 @@ Periods .. function:: Year(v) - :: - - Year(v) - Construct a ``Period`` type with the given ``v`` value. Input must be losslessly convertible to an ``Int64``. .. function:: default(p::Period) -> Period - :: - - default(p::Period) -> Period - Returns a sensible ``default`` value for the input Period by returning ``one(p)`` for Year, Month, and Day, and ``zero(p)`` for Hour, Minute, Second, and Millisecond. @@ -524,64 +325,36 @@ Conversion Functions .. function:: today() -> Date - :: - - today() -> Date - Returns the date portion of ``now()``. .. function:: unix2datetime(x) -> DateTime - :: - - unix2datetime(x) -> DateTime - Takes the number of seconds since unix epoch .. function:: datetime2unix(dt::DateTime) -> Float64 - :: - - datetime2unix(dt::DateTime) -> Float64 - Takes the given DateTime and returns the number of seconds since the unix epoch as a ``Float64``. .. function:: julian2datetime(julian_days) -> DateTime - :: - - julian2datetime(julian_days) -> DateTime - Takes the number of Julian calendar days since epoch .. function:: datetime2julian(dt::DateTime) -> Float64 - :: - - datetime2julian(dt::DateTime) -> Float64 - Takes the given DateTime and returns the number of Julian calendar days since the julian epoch as a ``Float64``. .. function:: rata2datetime(days) -> DateTime - :: - - rata2datetime(days) -> DateTime - Takes the number of Rata Die days since epoch .. function:: datetime2rata(dt::TimeType) -> Int64 - :: - - datetime2rata(dt::TimeType) -> Int64 - Returns the number of Rata Die days since epoch from the given Date or DateTime. diff --git a/doc/stdlib/file.rst b/doc/stdlib/file.rst index f8d06def9cc77..6f47724d02aef 100644 --- a/doc/stdlib/file.rst +++ b/doc/stdlib/file.rst @@ -7,514 +7,286 @@ .. function:: pwd() -> AbstractString - :: - - pwd() -> AbstractString - Get the current working directory. -.. function:: cd(dir::AbstractString) +.. function:: cd(f[, dir]) - :: - - cd(f[, dir]) - Temporarily changes the current working directory (HOME if not specified) and applies function f before returning. -.. function:: cd(f, [dir]) +.. function:: cd(f[, dir]) - :: - - cd(f[, dir]) - Temporarily changes the current working directory (HOME if not specified) and applies function f before returning. .. function:: readdir([dir]) -> Vector{ByteString} - :: - - readdir([dir]) -> Vector{ByteString} - Returns the files and directories in the directory *dir* (or the current working directory if not given). -.. function:: mkdir(path, [mode]) +.. function:: mkdir(path[, mode]) - :: - - mkdir(path[, mode]) - Make a new directory with name ``path`` and permissions ``mode``. mask. -.. function:: mkpath(path, [mode]) +.. function:: mkpath(path[, mode]) - :: - - mkpath(path[, mode]) - Create all directories in the given ``path``, with permissions creation mask. .. function:: symlink(target, link) - :: - - symlink(target, link) - Creates a symbolic link to ``target`` with the name ``link``. Note: This function raises an error under operating systems that .. function:: readlink(path) -> AbstractString - :: - - readlink(path) -> AbstractString - Returns the value of a symbolic link ``path``. .. function:: chmod(path, mode) - :: - - chmod(path, mode) - Change the permissions mode of ``path`` to ``mode``. Only integer .. function:: stat(file) - :: - - stat(file) - Returns a structure whose fields contain information about the file. The fields of the structure are: .. function:: lstat(file) - :: - - lstat(file) - Like stat, but for symbolic links gets the info for the link itself rather than the file it refers to. This function must be called on a file path rather than a file object or a file descriptor. .. function:: ctime(file) - :: - - ctime(file) - Equivalent to stat(file).ctime .. function:: mtime(file) - :: - - mtime(file) - Equivalent to stat(file).mtime .. function:: filemode(file) - :: - - filemode(file) - Equivalent to stat(file).mode .. function:: filesize(path...) - :: - - filesize(path...) - Equivalent to stat(file).size .. function:: uperm(file) - :: - - uperm(file) - Gets the permissions of the owner of the file as a bitfield of For allowed arguments, see ``stat``. .. function:: gperm(file) - :: - - gperm(file) - Like uperm but gets the permissions of the group owning the file .. function:: operm(file) - :: - - operm(file) - Like uperm but gets the permissions for people who neither own the file nor are a member of the group owning the file .. function:: cp(src::AbstractString, dst::AbstractString; remove_destination::Bool=false, follow_symlinks::Bool=false) - :: - - cp(src::AbstractString, dst::AbstractString; remove_destination::Bool=false, follow_symlinks::Bool=false) - Copy the file, link, or directory from *src* to *dest*. If *follow_symlinks=false*, and src is a symbolic link, dst will be created as a symbolic link. If *follow_symlinks=true* and src is a symbolic link, dst will be a copy of the file or directory *src* refers to. -.. function:: download(url,[localfile]) +.. function:: download(url[, localfile]) - :: - - download(url[, localfile]) - Download a file from the given url, optionally renaming it to the given local file name. Note that this function relies on the availability of external tools such as ``curl``, ``wget`` or production use or situations in which more options are need, please use a package that provides the desired functionality instead. -.. function:: mv(src::AbstractString,dst::AbstractString; remove_destination::Bool=false) +.. function:: mv(src::AbstractString, dst::AbstractString; remove_destination::Bool=false) - :: - - mv(src::AbstractString, dst::AbstractString; remove_destination::Bool=false) - Move the file, link, or directory from *src* to *dest*. .. function:: rm(path::AbstractString; recursive=false) - :: - - rm(path::AbstractString; recursive=false) - Delete the file, link, or empty directory at the given path. If contents are removed recursively. .. function:: touch(path::AbstractString) - :: - - touch(path::AbstractString) - Update the last-modified timestamp on a file to the current time. .. function:: tempname() - :: - - tempname() - Generate a unique temporary file path. .. function:: tempdir() - :: - - tempdir() - Obtain the path of a temporary directory (possibly shared with other processes). .. function:: mktemp([parent=tempdir()]) - :: - - mktemp([parent=tempdir()]) - Returns ``(path, io)``, where ``path`` is the path of a new temporary file in ``parent`` and ``io`` is an open file object for this path. .. function:: mktempdir([parent=tempdir()]) - :: - - mktempdir([parent=tempdir()]) - Create a temporary directory in the ``parent`` directory and return its path. .. function:: isblockdev(path) -> Bool - :: - - isblockdev(path) -> Bool - Returns ``true`` if ``path`` is a block device, ``false`` otherwise. .. function:: ischardev(path) -> Bool - :: - - ischardev(path) -> Bool - Returns ``true`` if ``path`` is a character device, ``false`` otherwise. .. function:: isdir(path) -> Bool - :: - - isdir(path) -> Bool - Returns ``true`` if ``path`` is a directory, ``false`` otherwise. .. function:: isexecutable(path) -> Bool - :: - - isexecutable(path) -> Bool - Returns ``true`` if the current user has permission to execute .. function:: isfifo(path) -> Bool - :: - - isfifo(path) -> Bool - Returns ``true`` if ``path`` is a FIFO, ``false`` otherwise. .. function:: isfile(path) -> Bool - :: - - isfile(path) -> Bool - Returns ``true`` if ``path`` is a regular file, ``false`` otherwise. .. function:: islink(path) -> Bool - :: - - islink(path) -> Bool - Returns ``true`` if ``path`` is a symbolic link, ``false`` otherwise. .. function:: ismount(path) -> Bool - :: - - ismount(path) -> Bool - Returns ``true`` if ``path`` is a mount point, ``false`` otherwise. .. function:: ispath(path) -> Bool - :: - - ispath(path) -> Bool - Returns ``true`` if ``path`` is a valid filesystem path, ``false`` otherwise. .. function:: isreadable(path) -> Bool - :: - - isreadable(path) -> Bool - Returns ``true`` if the current user has permission to read .. function:: issetgid(path) -> Bool - :: - - issetgid(path) -> Bool - Returns ``true`` if ``path`` has the setgid flag set, ``false`` otherwise. .. function:: issetuid(path) -> Bool - :: - - issetuid(path) -> Bool - Returns ``true`` if ``path`` has the setuid flag set, ``false`` otherwise. .. function:: issocket(path) -> Bool - :: - - issocket(path) -> Bool - Returns ``true`` if ``path`` is a socket, ``false`` otherwise. .. function:: issticky(path) -> Bool - :: - - issticky(path) -> Bool - Returns ``true`` if ``path`` has the sticky bit set, ``false`` otherwise. .. function:: iswritable(path) -> Bool - :: - - iswritable(path) -> Bool - Returns ``true`` if the current user has permission to write to .. function:: homedir() -> AbstractString - :: - - homedir() -> AbstractString - Return the current user's home directory. .. function:: dirname(path::AbstractString) -> AbstractString - :: - - dirname(path::AbstractString) -> AbstractString - Get the directory part of a path. .. function:: basename(path::AbstractString) -> AbstractString - :: - - basename(path::AbstractString) -> AbstractString - Get the file name part of a path. .. function:: @__FILE__() -> AbstractString - :: - - @__FILE__() -> AbstractString - name of the script being run. Returns ``nothing`` if run from a REPL or an empty string if evaluated by ``julia -e ``. .. function:: isabspath(path::AbstractString) -> Bool - :: - - isabspath(path::AbstractString) -> Bool - Determines whether a path is absolute (begins at the root directory). .. function:: isdirpath(path::AbstractString) -> Bool - :: - - isdirpath(path::AbstractString) -> Bool - Determines whether a path refers to a directory (for example, ends with a path separator). .. function:: joinpath(parts...) -> AbstractString - :: - - joinpath(parts...) -> AbstractString - Join path components into a full path. If some argument is an absolute path, then prior components are dropped. .. function:: abspath(path::AbstractString) -> AbstractString - :: - - abspath(path::AbstractString) -> AbstractString - Convert a path to an absolute path by adding the current directory if necessary. .. function:: normpath(path::AbstractString) -> AbstractString - :: - - normpath(path::AbstractString) -> AbstractString - Normalize a path, removing ``.`` and ``..`` entries. .. function:: realpath(path::AbstractString) -> AbstractString - :: - - realpath(path::AbstractString) -> AbstractString - Canonicalize a path by expanding symbolic links and removing ``.`` and ``..`` entries. .. function:: relpath(path::AbstractString, startpath::AbstractString = ".") -> AbstractString - :: - - relpath(path::AbstractString, startpath::AbstractString = ".") -> AbstractString - Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or startpath. .. function:: expanduser(path::AbstractString) -> AbstractString - :: - - expanduser(path::AbstractString) -> AbstractString - On Unix systems, replace a tilde character at the start of a path with the current user's home directory. -.. function:: splitdir(path::AbstractString) -> (AbstractString,AbstractString) +.. function:: splitdir(path::AbstractString) -> (AbstractString, AbstractString) - :: - - splitdir(path::AbstractString) -> (AbstractString, AbstractString) - Split a path into a tuple of the directory name and file name. -.. function:: splitdrive(path::AbstractString) -> (AbstractString,AbstractString) +.. function:: splitdrive(path::AbstractString) -> (AbstractString, AbstractString) - :: - - splitdrive(path::AbstractString) -> (AbstractString, AbstractString) - On Windows, split a path into the drive letter part and the path part. On Unix systems, the first component is always the empty string. -.. function:: splitext(path::AbstractString) -> (AbstractString,AbstractString) +.. function:: splitext(path::AbstractString) -> (AbstractString, AbstractString) - :: - - splitext(path::AbstractString) -> (AbstractString, AbstractString) - If the last component of a path contains a dot, split the path into everything before the dot and everything including and after the dot. Otherwise, return a tuple of the argument unmodified and the empty string. diff --git a/doc/stdlib/io-network.rst b/doc/stdlib/io-network.rst index 26bb221bd7cbe..422475070152f 100644 --- a/doc/stdlib/io-network.rst +++ b/doc/stdlib/io-network.rst @@ -19,435 +19,243 @@ General I/O Global variable referring to the standard input stream. -.. function:: open(file_name, [read, write, create, truncate, append]) -> IOStream +.. function:: open(f::function, args...) - :: - - open(f::function, args...) - Apply the function ``f`` to the result of ``open(args...)`` and close the resulting file descriptor upon completion. -.. function:: open(file_name, [mode]) -> IOStream +.. function:: open(f::function, args...) - :: - - open(f::function, args...) - Apply the function ``f`` to the result of ``open(args...)`` and close the resulting file descriptor upon completion. .. function:: open(f::function, args...) - :: - - open(f::function, args...) - Apply the function ``f`` to the result of ``open(args...)`` and close the resulting file descriptor upon completion. -.. function:: IOBuffer() -> IOBuffer +.. function:: IOBuffer([data][, readable, writable[, maxsize]]) - :: - - IOBuffer([data][, readable, writable[, maxsize]]) - Create an IOBuffer, which may optionally operate on a pre-existing array. If the readable/writable arguments are given, they restrict whether or not the buffer may be read from or written to respectively. By default the buffer is readable but not writable. The last argument optionally specifies a size beyond which the buffer may not be grown. -.. function:: IOBuffer(size::Int) +.. function:: IOBuffer([data][, readable, writable[, maxsize]]) - :: - - IOBuffer([data][, readable, writable[, maxsize]]) - Create an IOBuffer, which may optionally operate on a pre-existing array. If the readable/writable arguments are given, they restrict whether or not the buffer may be read from or written to respectively. By default the buffer is readable but not writable. The last argument optionally specifies a size beyond which the buffer may not be grown. -.. function:: IOBuffer(string) +.. function:: IOBuffer([data][, readable, writable[, maxsize]]) - :: - - IOBuffer([data][, readable, writable[, maxsize]]) - Create an IOBuffer, which may optionally operate on a pre-existing array. If the readable/writable arguments are given, they restrict whether or not the buffer may be read from or written to respectively. By default the buffer is readable but not writable. The last argument optionally specifies a size beyond which the buffer may not be grown. -.. function:: IOBuffer([data,],[readable,writable,[maxsize]]) +.. function:: IOBuffer([data][, readable, writable[, maxsize]]) - :: - - IOBuffer([data][, readable, writable[, maxsize]]) - Create an IOBuffer, which may optionally operate on a pre-existing array. If the readable/writable arguments are given, they restrict whether or not the buffer may be read from or written to respectively. By default the buffer is readable but not writable. The last argument optionally specifies a size beyond which the buffer may not be grown. .. function:: takebuf_array(b::IOBuffer) - :: - - takebuf_array(b::IOBuffer) - Obtain the contents of an ``IOBuffer`` as an array, without copying. Afterwards, the IOBuffer is reset to its initial state. .. function:: takebuf_string(b::IOBuffer) - :: - - takebuf_string(b::IOBuffer) - Obtain the contents of an ``IOBuffer`` as a string, without copying. Afterwards, the IOBuffer is reset to its initial state. -.. function:: fdio([name::AbstractString, ]fd::Integer[, own::Bool]) -> IOStream +.. function:: fdio([name::AbstractString], fd::Integer[, own::Bool]) -> IOStream - :: - - fdio([name::AbstractString], fd::Integer[, own::Bool]) -> IOStream - Create an ``IOStream`` object from an integer file descriptor. If descriptor. By default, an ``IOStream`` is closed when it is garbage collected. ``name`` allows you to associate the descriptor with a named file. .. function:: flush(stream) - :: - - flush(stream) - Commit all currently buffered writes to the given stream. .. function:: close(stream) - :: - - close(stream) - Close an I/O stream. Performs a ``flush`` first. .. function:: write(stream, x) - :: - - write(stream, x) - Write the canonical binary representation of a value to the given stream. -.. function:: read(stream, type) +.. function:: read(stream, type, dims) - :: - - read(stream, type, dims) - Read a series of values of the given type from a stream, in canonical binary representation. ``dims`` is either a tuple or a series of integer arguments specifying the size of ``Array`` to return. .. function:: read(stream, type, dims) - :: - - read(stream, type, dims) - Read a series of values of the given type from a stream, in canonical binary representation. ``dims`` is either a tuple or a series of integer arguments specifying the size of ``Array`` to return. .. function:: read!(stream, array::Array) - :: - - read!(stream, array::Array) - Read binary data from a stream, filling in the argument ``array``. .. function:: readbytes!(stream, b::Vector{UInt8}, nb=length(b)) - :: - - readbytes!(stream, b::Vector{UInt8}, nb=length(b)) - Read at most ``nb`` bytes from the stream into ``b``, returning the number of bytes read (increasing the size of ``b`` as needed). .. function:: readbytes(stream, nb=typemax(Int)) - :: - - readbytes(stream, nb=typemax(Int)) - Read at most ``nb`` bytes from the stream, returning a .. function:: position(s) - :: - - position(s) - Get the current position of a stream. .. function:: seek(s, pos) - :: - - seek(s, pos) - Seek a stream to the given position. .. function:: seekstart(s) - :: - - seekstart(s) - Seek a stream to its beginning. .. function:: seekend(s) - :: - - seekend(s) - Seek a stream to its end. .. function:: skip(s, offset) - :: - - skip(s, offset) - Seek a stream relative to the current position. .. function:: mark(s) - :: - - mark(s) - Add a mark at the current position of stream ``s``. Returns the marked position. See also ``unmark()``, ``reset()``, ``ismarked()`` .. function:: unmark(s) - :: - - unmark(s) - Remove a mark from stream ``s``. Returns ``true`` if the stream was marked, ``false`` otherwise. See also ``mark()``, ``reset()``, ``ismarked()`` .. function:: reset(s) - :: - - reset(s) - Reset a stream ``s`` to a previously marked position, and remove the mark. Returns the previously marked position. Throws an error if the stream is not marked. See also ``mark()``, ``unmark()``, ``ismarked()`` .. function:: ismarked(s) - :: - - ismarked(s) - Returns true if stream ``s`` is marked. See also ``mark()``, ``unmark()``, ``reset()`` .. function:: eof(stream) -> Bool - :: - - eof(stream) -> Bool - Tests whether an I/O stream is at end-of-file. If the stream is not yet exhausted, this function will block to wait for more data if necessary, and then return ``false``. Therefore it is always safe to read one byte after seeing ``eof`` return ``false``. ``eof`` will return ``false`` as long as buffered data is still available, even if the remote end of a connection is closed. .. function:: isreadonly(stream) -> Bool - :: - - isreadonly(stream) -> Bool - Determine whether a stream is read-only. .. function:: isopen(stream) -> Bool - :: - - isopen(stream) -> Bool - Determine whether a stream is open (i.e. has not been closed yet). If the connection has been closed remotely (in case of e.g. a socket), ``isopen`` will return ``false`` even though buffered data may still be available. Use ``eof`` to check if necessary. .. function:: serialize(stream, value) - :: - - serialize(stream, value) - Write an arbitrary value to a stream in an opaque format, such that it can be read back by ``deserialize``. The read-back value will be as identical as possible to the original. In general, this process will not work if the reading and writing are done by different versions of Julia, or an instance of Julia with a different system image. .. function:: deserialize(stream) - :: - - deserialize(stream) - Read a value written by ``serialize``. .. function:: print_escaped(io, str::AbstractString, esc::AbstractString) - :: - - print_escaped(io, str::AbstractString, esc::AbstractString) - General escaping of traditional C and Unicode escape sequences, plus any characters in esc are also escaped (with a backslash). .. function:: print_unescaped(io, s::AbstractString) - :: - - print_unescaped(io, s::AbstractString) - General unescaping of traditional C and Unicode escape sequences. Reverse of ``print_escaped()``. -.. function:: print_joined(io, items, delim, [last]) +.. function:: print_joined(io, items, delim[, last]) - :: - - print_joined(io, items, delim[, last]) - Print elements of ``items`` to ``io`` with ``delim`` between them. If ``last`` is specified, it is used as the final delimiter instead of ``delim``. .. function:: print_shortest(io, x) - :: - - print_shortest(io, x) - Print the shortest possible representation, with the minimum number of consecutive non-zero digits, of number ``x``, ensuring that it would parse to the exact same number. .. function:: fd(stream) - :: - - fd(stream) - Returns the file descriptor backing the stream or file. Note that this function only applies to synchronous *File*'s and *IOStream*'s not to any of the asynchronous streams. -.. function:: redirect_stdout() +.. function:: redirect_stdout(stream) - :: - - redirect_stdout(stream) - Replace STDOUT by stream for all C and julia level output to STDOUT. Note that *stream* must be a TTY, a Pipe or a TcpSocket. .. function:: redirect_stdout(stream) - :: - - redirect_stdout(stream) - Replace STDOUT by stream for all C and julia level output to STDOUT. Note that *stream* must be a TTY, a Pipe or a TcpSocket. .. function:: redirect_stderr([stream]) - :: - - redirect_stderr([stream]) - Like redirect_stdout, but for STDERR .. function:: redirect_stdin([stream]) - :: - - redirect_stdin([stream]) - Like redirect_stdout, but for STDIN. Note that the order of the return tuple is still (rd,wr), i.e. data to be read from STDIN, may be written to wr. .. function:: readchomp(x) - :: - - readchomp(x) - Read the entirety of x as a string but remove trailing newlines. Equivalent to chomp(readall(x)). -.. function:: truncate(file,n) +.. function:: truncate(file, n) - :: - - truncate(file, n) - Resize the file or buffer given by the first argument to exactly file or buffer is grown .. function:: skipchars(stream, predicate; linecomment::Char) - :: - - skipchars(stream, predicate; linecomment::Char) - Advance the stream until before the first character for which isspace)` will skip all whitespace. If keyword argument through the end of a line will also be skipped. -.. function:: countlines(io,[eol::Char]) +.. function:: countlines(io[, eol::Char]) - :: - - countlines(io[, eol::Char]) - Read io until the end of the stream/file and count the number of non-empty lines. To specify a file pass the filename as the first argument. EOL markers other than '\n' are supported by passing them as the second argument. -.. function:: PipeBuffer() +.. function:: PipeBuffer(data::Vector{UInt8}[, maxsize]) - :: - - PipeBuffer(data::Vector{UInt8}[, maxsize]) - Create a PipeBuffer to operate on a data vector, optionally specifying a size beyond which the underlying Array may not be grown. -.. function:: PipeBuffer(data::Vector{UInt8},[maxsize]) +.. function:: PipeBuffer(data::Vector{UInt8}[, maxsize]) - :: - - PipeBuffer(data::Vector{UInt8}[, maxsize]) - Create a PipeBuffer to operate on a data vector, optionally specifying a size beyond which the underlying Array may not be grown. .. function:: readavailable(stream) - :: - - readavailable(stream) - Read all available data on the stream, blocking the task only if no data is available. The result is a ``Vector{UInt8,1}``. @@ -456,307 +264,171 @@ Text I/O .. function:: show(x) - :: - - show(x) - Write an informative text representation of a value to the current output stream. New types should overload ``show(io, x)`` where the first argument is a stream. The representation used by ``show`` generally includes Julia-specific formatting and type information. .. function:: showcompact(x) - :: - - showcompact(x) - Show a more compact representation of a value. This is used for printing array elements. If a new type has a different compact representation, it should overload ``showcompact(io, x)`` where the first argument is a stream. .. function:: showall(x) - :: - - showall(x) - Similar to ``show``, except shows all elements of arrays. .. function:: summary(x) - :: - - summary(x) - Return a string giving a brief description of a value. By default returns ``string(typeof(x))``. For arrays, returns strings like .. function:: print(x) - :: - - print(x) - Write (to the default output stream) a canonical (un-decorated) text representation of a value if there is one, otherwise call formatting and tries to avoid Julia-specific details. .. function:: println(x) - :: - - println(x) - Print (using ``print()``) ``x`` followed by a newline. -.. function:: print_with_color(color::Symbol, [io], strings...) +.. function:: print_with_color(color::Symbol[, io], strings...) - :: - - print_with_color(color::Symbol[, io], strings...) - Print strings in a color specified as a symbol, for example .. function:: info(msg) - :: - - info(msg) - Display an informational message. .. function:: warn(msg) - :: - - warn(msg) - Display a warning. .. function:: @printf([io::IOStream], "%Fmt", args...) - :: - - @printf([io::IOStream], "%Fmt", args...) - Print arg(s) using C ``printf()`` style format specification string. Optionally, an IOStream may be passed as the first argument to redirect output. .. function:: @sprintf("%Fmt", args...) - :: - - @sprintf("%Fmt", args...) - Return ``@printf`` formatted output as string. .. function:: sprint(f::Function, args...) - :: - - sprint(f::Function, args...) - Call the given function with an I/O stream and the supplied extra arguments. Everything written to this I/O stream is returned as a string. .. function:: showerror(io, e) - :: - - showerror(io, e) - Show a descriptive representation of an exception object. .. function:: dump(x) - :: - - dump(x) - Show all user-visible structure of a value. .. function:: xdump(x) - :: - - xdump(x) - Show all structure of a value, including all fields of objects. -.. function:: readall(stream::IO) +.. function:: readall(filename::AbstractString) - :: - - readall(filename::AbstractString) - Open ``filename``, read the entire contents as a string, then close the file. Equivalent to ``open(readall, filename)``. .. function:: readall(filename::AbstractString) - :: - - readall(filename::AbstractString) - Open ``filename``, read the entire contents as a string, then close the file. Equivalent to ``open(readall, filename)``. .. function:: readline(stream=STDIN) - :: - - readline(stream=STDIN) - Read a single line of text, including a trailing newline character .. function:: readuntil(stream, delim) - :: - - readuntil(stream, delim) - Read a string, up to and including the given delimiter byte. .. function:: readlines(stream) - :: - - readlines(stream) - Read all lines as an array. .. function:: eachline(stream) - :: - - eachline(stream) - Create an iterable object that will yield each line from a stream. -.. function:: readdlm(source, delim::Char, T::Type, eol::Char; header=false, skipstart=0, skipblanks=true, use_mmap, ignore_invalid_chars=false, quotes=true, dims, comments=true, comment_char='#') +.. function:: readdlm(source; options...) - :: - - readdlm(source; options...) - The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as ``\n``. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned. -.. function:: readdlm(source, delim::Char, eol::Char; options...) +.. function:: readdlm(source; options...) - :: - - readdlm(source; options...) - The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as ``\n``. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned. -.. function:: readdlm(source, delim::Char, T::Type; options...) +.. function:: readdlm(source; options...) - :: - - readdlm(source; options...) - The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as ``\n``. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned. -.. function:: readdlm(source, delim::Char; options...) +.. function:: readdlm(source; options...) - :: - - readdlm(source; options...) - The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as ``\n``. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned. -.. function:: readdlm(source, T::Type; options...) +.. function:: readdlm(source; options...) - :: - - readdlm(source; options...) - The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as ``\n``. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned. .. function:: readdlm(source; options...) - :: - - readdlm(source; options...) - The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as ``\n``. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a cell array of numbers and strings is returned. -.. function:: writedlm(f, A, delim='\\t') +.. function:: writedlm(f, A, delim='\t') - :: - - writedlm(f, A, delim='\t') - Write ``A`` (a vector, matrix or an iterable collection of iterable rows) as text to ``f`` (either a filename string or an ``IO`` stream) using the given delimeter ``delim`` (which defaults to tab, but can be any printable Julia object, typically a ``Char`` or For example, two vectors ``x`` and ``y`` of the same length can be written as two columns of tab-delimited text to ``f`` by either .. function:: readcsv(source, [T::Type]; options...) - :: - - readcsv(source, [T::Type]; options...) - Equivalent to ``readdlm`` with ``delim`` set to comma. .. function:: writecsv(filename, A) - :: - - writecsv(filename, A) - Equivalent to ``writedlm`` with ``delim`` set to comma. .. function:: Base64EncodePipe(ostream) - :: - - Base64EncodePipe(ostream) - Returns a new write-only I/O stream, which converts any bytes written to it into base64-encoded ASCII bytes written to necessary to complete the encoding (but does not close .. function:: Base64DecodePipe(istream) - :: - - Base64DecodePipe(istream) - Returns a new read-only I/O stream, which decodes base64-encoded data read from ``istream``. .. function:: base64encode(writefunc, args...) - :: - - base64encode(writefunc, args...) - Given a ``write``-like function ``writefunc``, which takes an I/O stream as its first argument, ``base64(writefunc, args...)`` calls returns the string. ``base64(args...)`` is equivalent to using the standard ``write`` functions and returns the base64-encoded string. .. function:: base64decode(string) - :: - - base64decode(string) - Decodes the base64-encoded ``string`` and returns a @@ -783,64 +455,36 @@ Julia environments (such as the IPython-based IJulia notebook). .. function:: display(x) - :: - - display(x) - Display ``x`` using the topmost applicable display in the display stack, typically using the richest supported multimedia output for display ``d`` only, throwing a ``MethodError`` if ``d`` cannot display objects of this type. There are also two variants with a ``mime`` argument (a MIME type string, such as ``image/png``), which attempt to display ``x`` using the requested MIME type *only*, throwing a ``MethodError`` if this type is not supported by either the display(s) or by ``x``. With these variants, one can also supply the ``raw`` data in the requested MIME type by passing ``x::AbstractString`` (for MIME types with text-based storage, such as text/html or application/postscript) or ``x::Vector{UInt8}`` (for binary MIME types). .. function:: redisplay(x) - :: - - redisplay(x) - By default, the ``redisplay`` functions simply call ``display``. However, some display backends may override ``redisplay`` to modify an existing display of ``x`` (if any). Using ``redisplay`` is also a hint to the backend that ``x`` may be redisplayed several times, and the backend may choose to defer the display until (for example) the next interactive prompt. .. function:: displayable(mime) -> Bool - :: - - displayable(mime) -> Bool - Returns a boolean value indicating whether the given ``mime`` type display stack, or specifically by the display ``d`` in the second variant. .. function:: writemime(stream, mime, x) - :: - - writemime(stream, mime, x) - - The ``display`` functions ultimately call ``writemime`` in order to write an object ``x`` as a given ``mime`` type to a given I/O provide a rich multimedia representation of a user-defined type for ``T``, via: ``writemime(stream, ::MIME``mime``, x::T) = ...``, where ``mime`` is a MIME-type string and the function body calls literal strings; to construct ``MIME`` types in a more flexible manner use ``MIME{symbol(``)}``.) For example, if you define a ``MyImage`` type and know how to write it to a PNG file, you could define a function ``writemime(stream, be displayed on any PNG-capable `Display`` (such as IJulia). As usual, be sure to ``import Base.writemime`` in order to add new methods to the built-in Julia function ``writemime``. Technically, the ``MIME``mime`` macro defines a singleton type for the given ``mime`` string, which allows us to exploit Julia's dispatch mechanisms in determining how to display objects of any given type. + The ``display`` functions ultimately call ``writemime`` in order to write an object ``x`` as a given ``mime`` type to a given I/O provide a rich multimedia representation of a user-defined type for ``T``, via: ``writemime(stream, ::MIME"mime", x::T) = ...``, where ``mime`` is a MIME-type string and the function body calls literal strings; to construct ``MIME`` types in a more flexible manner use ``MIME{symbol("")}``.) For example, if you define a ``MyImage`` type and know how to write it to a PNG file, you could define a function ``writemime(stream, be displayed on any PNG-capable `Display`` (such as IJulia). As usual, be sure to ``import Base.writemime`` in order to add new methods to the built-in Julia function ``writemime``. Technically, the ``MIME"mime"`` macro defines a singleton type for the given ``mime`` string, which allows us to exploit Julia's dispatch mechanisms in determining how to display objects of any given type. .. function:: mimewritable(mime, x) - :: - - mimewritable(mime, x) - Returns a boolean value indicating whether or not the object ``x`` can be written as the given ``mime`` type. (By default, this is determined automatically by the existence of the corresponding .. function:: reprmime(mime, x) - :: - - reprmime(mime, x) - Returns an ``AbstractString`` or ``Vector{UInt8}`` containing the representation of ``x`` in the requested ``mime`` type, as written by ``writemime`` (throwing a ``MethodError`` if no appropriate MIME types with textual representations (such as ``text/html`` or ``application/postscript``), whereas binary data is returned as ``Vector{UInt8}``. (The function ``istext(mime)`` returns whether or not Julia treats a given ``mime`` type as text.) As a special case, if ``x`` is an ``AbstractString`` (for textual MIME types) or a ``Vector{UInt8}`` (for binary MIME types), the requested ``mime`` format and simply returns ``x``. .. function:: stringmime(mime, x) - :: - - stringmime(mime, x) - Returns an ``AbstractString`` containing the representation of string. @@ -872,277 +516,157 @@ stack with: .. function:: pushdisplay(d::Display) - :: - - pushdisplay(d::Display) - Pushes a new display ``d`` on top of the global display-backend stack. Calling ``display(x)`` or ``display(mime, x)`` will display topmost backend that does not throw a ``MethodError``). .. function:: popdisplay() - :: - - popdisplay() - Pop the topmost backend off of the display-backend stack, or the topmost copy of ``d`` in the second variant. .. function:: TextDisplay(stream) - :: - - TextDisplay(stream) - Returns a ``TextDisplay <: Display``, which can display any object as the text/plain MIME type (only), writing the text representation to the given I/O stream. (The text representation is the same as the way an object is printed in the Julia REPL.) .. function:: istext(m::MIME) - :: - - istext(m::MIME) - Determine whether a MIME type is text data. Memory-mapped I/O ----------------- -.. function:: mmap_array(type, dims, stream, [offset]) +.. function:: mmap_array(type, dims, stream[, offset]) - :: - - mmap_array(type, dims, stream[, offset]) - Create an ``Array`` whose values are linked to a file, using memory-mapping. This provides a convenient way of working with data too large to fit in the computer's memory. The type determines how the bytes of the array are interpreted. Note that the file must be stored in binary format, and no format conversions are possible (this is a limitation of operating systems, not Julia). The file is passed via the stream argument. When you initialize the stream, use ``r`` for a ``read-only`` array, and ``w+`` to create a new array used to write values to disk. Optionally, you can specify an offset (in bytes) if, for example, you want to skip over a header in the file. The default value for the offset is the current stream position. For example, the following code: creates a ``m``-by-``n`` ``Matrix{Int}``, linked to the file associated with stream ``s``. A more portable file would need to encode the word size–-32 bit or 64 bit–-and endianness information in the header. In practice, consider encoding binary data using standard formats like HDF5 -.. function:: mmap_bitarray([type,] dims, stream, [offset]) +.. function:: mmap_bitarray([type], dims, stream[, offset]) - :: - - mmap_bitarray([type], dims, stream[, offset]) - Create a ``BitArray`` whose values are linked to a file, using memory-mapping; it has the same purpose, works in the same way, and has the same arguments, as ``mmap_array()``, but the byte representation is different. The ``type`` parameter is optional, and must be ``Bool`` if given. This would create a 25-by-30000 ``BitArray``, linked to the file associated with stream ``s``. -.. function:: msync(array) +.. function:: msync(ptr, len[, flags]) - :: - - msync(ptr, len[, flags]) - Forces synchronization of the ``mmap()``ped memory region from combination of ``MS_ASYNC``, ``MS_SYNC``, or ``MS_INVALIDATE``. See your platform man page for specifics. The flags argument is not valid on Windows. You may not need to call ``msync``, because synchronization is performed at intervals automatically by the operating system. However, you can call this directly if, for example, you are concerned about losing the result of a long-running calculation. Network I/O ----------- -.. function:: connect([host],port) -> TcpSocket +.. function:: connect(manager::FooManager, pid::Int, config::WorkerConfig) -> (instrm::AsyncStream, outstrm::AsyncStream) - :: - - connect(manager::FooManager, pid::Int, config::WorkerConfig) -> (instrm::AsyncStream, outstrm::AsyncStream) - Implemented by cluster managers using custom transports. It should establish a logical connection to worker with id ``pid``, specified by ``config`` and return a pair of ``AsyncStream`` objects. Messages from ``pid`` to current process will be read off messages are delivered and received completely and in order. socket connections in-between workers. -.. function:: connect(path) -> Pipe +.. function:: connect(manager::FooManager, pid::Int, config::WorkerConfig) -> (instrm::AsyncStream, outstrm::AsyncStream) - :: - - connect(manager::FooManager, pid::Int, config::WorkerConfig) -> (instrm::AsyncStream, outstrm::AsyncStream) - Implemented by cluster managers using custom transports. It should establish a logical connection to worker with id ``pid``, specified by ``config`` and return a pair of ``AsyncStream`` objects. Messages from ``pid`` to current process will be read off messages are delivered and received completely and in order. socket connections in-between workers. -.. function:: listen([addr,]port) -> TcpServer +.. function:: listen(path) -> PipeServer - :: - - listen(path) -> PipeServer - Listens on/Creates a Named Pipe/Domain Socket .. function:: listen(path) -> PipeServer - :: - - listen(path) -> PipeServer - Listens on/Creates a Named Pipe/Domain Socket .. function:: getaddrinfo(host) - :: - - getaddrinfo(host) - Gets the IP address of the ``host`` (may have to do a DNS lookup) .. function:: parseip(addr) - :: - - parseip(addr) - Parse a string specifying an IPv4 or IPv6 ip address. .. function:: IPv4(host::Integer) -> IPv4 - :: - - IPv4(host::Integer) -> IPv4 - Returns IPv4 object from ip address formatted as Integer .. function:: IPv6(host::Integer) -> IPv6 - :: - - IPv6(host::Integer) -> IPv6 - Returns IPv6 object from ip address formatted as Integer .. function:: nb_available(stream) - :: - - nb_available(stream) - Returns the number of bytes available for reading before a read from this stream or buffer will block. -.. function:: accept(server[,client]) +.. function:: accept(server[, client]) - :: - - accept(server[, client]) - Accepts a connection on the given server and returns a connection to the client. An uninitialized client stream may be provided, in which case it will be used instead of creating a new stream. -.. function:: listenany(port_hint) -> (UInt16,TcpServer) +.. function:: listenany(port_hint) -> (UInt16, TcpServer) - :: - - listenany(port_hint) -> (UInt16, TcpServer) - Create a TcpServer on any port, using hint as a starting point. Returns a tuple of the actual port that the server was created on and the server itself. .. function:: watch_file(cb=false, s; poll=false) - :: - - watch_file(cb=false, s; poll=false) - Watch file or directory ``s`` and run callback ``cb`` when ``s`` is modified. The ``poll`` parameter specifies whether to use file system event monitoring or polling. The callback function ``cb`` should accept 3 arguments: ``(filename, events, status)`` where an object with boolean fields ``changed`` and ``renamed`` when using file system event monitoring, or ``readable`` and .. function:: poll_fd(fd, seconds::Real; readable=false, writable=false) - :: - - poll_fd(fd, seconds::Real; readable=false, writable=false) - Poll a file descriptor fd for changes in the read or write availability and with a timeout given by the second argument. If the timeout is not needed, use ``wait(fd)`` instead. The keyword arguments determine which of read and/or write status should be monitored and at least one of them needs to be set to true. The returned value is an object with boolean fields ``readable``, .. function:: poll_file(s, interval_seconds::Real, seconds::Real) - :: - - poll_file(s, interval_seconds::Real, seconds::Real) - Monitor a file for changes by polling every *interval_seconds* seconds for *seconds* seconds. A return value of true indicates the file changed, a return value of false indicates a timeout. .. function:: bind(socket::Union{UDPSocket, TCPSocket}, host::IPv4, port::Integer) - :: - - bind(socket::Union{UDPSocket, TCPSocket}, host::IPv4, port::Integer) - Bind ``socket`` to the given ``host:port``. Note that *0.0.0.0* will listen on all devices. .. function:: send(socket::UDPSocket, host::IPv4, port::Integer, msg) - :: - - send(socket::UDPSocket, host::IPv4, port::Integer, msg) - - Send ``msg`` over ``socket to ``host:port``. + Send ``msg`` over ``socket to `host:port``. .. function:: recv(socket::UDPSocket) - :: - - recv(socket::UDPSocket) - Read a UDP packet from the specified socket, and return the bytes received. This call blocks. .. function:: recvfrom(socket::UDPSocket) -> (address, data) - :: - - recvfrom(socket::UDPSocket) -> (address, data) - Read a UDP packet from the specified socket, returning a tuple of appropriate. .. function:: setopt(sock::UDPSocket; multicast_loop = nothing, multicast_ttl=nothing, enable_broadcast=nothing, ttl=nothing) - :: - - setopt(sock::UDPSocket; multicast_loop = nothing, multicast_ttl=nothing, enable_broadcast=nothing, ttl=nothing) - Set UDP socket options. ``multicast_loop``: loopback for multicast packets (default: true). ``multicast_ttl``: TTL for multicast packets. ``enable_broadcast``: flag must be set to true if socket will be used for broadcast messages, or else the UDP system will return an access error (default: false). ``ttl``: Time-to-live of packets sent on the socket. .. function:: ntoh(x) - :: - - ntoh(x) - Converts the endianness of a value from Network byte order (big- endian) to that used by the Host. .. function:: hton(x) - :: - - hton(x) - Converts the endianness of a value from that used by the Host to Network byte order (big-endian). .. function:: ltoh(x) - :: - - ltoh(x) - Converts the endianness of a value from Little-endian to that used by the Host. .. function:: htol(x) - :: - - htol(x) - Converts the endianness of a value from that used by the Host to Little-endian. diff --git a/doc/stdlib/libc.rst b/doc/stdlib/libc.rst index 623436fc64773..f20e663f6e67b 100644 --- a/doc/stdlib/libc.rst +++ b/doc/stdlib/libc.rst @@ -6,109 +6,61 @@ .. function:: malloc(size::Integer) -> Ptr{Void} - :: - - malloc(size::Integer) -> Ptr{Void} - Call ``malloc`` from the C standard library. .. function:: calloc(num::Integer, size::Integer) -> Ptr{Void} - :: - - calloc(num::Integer, size::Integer) -> Ptr{Void} - Call ``calloc`` from the C standard library. .. function:: realloc(addr::Ptr, size::Integer) -> Ptr{Void} - :: - - realloc(addr::Ptr, size::Integer) -> Ptr{Void} - Call ``realloc`` from the C standard library. See warning in the documentation for ``free`` regarding only using this on memory originally obtained from ``malloc``. .. function:: free(addr::Ptr) - :: - - free(addr::Ptr) - Call ``free`` from the C standard library. Only use this on memory obtained from ``malloc``, not on pointers retrieved from other C libraries. ``Ptr`` objects obtained from C libraries should be freed by the free functions defined in that library, to avoid assertion failures if multiple ``libc`` libraries exist on the system. .. function:: errno([code]) - :: - - errno([code]) - Get the value of the C library's ``errno``. If an argument is specified, it is used to set the value of ``errno``. The value of ``errno`` is only valid immediately after a ``ccall`` to a C library routine that sets it. Specifically, you cannot call executed between prompts. .. function:: strerror(n) - :: - - strerror(n) - Convert a system call error code to a descriptive string .. function:: time(t::TmStruct) - :: - - time(t::TmStruct) - Converts a ``TmStruct`` struct to a number of seconds since the epoch. .. function:: strftime([format], time) - :: - - strftime([format], time) - Convert time, given as a number of seconds since the epoch or a Supported formats are the same as those in the standard C library. .. function:: strptime([format], timestr) - :: - - strptime([format], timestr) - Parse a formatted time string into a ``TmStruct`` giving the seconds, minute, hour, date, etc. Supported formats are the same as those in the standard C library. On some platforms, timezones will not be parsed correctly. If the result of this function will be passed to ``time`` to convert it to seconds since the epoch, the will tell the C library to use the current system settings to determine the timezone. .. function:: TmStruct([seconds]) - :: - - TmStruct([seconds]) - Convert a number of seconds since the epoch to broken-down format, with fields ``sec``, ``min``, ``hour``, ``mday``, ``month``, .. function:: flush_cstdio() - :: - - flush_cstdio() - Flushes the C ``stdout`` and ``stderr`` streams (which may have been written to by external C code). -.. function:: msync(ptr, len, [flags]) +.. function:: msync(ptr, len[, flags]) - :: - - msync(ptr, len[, flags]) - Forces synchronization of the ``mmap()``ped memory region from combination of ``MS_ASYNC``, ``MS_SYNC``, or ``MS_INVALIDATE``. See your platform man page for specifics. The flags argument is not valid on Windows. You may not need to call ``msync``, because synchronization is performed at intervals automatically by the operating system. However, you can call this directly if, for example, you are concerned about losing the result of a long-running calculation. @@ -126,19 +78,11 @@ .. function:: mmap(len, prot, flags, fd, offset) - :: - - mmap(len, prot, flags, fd, offset) - Low-level interface to the ``mmap`` system call. See the man page. .. function:: munmap(pointer, len) - :: - - munmap(pointer, len) - Low-level interface for unmapping memory (see the man page). With is unmapped for you when the array goes out of scope. diff --git a/doc/stdlib/libdl.rst b/doc/stdlib/libdl.rst index 569944ebc789c..953dd1a923247 100644 --- a/doc/stdlib/libdl.rst +++ b/doc/stdlib/libdl.rst @@ -4,21 +4,13 @@ Dynamic Linker **************** -.. function:: dlopen(libfile::AbstractString [, flags::Integer]) +.. function:: dlopen(libfile::AbstractString[, flags::Integer]) - :: - - dlopen(libfile::AbstractString[, flags::Integer]) - Load a shared library, returning an opaque handle. The optional flags argument is a bitwise-or of zero or more of the POSIX (and/or GNU libc and/or MacOS) dlopen command, if possible, or are ignored if the specified functionality is not available on the current platform. The default is these flags, on POSIX platforms, is to specify symbols to be available for usage in other shared libraries, in situations where there are dependencies between shared libraries. -.. function:: dlopen_e(libfile::AbstractString [, flags::Integer]) +.. function:: dlopen_e(libfile::AbstractString[, flags::Integer]) - :: - - dlopen_e(libfile::AbstractString[, flags::Integer]) - Similar to ``dlopen()``, except returns a ``NULL`` pointer instead of raising errors. @@ -56,37 +48,21 @@ .. function:: dlsym(handle, sym) - :: - - dlsym(handle, sym) - Look up a symbol from a shared library handle, return callable function pointer on success. .. function:: dlsym_e(handle, sym) - :: - - dlsym_e(handle, sym) - Look up a symbol from a shared library handle, silently return NULL pointer on lookup failure. .. function:: dlclose(handle) - :: - - dlclose(handle) - Close shared library referenced by handle. .. function:: find_library(names, locations) - :: - - find_library(names, locations) - Searches for the first library in ``names`` in the paths in the that order) which can successfully be dlopen'd. On success, the return value will be one of the names (potentially prefixed by one of the paths in locations). This string can be assigned to a diff --git a/doc/stdlib/linalg.rst b/doc/stdlib/linalg.rst index 081bf84f7e7f6..45ba5f4683424 100644 --- a/doc/stdlib/linalg.rst +++ b/doc/stdlib/linalg.rst @@ -13,12 +13,8 @@ Standard Functions Linear algebra functions in Julia are largely implemented by calling functions from `LAPACK `_. Sparse factorizations call functions from `SuiteSparse `_. -.. function:: *(A, B) +.. function:: *(s, t) - :: - - *(s, t) - Concatenate strings. The ``*`` operator is an alias to this function. @@ -31,46 +27,26 @@ Linear algebra functions in Julia are largely implemented by calling functions f .. function:: dot(x, y) - :: - - dot(x, y) - Compute the dot product. For complex vectors, the first vector is conjugated. .. function:: vecdot(x, y) - :: - - vecdot(x, y) - For any iterable containers ``x`` and ``y`` (including arrays of any dimension) of numbers (or any element type for which ``dot`` is defined), compute the Euclidean dot product (the sum of .. function:: cross(x, y) - :: - - cross(x, y) - Compute the cross product of two 3-vectors. .. function:: factorize(A) - :: - - factorize(A) - Compute a convenient factorization (including LU, Cholesky, Bunch- Kaufman, LowerTriangular, UpperTriangular) of A, based upon the type of the input matrix. The return value can then be reused for efficient solving of multiple systems. For example: -.. function:: full(F) +.. function:: full(QRCompactWYQ[, thin=true]) -> Matrix - :: - - full(QRCompactWYQ[, thin=true]) -> Matrix - Converts an orthogonal or unitary matrix stored as a Optionally takes a ``thin`` Boolean argument, which if ``true`` omits the columns that span the rows of ``R`` in the QR factorization that are zero. The resulting matrix is the ``Q`` in a thin QR factorization (sometimes called the reduced QR factorization). If ``false``, returns a ``Q`` that spans all rows of ``R`` in its corresponding QR factorization. @@ -78,136 +54,76 @@ Linear algebra functions in Julia are largely implemented by calling functions f .. function:: lu(A) -> L, U, p - :: - - lu(A) -> L, U, p - Compute the LU factorization of ``A``, such that ``A[p,:] = L*U``. -.. function:: lufact(A [,pivot=Val{true}]) -> F +.. function:: lufact(A[, pivot=Val{true}]) -> F - :: - - lufact(A[, pivot=Val{true}]) -> F - Compute the LU factorization of ``A``. The return type of ``F`` depends on the type of ``A``. In most cases, if ``A`` is a subtype pivoting is chosen (default) the element type should also support examples are shown in the table below. The individual components of the factorization ``F`` can be accessed by indexing: .. function:: lufact!(A) -> LU - :: - - lufact!(A) -> LU - overwriting the input A, instead of creating a copy. For sparse 1-based indices to 0-based indices. -.. function:: chol(A, [LU]) -> F +.. function:: chol(A[, LU]) -> F - :: - - chol(A[, LU]) -> F - Compute the Cholesky factorization of a symmetric positive definite matrix ``A`` and return the matrix ``F``. If ``LU`` is ``Val{:U}`` and ``A = F*F'``. ``LU`` defaults to ``Val{:U}``. -.. function:: cholfact(A, [LU=:U[,pivot=Val{false}]][;tol=-1.0]) -> Cholesky +.. function:: cholfact(A; shift=0, perm=Int[]) -> CHOLMOD.Factor - :: - - cholfact(A; shift=0, perm=Int[]) -> CHOLMOD.Factor - Compute the Cholesky factorization of a sparse positive definite matrix ``A``. A fill-reducing permutation is used. ``F = cholfact(A)`` is most frequently used to solve systems of equations with ``F\b``, but also the methods ``diag``, ``det``, ``logdet`` are defined for ``F``. You can also extract individual factors from ``F``, using ``F[:L]``. However, since pivoting is on by default, the factorization is internally represented as ``A == P'*L*L'*P`` with a permutation matrix ``P``; using just ``L`` without accounting for ``P`` will give incorrect answers. To include the effects of permutation, it's typically preferable to extact ``combined`` factors like ``PtL = F[:PtL]`` (the equivalent of ``P'*L``) and ``LtP = F[:UP]`` (the equivalent of ``L'*P``). Setting optional ``shift`` keyword argument computes the factorization of ``A+shift*I`` instead of ``A``. If the ``perm`` argument is nonempty, it should be a permutation of *1:size(A,1)* giving the ordering to use (instead of CHOLMOD's default AMD ordering). The function calls the C library CHOLMOD and many other functions from the library are wrapped but not exported. .. function:: cholfact(A; shift=0, perm=Int[]) -> CHOLMOD.Factor - :: - - cholfact(A; shift=0, perm=Int[]) -> CHOLMOD.Factor - Compute the Cholesky factorization of a sparse positive definite matrix ``A``. A fill-reducing permutation is used. ``F = cholfact(A)`` is most frequently used to solve systems of equations with ``F\b``, but also the methods ``diag``, ``det``, ``logdet`` are defined for ``F``. You can also extract individual factors from ``F``, using ``F[:L]``. However, since pivoting is on by default, the factorization is internally represented as ``A == P'*L*L'*P`` with a permutation matrix ``P``; using just ``L`` without accounting for ``P`` will give incorrect answers. To include the effects of permutation, it's typically preferable to extact ``combined`` factors like ``PtL = F[:PtL]`` (the equivalent of ``P'*L``) and ``LtP = F[:UP]`` (the equivalent of ``L'*P``). Setting optional ``shift`` keyword argument computes the factorization of ``A+shift*I`` instead of ``A``. If the ``perm`` argument is nonempty, it should be a permutation of *1:size(A,1)* giving the ordering to use (instead of CHOLMOD's default AMD ordering). The function calls the C library CHOLMOD and many other functions from the library are wrapped but not exported. .. function:: cholfact!(A [,LU=:U [,pivot=Val{false}]][;tol=-1.0]) -> Cholesky - :: - - cholfact!(A [,LU=:U [,pivot=Val{false}]][;tol=-1.0]) -> Cholesky - overwriting the input ``A``, instead of creating a copy. different matrix ``F`` with the same structure when used as: -.. function:: ldltfact(A) -> LDLtFactorization +.. function:: ldltfact(A; shift=0, perm=Int[]) -> CHOLMOD.Factor - :: - - ldltfact(A; shift=0, perm=Int[]) -> CHOLMOD.Factor - Compute the LDLt factorization of a sparse symmetric or Hermitian matrix ``A``. A fill-reducing permutation is used. ``F = ldltfact(A)`` is most frequently used to solve systems of equations with ``F\b``, but also the methods ``diag``, ``det``, ``logdet`` are defined for ``F``. You can also extract individual factors from the factorization is internally represented as ``A == P'*L*D*L'*P`` with a permutation matrix ``P``; using just ``L`` without accounting for ``P`` will give incorrect answers. To include the effects of permutation, it's typically preferable to extact complete list of supported factors is ``:L, :PtL, :D, :UP, :U, :LD, Setting optional `shift`` keyword argument computes the factorization of ``A+shift*I`` instead of ``A``. If the ``perm`` argument is nonempty, it should be a permutation of *1:size(A,1)* giving the ordering to use (instead of CHOLMOD's default AMD ordering). The function calls the C library CHOLMOD and many other functions from the library are wrapped but not exported. .. function:: ldltfact(A; shift=0, perm=Int[]) -> CHOLMOD.Factor - :: - - ldltfact(A; shift=0, perm=Int[]) -> CHOLMOD.Factor - Compute the LDLt factorization of a sparse symmetric or Hermitian matrix ``A``. A fill-reducing permutation is used. ``F = ldltfact(A)`` is most frequently used to solve systems of equations with ``F\b``, but also the methods ``diag``, ``det``, ``logdet`` are defined for ``F``. You can also extract individual factors from the factorization is internally represented as ``A == P'*L*D*L'*P`` with a permutation matrix ``P``; using just ``L`` without accounting for ``P`` will give incorrect answers. To include the effects of permutation, it's typically preferable to extact complete list of supported factors is ``:L, :PtL, :D, :UP, :U, :LD, Setting optional `shift`` keyword argument computes the factorization of ``A+shift*I`` instead of ``A``. If the ``perm`` argument is nonempty, it should be a permutation of *1:size(A,1)* giving the ordering to use (instead of CHOLMOD's default AMD ordering). The function calls the C library CHOLMOD and many other functions from the library are wrapped but not exported. -.. function:: qr(A [,pivot=Val{false}][;thin=true]) -> Q, R, [p] +.. function:: qr(A[, pivot=Val{false}][;thin=true]) -> Q, R, [p] - :: - - qr(A[, pivot=Val{false}][;thin=true]) -> Q, R, [p] - Compute the (pivoted) QR factorization of ``A`` such that either is to compute a thin factorization. Note that ``R`` is not extended with zeros when the full ``Q`` is requested. -.. function:: qrfact(A [,pivot=Val{false}]) -> F +.. function:: qrfact(A) -> SPQR.Factorization - :: - - qrfact(A) -> SPQR.Factorization - Compute the QR factorization of a sparse matrix ``A``. A fill- reducing permutation is used. The main application of this type is to solve least squares problems with ``\``. The function calls the C library SPQR and a few additional functions from the library are wrapped but not exported. .. function:: qrfact(A) -> SPQR.Factorization - :: - - qrfact(A) -> SPQR.Factorization - Compute the QR factorization of a sparse matrix ``A``. A fill- reducing permutation is used. The main application of this type is to solve least squares problems with ``\``. The function calls the C library SPQR and a few additional functions from the library are wrapped but not exported. -.. function:: qrfact!(A [,pivot=Val{false}]) +.. function:: qrfact!(A[, pivot=Val{false}]) - :: - - qrfact!(A[, pivot=Val{false}]) - instead of creating a copy. .. function:: full(QRCompactWYQ[, thin=true]) -> Matrix - :: - - full(QRCompactWYQ[, thin=true]) -> Matrix - Converts an orthogonal or unitary matrix stored as a Optionally takes a ``thin`` Boolean argument, which if ``true`` omits the columns that span the rows of ``R`` in the QR factorization that are zero. The resulting matrix is the ``Q`` in a thin QR factorization (sometimes called the reduced QR factorization). If ``false``, returns a ``Q`` that spans all rows of ``R`` in its corresponding QR factorization. .. function:: bkfact(A) -> BunchKaufman - :: - - bkfact(A) -> BunchKaufman - Compute the Bunch-Kaufman [Bunch1977] factorization of a real symmetric or complex Hermitian matrix ``A`` and return a @@ -215,541 +131,301 @@ Linear algebra functions in Julia are largely implemented by calling functions f .. function:: bkfact!(A) -> BunchKaufman - :: - - bkfact!(A) -> BunchKaufman - overwriting the input ``A``, instead of creating a copy. .. function:: sqrtm(A) - :: - - sqrtm(A) - Compute the matrix square root of ``A``. If ``B = sqrtm(A)``, then using Schur factorizations (``schurfact()``) unless it detects the matrix to be Hermitian or real symmetric, in which case it computes the matrix square root from an eigendecomposition (``eigfact()``). In the latter situation for positive definite matrices, the matrix square root has ``Real`` elements, otherwise it has ``Complex`` elements. -.. function:: eig(A,[irange,][vl,][vu,][permute=true,][scale=true]) -> D, V +.. function:: eig(A, B) -> D, V - :: - - eig(A, B) -> D, V - Computes generalized eigenvalues and vectors of ``A`` with respect to ``B``. the factorization to a tuple; where possible, using ``eigfact()`` is recommended. .. function:: eig(A, B) -> D, V - :: - - eig(A, B) -> D, V - Computes generalized eigenvalues and vectors of ``A`` with respect to ``B``. the factorization to a tuple; where possible, using ``eigfact()`` is recommended. .. function:: eigvals(A,[irange,][vl,][vu]) - :: - - eigvals(A,[irange,][vl,][vu]) - Returns the eigenvalues of ``A``. If ``A`` is ``Symmetric``, only a subset of the eigenvalues by specifying either a eigenvalues, or a pair ``vl`` and ``vu`` for the lower and upper boundaries of the eigenvalues. For general non-symmetric matrices it is possible to specify how the matrix is balanced before the eigenvector calculation. The option ``permute=true`` permutes the matrix to become closer to upper triangular, and ``scale=true`` scales the matrix by its diagonal elements to make rows and columns more equal in norm. The default is ``true`` for both options. .. function:: eigmax(A) - :: - - eigmax(A) - Returns the largest eigenvalue of ``A``. .. function:: eigmin(A) - :: - - eigmin(A) - Returns the smallest eigenvalue of ``A``. .. function:: eigvecs(A, [eigvals,][permute=true,][scale=true]) -> Matrix - :: - - eigvecs(A, [eigvals,][permute=true,][scale=true]) -> Matrix - Returns a matrix ``M`` whose columns are the eigenvectors of ``A``. k]``.) The `permute`` and ``scale`` keywords are the same as for For ``SymTridiagonal`` matrices, if the optional vector of eigenvalues ``eigvals`` is specified, returns the specific corresponding eigenvectors. -.. function:: eigfact(A,[irange,][vl,][vu,][permute=true,][scale=true]) -> Eigen +.. function:: eigfact(A, B) -> GeneralizedEigen - :: - - eigfact(A, B) -> GeneralizedEigen - Computes the generalized eigenvalue decomposition of ``A`` and which contains the generalized eigenvalues in ``F[:values]`` and the generalized eigenvectors in the columns of the matrix obtained from the slice ``F[:vectors][:, k]``.) .. function:: eigfact(A, B) -> GeneralizedEigen - :: - - eigfact(A, B) -> GeneralizedEigen - Computes the generalized eigenvalue decomposition of ``A`` and which contains the generalized eigenvalues in ``F[:values]`` and the generalized eigenvectors in the columns of the matrix obtained from the slice ``F[:vectors][:, k]``.) -.. function:: eigfact!(A, [B]) +.. function:: eigfact!(A[, B]) - :: - - eigfact!(A[, B]) - Same as ``eigfact()``, but saves space by overwriting the input .. function:: hessfact(A) - :: - - hessfact(A) - Compute the Hessenberg decomposition of ``A`` and return a unitary matrix can be accessed with ``F[:Q]`` and the Hessenberg matrix with ``F[:H]``. When ``Q`` is extracted, the resulting type is the ``HessenbergQ`` object, and may be converted to a regular matrix with ``full()``. .. function:: hessfact!(A) - :: - - hessfact!(A) - overwriting the input A, instead of creating a copy. -.. function:: schurfact(A) -> Schur +.. function:: schurfact(A, B) -> GeneralizedSchur - :: - - schurfact(A, B) -> GeneralizedSchur - Computes the Generalized Schur (or QZ) factorization of the matrices ``A`` and ``B``. The (quasi) triangular Schur factors can be obtained from the ``Schur`` object ``F`` with ``F[:S]`` and obtained with ``F[:left]`` or ``F[:Q]`` and the right unitary/orthogonal Schur vectors can be obtained with ``F[:right]`` or ``F[:Z]`` such that ``A=F[:left]*F[:S]*F[:right]'`` and .. function:: schurfact!(A) - :: - - schurfact!(A) - Computes the Schur factorization of ``A``, overwriting ``A`` in the process. See ``schurfact()`` -.. function:: schur(A) -> Schur[:T], Schur[:Z], Schur[:values] +.. function:: schur(A, B) -> GeneralizedSchur[:S], GeneralizedSchur[:T], GeneralizedSchur[:Q], GeneralizedSchur[:Z] - :: - - schur(A, B) -> GeneralizedSchur[:S], GeneralizedSchur[:T], GeneralizedSchur[:Q], GeneralizedSchur[:Z] - See ``schurfact()`` -.. function:: ordschur(Q, T, select) -> Schur +.. function:: ordschur(GS, select) -> GeneralizedSchur - :: - - ordschur(GS, select) -> GeneralizedSchur - Reorders the Generalized Schur factorization of a Generalized Schur object. See ``ordschur()``. -.. function:: ordschur!(Q, T, select) -> Schur +.. function:: ordschur!(GS, select) -> GeneralizedSchur - :: - - ordschur!(GS, select) -> GeneralizedSchur - Reorders the Generalized Schur factorization of a Generalized Schur object by overwriting the object with the new factorization. See -.. function:: ordschur(S, select) -> Schur +.. function:: ordschur(GS, select) -> GeneralizedSchur - :: - - ordschur(GS, select) -> GeneralizedSchur - Reorders the Generalized Schur factorization of a Generalized Schur object. See ``ordschur()``. -.. function:: ordschur!(S, select) -> Schur +.. function:: ordschur!(GS, select) -> GeneralizedSchur - :: - - ordschur!(GS, select) -> GeneralizedSchur - Reorders the Generalized Schur factorization of a Generalized Schur object by overwriting the object with the new factorization. See .. function:: schurfact(A, B) -> GeneralizedSchur - :: - - schurfact(A, B) -> GeneralizedSchur - Computes the Generalized Schur (or QZ) factorization of the matrices ``A`` and ``B``. The (quasi) triangular Schur factors can be obtained from the ``Schur`` object ``F`` with ``F[:S]`` and obtained with ``F[:left]`` or ``F[:Q]`` and the right unitary/orthogonal Schur vectors can be obtained with ``F[:right]`` or ``F[:Z]`` such that ``A=F[:left]*F[:S]*F[:right]'`` and -.. function:: schur(A,B) -> GeneralizedSchur[:S], GeneralizedSchur[:T], GeneralizedSchur[:Q], GeneralizedSchur[:Z] +.. function:: schur(A, B) -> GeneralizedSchur[:S], GeneralizedSchur[:T], GeneralizedSchur[:Q], GeneralizedSchur[:Z] - :: - - schur(A, B) -> GeneralizedSchur[:S], GeneralizedSchur[:T], GeneralizedSchur[:Q], GeneralizedSchur[:Z] - See ``schurfact()`` -.. function:: ordschur(S, T, Q, Z, select) -> GeneralizedSchur +.. function:: ordschur(GS, select) -> GeneralizedSchur - :: - - ordschur(GS, select) -> GeneralizedSchur - Reorders the Generalized Schur factorization of a Generalized Schur object. See ``ordschur()``. -.. function:: ordschur!(S, T, Q, Z, select) -> GeneralizedSchur +.. function:: ordschur!(GS, select) -> GeneralizedSchur - :: - - ordschur!(GS, select) -> GeneralizedSchur - Reorders the Generalized Schur factorization of a Generalized Schur object by overwriting the object with the new factorization. See .. function:: ordschur(GS, select) -> GeneralizedSchur - :: - - ordschur(GS, select) -> GeneralizedSchur - Reorders the Generalized Schur factorization of a Generalized Schur object. See ``ordschur()``. .. function:: ordschur!(GS, select) -> GeneralizedSchur - :: - - ordschur!(GS, select) -> GeneralizedSchur - Reorders the Generalized Schur factorization of a Generalized Schur object by overwriting the object with the new factorization. See -.. function:: svdfact(A, [thin=true]) -> SVD +.. function:: svdfact(A, B) -> GeneralizedSVD - :: - - svdfact(A, B) -> GeneralizedSVD - Compute the generalized SVD of ``A`` and ``B``, returning a F[:U]*F[:D1]*F[:R0]*F[:Q]'` and `B = F[:V]*F[:D2]*F[:R0]*F[:Q]'`. -.. function:: svdfact!(A, [thin=true]) -> SVD +.. function:: svdfact!(A[, thin=true]) -> SVD - :: - - svdfact!(A[, thin=true]) -> SVD - overwriting the input A, instead of creating a copy. If ``thin`` is to produce a thin decomposition. -.. function:: svd(A, [thin=true]) -> U, S, V +.. function:: svd(A, B) -> U, V, Q, D1, D2, R0 - :: - - svd(A, B) -> U, V, Q, D1, D2, R0 - Wrapper around ``svdfact`` extracting all parts the factorization to a tuple. Direct use of ``svdfact`` is therefore generally more efficient. The function returns the generalized SVD of ``A`` and such that ``A = U*D1*R0*Q'`` and ``B = V*D2*R0*Q'``. -.. function:: svdvals(A) +.. function:: svdvals(A, B) - :: - - svdvals(A, B) - Return only the singular values from the generalized singular value decomposition of ``A`` and ``B``. .. function:: svdvals!(A) - :: - - svdvals!(A) - Returns the singular values of ``A``, while saving space by overwriting the input. .. function:: svdfact(A, B) -> GeneralizedSVD - :: - - svdfact(A, B) -> GeneralizedSVD - Compute the generalized SVD of ``A`` and ``B``, returning a F[:U]*F[:D1]*F[:R0]*F[:Q]'` and `B = F[:V]*F[:D2]*F[:R0]*F[:Q]'`. .. function:: svd(A, B) -> U, V, Q, D1, D2, R0 - :: - - svd(A, B) -> U, V, Q, D1, D2, R0 - Wrapper around ``svdfact`` extracting all parts the factorization to a tuple. Direct use of ``svdfact`` is therefore generally more efficient. The function returns the generalized SVD of ``A`` and such that ``A = U*D1*R0*Q'`` and ``B = V*D2*R0*Q'``. .. function:: svdvals(A, B) - :: - - svdvals(A, B) - Return only the singular values from the generalized singular value decomposition of ``A`` and ``B``. -.. function:: triu(M) +.. function:: triu(M, k) - :: - - triu(M, k) - Returns the upper triangle of ``M`` starting from the ``k``th superdiagonal. .. function:: triu(M, k) - :: - - triu(M, k) - Returns the upper triangle of ``M`` starting from the ``k``th superdiagonal. -.. function:: triu!(M) +.. function:: triu!(M, k) - :: - - triu!(M, k) - Returns the upper triangle of ``M`` starting from the ``k``th superdiagonal, overwriting ``M`` in the process. .. function:: triu!(M, k) - :: - - triu!(M, k) - Returns the upper triangle of ``M`` starting from the ``k``th superdiagonal, overwriting ``M`` in the process. -.. function:: tril(M) +.. function:: tril(M, k) - :: - - tril(M, k) - Returns the lower triangle of ``M`` starting from the ``k``th subdiagonal. .. function:: tril(M, k) - :: - - tril(M, k) - Returns the lower triangle of ``M`` starting from the ``k``th subdiagonal. -.. function:: tril!(M) +.. function:: tril!(M, k) - :: - - tril!(M, k) - Returns the lower triangle of ``M`` starting from the ``k``th subdiagonal, overwriting ``M`` in the process. .. function:: tril!(M, k) - :: - - tril!(M, k) - Returns the lower triangle of ``M`` starting from the ``k``th subdiagonal, overwriting ``M`` in the process. .. function:: diagind(M[, k]) - :: - - diagind(M[, k]) - A ``Range`` giving the indices of the ``k``th diagonal of the matrix ``M``. .. function:: diag(M[, k]) - :: - - diag(M[, k]) - The ``k``th diagonal of a matrix, as a vector. Use ``diagm`` to construct a diagonal matrix. .. function:: diagm(v[, k]) - :: - - diagm(v[, k]) - Construct a diagonal matrix and place ``v`` on the ``k``th diagonal. -.. function:: scale(A, b) +.. function:: scale(b, A) - :: - - scale(b, A) - Scale an array ``A`` by a scalar ``b``, returning a new array. If ``A`` is a matrix and ``b`` is a vector, then ``scale(A,b)`` scales each column ``i`` of ``A`` by ``b[i]`` (similar to array. Note: for large ``A``, ``scale`` can be much faster than ``A .* b`` or ``b .* A``, due to the use of BLAS. .. function:: scale(b, A) - :: - - scale(b, A) - Scale an array ``A`` by a scalar ``b``, returning a new array. If ``A`` is a matrix and ``b`` is a vector, then ``scale(A,b)`` scales each column ``i`` of ``A`` by ``b[i]`` (similar to array. Note: for large ``A``, ``scale`` can be much faster than ``A .* b`` or ``b .* A``, due to the use of BLAS. -.. function:: scale!(A, b) +.. function:: scale!(b, A) - :: - - scale!(b, A) - Scale an array ``A`` by a scalar ``b``, similar to ``scale()`` but overwriting ``A`` in-place. If ``A`` is a matrix and ``b`` is a vector, then ``scale!(A,b)`` scales each column ``i`` of ``A`` by ``b[i]`` (similar to place on ``A``. .. function:: scale!(b, A) - :: - - scale!(b, A) - Scale an array ``A`` by a scalar ``b``, similar to ``scale()`` but overwriting ``A`` in-place. If ``A`` is a matrix and ``b`` is a vector, then ``scale!(A,b)`` scales each column ``i`` of ``A`` by ``b[i]`` (similar to place on ``A``. .. function:: Tridiagonal(dl, d, du) - :: - - Tridiagonal(dl, d, du) - Construct a tridiagonal matrix from the lower diagonal, diagonal, and upper diagonal, respectively. The result is of type but may be converted into a regular matrix with ``full()``. .. function:: Bidiagonal(dv, ev, isupper) - :: - - Bidiagonal(dv, ev, isupper) - Constructs an upper (``isupper=true``) or lower (``isupper=false``) bidiagonal matrix using the given diagonal (``dv``) and off- diagonal (``ev``) vectors. The result is of type ``Bidiagonal`` and provides efficient specialized linear solvers, but may be converted into a regular matrix with ``full()``. .. function:: SymTridiagonal(d, du) - :: - - SymTridiagonal(d, du) - Construct a real symmetric tridiagonal matrix from the diagonal and upper diagonal, respectively. The result is of type but may be converted into a regular matrix with ``full()``. .. function:: rank(M) - :: - - rank(M) - Compute the rank of a matrix. -.. function:: norm(A, [p]) +.. function:: norm(A[, p]) - :: - - norm(A[, p]) - Compute the ``p``-norm of a vector or the operator norm of a matrix For vectors, ``p`` can assume any numeric value (even though not all values produce a mathematically valid vector norm). In particular, ``norm(A, Inf)`` returns the largest value in For matrices, valid values of ``p`` are ``1``, ``2``, or ``Inf``. implemented.) Use ``vecnorm()`` to compute the Frobenius norm. -.. function:: vecnorm(A, [p]) +.. function:: vecnorm(A[, p]) - :: - - vecnorm(A[, p]) - For any iterable container ``A`` (including arrays of any dimension) of numbers (or any element type for which ``norm`` is defined), compute the ``p``-norm (defaulting to ``p=2``) as if For example, if ``A`` is a matrix and ``p=2``, then this is equivalent to the Frobenius norm. -.. function:: cond(M, [p]) +.. function:: cond(M[, p]) - :: - - cond(M[, p]) - Condition number of the matrix ``M``, computed using the operator -.. function:: condskeel(M, [x, p]) +.. function:: condskeel(M[, x, p]) - :: - - condskeel(M[, x, p]) - Skeel condition number \kappa_S of the matrix ``M``, optionally with respect to the vector ``x``, as computed using the operator values for ``p`` are ``1``, ``2``, or ``Inf``. This quantity is also known in the literature as the Bauer condition number, relative condition number, or componentwise relative condition number. .. function:: trace(M) - :: - - trace(M) - Matrix trace .. function:: det(M) - :: - - det(M) - Matrix determinant .. function:: logdet(M) - :: - - logdet(M) - Log of matrix determinant. Equivalent to ``log(det(M))``, but may provide increased accuracy and/or speed. @@ -759,235 +435,131 @@ Linear algebra functions in Julia are largely implemented by calling functions f .. function:: inv(M) - :: - - inv(M) - Matrix inverse .. function:: pinv(M[, tol]) - :: - - pinv(M[, tol]) - Computes the Moore-Penrose pseudoinverse. For matrices ``M`` with floating point elements, it is convenient to compute the pseudoinverse by inverting only singular values above a given threshold, ``tol``. The optimal choice of ``tol`` varies both with the value of ``M`` and the intended application of the pseudoinverse. The default value of ``tol`` is essentially machine epsilon for the real part of a matrix element multiplied by the larger matrix dimension. For inverting dense ill- conditioned matrices in a least-squares sense, ``tol = sqrt(eps(real(float(one(eltype(M))))))`` is recommended. For more information, see [8859], [B96], [S84], [KY88]. .. function:: nullspace(M) - :: - - nullspace(M) - Basis for nullspace of ``M``. .. function:: repmat(A, n, m) - :: - - repmat(A, n, m) - Construct a matrix by repeating the given matrix ``n`` times in dimension 1 and ``m`` times in dimension 2. .. function:: repeat(A, inner = Int[], outer = Int[]) - :: - - repeat(A, inner = Int[], outer = Int[]) - Construct an array by repeating the entries of ``A``. The i-th element of ``inner`` specifies the number of times that the individual entries of the i-th dimension of ``A`` should be repeated. The i-th element of ``outer`` specifies the number of times that a slice along the i-th dimension of ``A`` should be repeated. .. function:: kron(A, B) - :: - - kron(A, B) - Kronecker tensor product of two vectors or two matrices. .. function:: blkdiag(A...) - :: - - blkdiag(A...) - Concatenate matrices block-diagonally. Currently only implemented for sparse matrices. -.. function:: linreg(x, y) -> [a; b] +.. function:: linreg(x, y, w) - :: - - linreg(x, y, w) - Weighted least-squares linear regression. .. function:: linreg(x, y, w) - :: - - linreg(x, y, w) - Weighted least-squares linear regression. .. function:: expm(A) - :: - - expm(A) - Matrix exponential. .. function:: lyap(A, C) - :: - - lyap(A, C) - Computes the solution ``X`` to the continuous Lyapunov equation part and no two eigenvalues are negative complex conjugates of each other. .. function:: sylvester(A, B, C) - :: - - sylvester(A, B, C) - Computes the solution ``X`` to the Sylvester equation `AX + XB + C .. function:: issym(A) -> Bool - :: - - issym(A) -> Bool - Test whether a matrix is symmetric. .. function:: isposdef(A) -> Bool - :: - - isposdef(A) -> Bool - Test whether a matrix is positive definite. .. function:: isposdef!(A) -> Bool - :: - - isposdef!(A) -> Bool - Test whether a matrix is positive definite, overwriting ``A`` in the processes. .. function:: istril(A) -> Bool - :: - - istril(A) -> Bool - Test whether a matrix is lower triangular. .. function:: istriu(A) -> Bool - :: - - istriu(A) -> Bool - Test whether a matrix is upper triangular. .. function:: isdiag(A) -> Bool - :: - - isdiag(A) -> Bool - Test whether a matrix is diagonal. .. function:: ishermitian(A) -> Bool - :: - - ishermitian(A) -> Bool - Test whether a matrix is Hermitian. .. function:: transpose(A) - :: - - transpose(A) - The transposition operator (``.'``). -.. function:: transpose!(dest,src) +.. function:: transpose!(dest, src) - :: - - transpose!(dest, src) - Transpose array ``src`` and store the result in the preallocated array ``dest``, which should have a size corresponding to supported and unexpected results will happen if *src* and *dest* have overlapping memory regions. .. function:: ctranspose(A) - :: - - ctranspose(A) - The conjugate transposition operator (``'``). -.. function:: ctranspose!(dest,src) +.. function:: ctranspose!(dest, src) - :: - - ctranspose!(dest, src) - Conjugate transpose array ``src`` and store the result in the preallocated array ``dest``, which should have a size corresponding to ``(size(src,2),size(src,1))``. No in-place transposition is supported and unexpected results will happen if *src* and *dest* have overlapping memory regions. -.. function:: eigs(A, [B,]; nev=6, which="LM", tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0,))) -> (d,[v,],nconv,niter,nmult,resid) +.. function:: eigs(A[, B], ; nev=6, which="LM", tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0, ))) -> (d[, v], nconv, niter, nmult, resid) - :: - - eigs(A[, B], ; nev=6, which="LM", tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0, ))) -> (d[, v], nconv, niter, nmult, resid) - Computes eigenvalues ``d`` of ``A`` using Lanczos or Arnoldi iterations for real symmetric or general nonsymmetric matrices respectively. If ``B`` is provided, the generalized eigenproblem is solved. The following keyword arguments are supported: corresponding Ritz vectors ``v`` (only if ``ritzvec=true``), the number of converged eigenvalues ``nconv``, the number of iterations Note: The ``sigma`` and ``which`` keywords interact: the .. function:: svds(A; nsv=6, ritzvec=true, tol=0.0, maxiter=1000) -> (left_sv, s, right_sv, nconv, niter, nmult, resid) - :: - - svds(A; nsv=6, ritzvec=true, tol=0.0, maxiter=1000) -> (left_sv, s, right_sv, nconv, niter, nmult, resid) - Lanczos or Arnoldi iterations. Uses ``eigs()`` underneath. Inputs are: .. function:: peakflops(n; parallel=false) - :: - - peakflops(n; parallel=false) - double precision ``Base.LinAlg.BLAS.gemm!()``. By default, if no arguments are specified, it multiplies a matrix of size ``n x n``, where ``n = 2000``. If the underlying BLAS is using multiple threads, higher flop rates are realized. The number of BLAS threads can be set with ``blas_set_num_threads(n)``. If the keyword argument ``parallel`` is set to ``true``, flop rate of the entire parallel computer is returned. When running in parallel, only 1 BLAS thread is used. The argument ``n`` still refers to the size of the problem that is solved on each processor. @@ -1007,388 +579,216 @@ Usually a function has 4 methods defined, one each for ``Float64``, .. function:: dot(n, X, incx, Y, incy) - :: - - dot(n, X, incx, Y, incy) - Dot product of two vectors consisting of ``n`` elements of array stride ``incy``. .. function:: dotu(n, X, incx, Y, incy) - :: - - dotu(n, X, incx, Y, incy) - Dot function for two complex vectors. .. function:: dotc(n, X, incx, U, incy) - :: - - dotc(n, X, incx, U, incy) - Dot function for two complex vectors conjugating the first vector. .. function:: blascopy!(n, X, incx, Y, incy) - :: - - blascopy!(n, X, incx, Y, incy) - Copy ``n`` elements of array ``X`` with stride ``incx`` to array .. function:: nrm2(n, X, incx) - :: - - nrm2(n, X, incx) - 2-norm of a vector consisting of ``n`` elements of array ``X`` with stride ``incx``. .. function:: asum(n, X, incx) - :: - - asum(n, X, incx) - sum of the absolute values of the first ``n`` elements of array .. function:: axpy!(a, X, Y) - :: - - axpy!(a, X, Y) - Overwrite ``Y`` with ``a*X + Y``. Returns ``Y``. .. function:: scal!(n, a, X, incx) - :: - - scal!(n, a, X, incx) - Overwrite ``X`` with ``a*X``. Returns ``X``. .. function:: scal(n, a, X, incx) - :: - - scal(n, a, X, incx) - Returns ``a*X``. .. function:: ger!(alpha, x, y, A) - :: - - ger!(alpha, x, y, A) - Rank-1 update of the matrix ``A`` with vectors ``x`` and ``y`` as .. function:: syr!(uplo, alpha, x, A) - :: - - syr!(uplo, alpha, x, A) - Rank-1 update of the symmetric matrix ``A`` with vector ``x`` as .. function:: syrk!(uplo, trans, alpha, A, beta, C) - :: - - syrk!(uplo, trans, alpha, A, beta, C) - Rank-k update of the symmetric matrix ``C`` as ``alpha*A*A.' + beta*C`` or ``alpha*A.'*A + beta*C`` according to whether ``trans`` is 'N' or 'T'. When ``uplo`` is 'U' the upper triangle of ``C`` is updated ('L' for lower triangle). Returns ``C``. .. function:: syrk(uplo, trans, alpha, A) - :: - - syrk(uplo, trans, alpha, A) - Returns either the upper triangle or the lower triangle, according to ``uplo`` ('U' or 'L'), of ``alpha*A*A.'`` or ``alpha*A.'*A``, according to ``trans`` ('N' or 'T'). .. function:: her!(uplo, alpha, x, A) - :: - - her!(uplo, alpha, x, A) - Methods for complex arrays only. Rank-1 update of the Hermitian matrix ``A`` with vector ``x`` as ``alpha*x*x' + A``. When lower triangle). Returns ``A``. .. function:: herk!(uplo, trans, alpha, A, beta, C) - :: - - herk!(uplo, trans, alpha, A, beta, C) - Methods for complex arrays only. Rank-k update of the Hermitian matrix ``C`` as ``alpha*A*A' + beta*C`` or ``alpha*A'*A + beta*C`` according to whether ``trans`` is 'N' or 'T'. When ``uplo`` is 'U' the upper triangle of ``C`` is updated ('L' for lower triangle). Returns ``C``. .. function:: herk(uplo, trans, alpha, A) - :: - - herk(uplo, trans, alpha, A) - Methods for complex arrays only. Returns either the upper triangle or the lower triangle, according to ``uplo`` ('U' or 'L'), of .. function:: gbmv!(trans, m, kl, ku, alpha, A, x, beta, y) - :: - - gbmv!(trans, m, kl, ku, alpha, A, x, beta, y) - Update vector ``y`` as ``alpha*A*x + beta*y`` or ``alpha*A'*x + beta*y`` according to ``trans`` ('N' or 'T'). The matrix ``A`` is a general band matrix of dimension ``m`` by ``size(A,2)`` with updated ``y``. .. function:: gbmv(trans, m, kl, ku, alpha, A, x, beta, y) - :: - - gbmv(trans, m, kl, ku, alpha, A, x, beta, y) - Returns ``alpha*A*x`` or ``alpha*A'*x`` according to ``trans`` ('N' or 'T'). The matrix ``A`` is a general band matrix of dimension diagonals. .. function:: sbmv!(uplo, k, alpha, A, x, beta, y) - :: - - sbmv!(uplo, k, alpha, A, x, beta, y) - Update vector ``y`` as ``alpha*A*x + beta*y`` where ``A`` is a a symmetric band matrix of order ``size(A,2)`` with ``k`` super- diagonals stored in the argument ``A``. The storage layout for http://www.netlib.org/lapack/explore-html/. Returns the updated ``y``. -.. function:: sbmv(uplo, k, alpha, A, x) +.. function:: sbmv(uplo, k, A, x) - :: - - sbmv(uplo, k, A, x) - Returns ``A*x`` where ``A`` is a symmetric band matrix of order .. function:: sbmv(uplo, k, A, x) - :: - - sbmv(uplo, k, A, x) - Returns ``A*x`` where ``A`` is a symmetric band matrix of order .. function:: gemm!(tA, tB, alpha, A, B, beta, C) - :: - - gemm!(tA, tB, alpha, A, B, beta, C) - Update ``C`` as ``alpha*A*B + beta*C`` or the other three variants according to ``tA`` (transpose ``A``) and ``tB``. Returns the updated ``C``. -.. function:: gemm(tA, tB, alpha, A, B) +.. function:: gemm(tA, tB, A, B) - :: - - gemm(tA, tB, A, B) - Returns ``A*B`` or the other three variants according to ``tA`` .. function:: gemm(tA, tB, A, B) - :: - - gemm(tA, tB, A, B) - Returns ``A*B`` or the other three variants according to ``tA`` .. function:: gemv!(tA, alpha, A, x, beta, y) - :: - - gemv!(tA, alpha, A, x, beta, y) - Update the vector ``y`` as ``alpha*A*x + beta*y`` or ``alpha*A'x + beta*y`` according to ``tA`` (transpose ``A``). Returns the updated -.. function:: gemv(tA, alpha, A, x) +.. function:: gemv(tA, A, x) - :: - - gemv(tA, A, x) - Returns ``A*x`` or ``A'x`` according to ``tA`` (transpose ``A``). .. function:: gemv(tA, A, x) - :: - - gemv(tA, A, x) - Returns ``A*x`` or ``A'x`` according to ``tA`` (transpose ``A``). .. function:: symm!(side, ul, alpha, A, B, beta, C) - :: - - symm!(side, ul, alpha, A, B, beta, C) - Update ``C`` as ``alpha*A*B + beta*C`` or ``alpha*B*A + beta*C`` according to ``side``. ``A`` is assumed to be symmetric. Only the -.. function:: symm(side, ul, alpha, A, B) +.. function:: symm(tA, tB, alpha, A, B) - :: - - symm(tA, tB, alpha, A, B) - Returns ``alpha*A*B`` or the other three variants according to -.. function:: symm(side, ul, A, B) +.. function:: symm(tA, tB, alpha, A, B) - :: - - symm(tA, tB, alpha, A, B) - Returns ``alpha*A*B`` or the other three variants according to .. function:: symm(tA, tB, alpha, A, B) - :: - - symm(tA, tB, alpha, A, B) - Returns ``alpha*A*B`` or the other three variants according to .. function:: symv!(ul, alpha, A, x, beta, y) - :: - - symv!(ul, alpha, A, x, beta, y) - Update the vector ``y`` as ``alpha*A*x + beta*y``. ``A`` is assumed to be symmetric. Only the ``ul`` triangle of ``A`` is used. Returns the updated ``y``. -.. function:: symv(ul, alpha, A, x) +.. function:: symv(ul, A, x) - :: - - symv(ul, A, x) - Returns ``A*x``. ``A`` is assumed to be symmetric. Only the .. function:: symv(ul, A, x) - :: - - symv(ul, A, x) - Returns ``A*x``. ``A`` is assumed to be symmetric. Only the .. function:: trmm!(side, ul, tA, dA, alpha, A, B) - :: - - trmm!(side, ul, tA, dA, alpha, A, B) - Update ``B`` as ``alpha*A*B`` or one of the other three variants determined by ``side`` (A on left or right) and ``tA`` (transpose A). Only the ``ul`` triangle of ``A`` is used. ``dA`` indicates if Returns the updated ``B``. .. function:: trmm(side, ul, tA, dA, alpha, A, B) - :: - - trmm(side, ul, tA, dA, alpha, A, B) - Returns ``alpha*A*B`` or one of the other three variants determined by ``side`` (A on left or right) and ``tA`` (transpose A). Only the unit-triangular (the diagonal is assumed to be all ones). .. function:: trsm!(side, ul, tA, dA, alpha, A, B) - :: - - trsm!(side, ul, tA, dA, alpha, A, B) - Overwrite ``B`` with the solution to ``A*X = alpha*B`` or one of the other three variants determined by ``side`` (A on left or right of ``X``) and ``tA`` (transpose A). Only the ``ul`` triangle of diagonal is assumed to be all ones). Returns the updated ``B``. .. function:: trsm(side, ul, tA, dA, alpha, A, B) - :: - - trsm(side, ul, tA, dA, alpha, A, B) - Returns the solution to ``A*X = alpha*B`` or one of the other three variants determined by ``side`` (A on left or right of ``X``) and assumed to be all ones). .. function:: trmv!(side, ul, tA, dA, alpha, A, b) - :: - - trmv!(side, ul, tA, dA, alpha, A, b) - Update ``b`` as ``alpha*A*b`` or one of the other three variants determined by ``side`` (A on left or right) and ``tA`` (transpose A). Only the ``ul`` triangle of ``A`` is used. ``dA`` indicates if Returns the updated ``b``. .. function:: trmv(side, ul, tA, dA, alpha, A, b) - :: - - trmv(side, ul, tA, dA, alpha, A, b) - Returns ``alpha*A*b`` or one of the other three variants determined by ``side`` (A on left or right) and ``tA`` (transpose A). Only the unit-triangular (the diagonal is assumed to be all ones). .. function:: trsv!(ul, tA, dA, A, b) - :: - - trsv!(ul, tA, dA, A, b) - Overwrite ``b`` with the solution to ``A*x = b`` or one of the other two variants determined by ``tA`` (transpose A) and ``ul`` triangular (the diagonal is assumed to be all ones). Returns the updated ``b``. .. function:: trsv(ul, tA, dA, A, b) - :: - - trsv(ul, tA, dA, A, b) - Returns the solution to ``A*x = b`` or one of the other two variants determined by ``tA`` (transpose A) and ``ul`` (triangle of diagonal is assumed to be all ones). .. function:: blas_set_num_threads(n) - :: - - blas_set_num_threads(n) - Set the number of threads the BLAS library should use. diff --git a/doc/stdlib/math.rst b/doc/stdlib/math.rst index ff47749a1a9ec..e58631839972e 100644 --- a/doc/stdlib/math.rst +++ b/doc/stdlib/math.rst @@ -9,52 +9,32 @@ Mathematical Operators ---------------------- -.. function:: -(x) +.. function:: -(x, y) - :: - - -(x, y) - Subtraction operator. .. _+: .. function:: +(x, y...) - :: - - +(x, y...) - Addition operator. ``x+y+z+...`` calls this function with all arguments, i.e. ``+(x, y, z, ...)``. .. _-: .. function:: -(x, y) - :: - - -(x, y) - Subtraction operator. .. _*: -.. function:: *(x, y...) +.. function:: *(s, t) - :: - - *(s, t) - Concatenate strings. The ``*`` operator is an alias to this function. .. _/: .. function:: /(x, y) - :: - - /(x, y) - Right division operator: multiplication of ``x`` by the inverse of arguments. @@ -65,52 +45,32 @@ Mathematical Operators Gives floating-point results for integer arguments. .. _^: -.. function:: ^(x, y) +.. function:: ^(s, n) - :: - - ^(s, n) - Repeat ``n`` times the string ``s``. The ``^`` operator is an alias to this function. .. _.+: .. function:: .+(x, y) - :: - - .+(x, y) - Element-wise addition operator. .. _.-: .. function:: .-(x, y) - :: - - .-(x, y) - Element-wise subtraction operator. .. _.*: .. function:: .*(x, y) - :: - - .*(x, y) - Element-wise multiplication operator. .. _./: .. function:: ./(x, y) - :: - - ./(x, y) - Element-wise right division operator. @@ -122,185 +82,105 @@ Mathematical Operators .. _.^: .. function:: .^(x, y) - :: - - .^(x, y) - Element-wise exponentiation operator. .. function:: fma(x, y, z) - :: - - fma(x, y, z) - Computes ``x*y+z`` without rounding the intermediate result algorithms. See ``muladd``. .. function:: muladd(x, y, z) - :: - - muladd(x, y, z) - Combined multiply-add, computes ``x*y+z`` in an efficient manner. This may on some systems be equivalent to ``x*y+z``, or to .. function:: div(x, y) - :: - - div(x, y) - The quotient from Euclidean division. Computes ``x/y``, truncated to an integer. .. function:: fld(x, y) - :: - - fld(x, y) - Largest integer less than or equal to ``x/y``. .. function:: cld(x, y) - :: - - cld(x, y) - Smallest integer larger than or equal to ``x/y``. .. function:: mod(x, y) - :: - - mod(x, y) - Modulus after division, returning in the range [0,``y``), if ``y`` is positive, or (``y``,0] if ``y`` is negative. .. function:: mod2pi(x) - :: - - mod2pi(x) - Modulus after division by 2pi, returning in the range [0,2pi). This function computes a floating point representation of the modulus after division by numerically exact 2pi, and is therefore not exactly the same as mod(x,2pi), which would compute the modulus of x relative to division by the floating-point number 2pi. .. function:: rem(x, y) - :: - - rem(x, y) - Remainder from Euclidean division, returning a value of the same sign as``x``, and smaller in magnitude than ``y``. This value is always exact. .. function:: divrem(x, y) - :: - - divrem(x, y) - The quotient and remainder from Euclidean division. Equivalent to .. function:: fldmod(x, y) - :: - - fldmod(x, y) - The floored quotient and modulus after division. Equivalent to -.. function:: mod1(x,m) +.. function:: mod1(x, m) - :: - - mod1(x, m) - Modulus after division, returning in the range (0,m] -.. function:: rem1(x,m) +.. function:: rem1(x, m) - :: - - rem1(x, m) - Remainder after division, returning in the range (0,m] .. _//: .. function:: //(num, den) - :: - - //(num, den) - Divide two integers or rational numbers, giving a ``Rational`` result. -.. function:: rationalize([Type=Int,] x; tol=eps(x)) +.. function:: rationalize([Type=Int], x; tol=eps(x)) - :: - - rationalize([Type=Int], x; tol=eps(x)) - Approximate floating point number ``x`` as a Rational number with components of the given integer type. The result will differ from .. function:: num(x) - :: - - num(x) - Numerator of the rational representation of ``x`` .. function:: den(x) - :: - - den(x) - Denominator of the rational representation of ``x`` .. _<<: .. function:: <<(x, n) - :: - - <<(x, n) - Left bit shift operator. .. _>>: .. function:: >>(x, n) - :: - - >>(x, n) - Right bit shift operator, preserving the sign of ``x``. .. _>>>: .. function:: >>>(x, n) - :: - - >>>(x, n) - Unsigned right bit shift operator. @@ -312,220 +192,132 @@ Mathematical Operators function ``colon``. The colon is also used in indexing to select whole dimensions. -.. function:: colon(start, [step], stop) +.. function:: colon(start[, step], stop) - :: - - colon(start[, step], stop) - Called by ``:`` syntax for constructing ranges. -.. function:: range(start, [step], length) +.. function:: range(start[, step], length) - :: - - range(start[, step], length) - Construct a range by length, given a starting value and optional step (defaults to 1). .. _==: .. function:: ==(x, y) - :: - - ==(x, y) - Generic equality operator, giving a single ``Bool`` result. Falls back to ``===``. Should be implemented for all types with a notion of equality, based on the abstract value that an instance represents. For example, all numeric types are compared by numeric value, ignoring type. Strings are compared as sequences of characters, ignoring encoding. Follows IEEE semantics for floating-point numbers. Collections should generally implement ``==`` by calling ``==`` recursively on all contents. New numeric types should implement this function for two arguments of the new type, and handle comparison to other types via promotion rules where possible. .. _!=: .. function:: !=(x, y) - :: - - !=(x, y) - Not-equals comparison operator. Always gives the opposite answer as the fallback definition ``!=(x,y) = !(x==y)`` instead. .. _===: .. function:: ===(x, y) - :: - - ===(x, y) - See the ``is()`` operator .. _!==: .. function:: !==(x, y) - :: - - !==(x, y) - Equivalent to ``!is(x, y)`` .. _<: .. function:: <(x, y) - :: - - <(x, y) - Less-than comparison operator. New numeric types should implement this function for two arguments of the new type. Because of the behavior of floating-point NaN values, ``<`` implements a partial order. Types with a canonical partial order should implement ``<``, and types with a canonical total order should implement ``isless``. .. _<=: .. function:: <=(x, y) - :: - - <=(x, y) - Less-than-or-equals comparison operator. .. _>: .. function:: >(x, y) - :: - - >(x, y) - Greater-than comparison operator. Generally, new types should implement ``<`` instead of this function, and rely on the fallback definition ``>(x,y) = y=: .. function:: >=(x, y) - :: - - >=(x, y) - Greater-than-or-equals comparison operator. .. _.==: .. function:: .==(x, y) - :: - - .==(x, y) - Element-wise equality comparison operator. .. _.!=: .. function:: .!=(x, y) - :: - - .!=(x, y) - Element-wise not-equals comparison operator. .. _.<: .. function:: .<(x, y) - :: - - .<(x, y) - Element-wise less-than comparison operator. .. _.<=: .. function:: .<=(x, y) - :: - - .<=(x, y) - Element-wise less-than-or-equals comparison operator. .. _.>: .. function:: .>(x, y) - :: - - .>(x, y) - Element-wise greater-than comparison operator. .. _.>=: .. function:: .>=(x, y) - :: - - .>=(x, y) - Element-wise greater-than-or-equals comparison operator. -.. function:: cmp(x,y) +.. function:: cmp(x, y) - :: - - cmp(x, y) - Return -1, 0, or 1 depending on whether ``x`` is less than, equal to, or greater than ``y``, respectively. Uses the total order implemented by ``isless``. For floating-point numbers, uses ``<`` but throws an error for unordered arguments. .. _~: .. function:: ~(x) - :: - - ~(x) - Bitwise not .. _&: .. function:: &(x, y) - :: - - &(x, y) - Bitwise and .. _|: .. function:: |(x, y) - :: - - |(x, y) - Bitwise or .. _$: -.. function:: $(x, y) +.. function:: \$(x, y) - :: - - \$(x, y) - Bitwise exclusive or .. _!: .. function:: !(x) - :: - - !(x) - Boolean not @@ -539,174 +331,98 @@ Mathematical Operators Short-circuiting boolean or -.. function:: A_ldiv_Bc(a,b) +.. function:: A_ldiv_Bc(a, b) - :: - - A_ldiv_Bc(a, b) - Matrix operator A \ B^H -.. function:: A_ldiv_Bt(a,b) +.. function:: A_ldiv_Bt(a, b) - :: - - A_ldiv_Bt(a, b) - Matrix operator A \ B^T .. function:: A_mul_B!(Y, A, B) -> Y - :: - - A_mul_B!(Y, A, B) -> Y - Calculates the matrix-matrix or matrix-vector product *A B* and stores the result in *Y*, overwriting the existing value of *Y*. .. function:: A_mul_Bc(...) - :: - - A_mul_Bc(...) - Matrix operator A B^H .. function:: A_mul_Bt(...) - :: - - A_mul_Bt(...) - Matrix operator A B^T .. function:: A_rdiv_Bc(...) - :: - - A_rdiv_Bc(...) - Matrix operator A / B^H -.. function:: A_rdiv_Bt(a,b) +.. function:: A_rdiv_Bt(a, b) - :: - - A_rdiv_Bt(a, b) - Matrix operator A / B^T .. function:: Ac_ldiv_B(...) - :: - - Ac_ldiv_B(...) - Matrix operator A^H \ B .. function:: Ac_ldiv_Bc(...) - :: - - Ac_ldiv_Bc(...) - Matrix operator A^H \ B^H .. function:: Ac_mul_B(...) - :: - - Ac_mul_B(...) - Matrix operator A^H B .. function:: Ac_mul_Bc(...) - :: - - Ac_mul_Bc(...) - Matrix operator A^H B^H -.. function:: Ac_rdiv_B(a,b) +.. function:: Ac_rdiv_B(a, b) - :: - - Ac_rdiv_B(a, b) - Matrix operator A^H / B -.. function:: Ac_rdiv_Bc(a,b) +.. function:: Ac_rdiv_Bc(a, b) - :: - - Ac_rdiv_Bc(a, b) - Matrix operator A^H / B^H .. function:: At_ldiv_B(...) - :: - - At_ldiv_B(...) - Matrix operator A^T \ B .. function:: At_ldiv_Bt(...) - :: - - At_ldiv_Bt(...) - Matrix operator A^T \ B^T .. function:: At_mul_B(...) - :: - - At_mul_B(...) - Matrix operator A^T B .. function:: At_mul_Bt(...) - :: - - At_mul_Bt(...) - Matrix operator A^T B^T -.. function:: At_rdiv_B(a,b) +.. function:: At_rdiv_B(a, b) - :: - - At_rdiv_B(a, b) - Matrix operator A^T / B -.. function:: At_rdiv_Bt(a,b) +.. function:: At_rdiv_Bt(a, b) - :: - - At_rdiv_Bt(a, b) - Matrix operator A^T / B^T @@ -715,523 +431,291 @@ Mathematical Functions .. function:: isapprox(x::Number, y::Number; rtol::Real=cbrt(maxeps), atol::Real=sqrt(maxeps)) - :: - - isapprox(x::Number, y::Number; rtol::Real=cbrt(maxeps), atol::Real=sqrt(maxeps)) - Inexact equality comparison - behaves slightly different depending on types of input args: For default tolerance arguments, ``maxeps = max(eps(abs(x)), eps(abs(y)))``. .. function:: sin(x) - :: - - sin(x) - Compute sine of ``x``, where ``x`` is in radians .. function:: cos(x) - :: - - cos(x) - Compute cosine of ``x``, where ``x`` is in radians .. function:: tan(x) - :: - - tan(x) - Compute tangent of ``x``, where ``x`` is in radians .. function:: sind(x) - :: - - sind(x) - Compute sine of ``x``, where ``x`` is in degrees .. function:: cosd(x) - :: - - cosd(x) - Compute cosine of ``x``, where ``x`` is in degrees .. function:: tand(x) - :: - - tand(x) - Compute tangent of ``x``, where ``x`` is in degrees .. function:: sinpi(x) - :: - - sinpi(x) - Compute \sin(\pi x) more accurately than ``sin(pi*x)``, especially for large ``x``. .. function:: cospi(x) - :: - - cospi(x) - Compute \cos(\pi x) more accurately than ``cos(pi*x)``, especially for large ``x``. .. function:: sinh(x) - :: - - sinh(x) - Compute hyperbolic sine of ``x`` .. function:: cosh(x) - :: - - cosh(x) - Compute hyperbolic cosine of ``x`` .. function:: tanh(x) - :: - - tanh(x) - Compute hyperbolic tangent of ``x`` .. function:: asin(x) - :: - - asin(x) - Compute the inverse sine of ``x``, where the output is in radians .. function:: acos(x) - :: - - acos(x) - Compute the inverse cosine of ``x``, where the output is in radians .. function:: atan(x) - :: - - atan(x) - Compute the inverse tangent of ``x``, where the output is in radians .. function:: atan2(y, x) - :: - - atan2(y, x) - Compute the inverse tangent of ``y/x``, using the signs of both .. function:: asind(x) - :: - - asind(x) - Compute the inverse sine of ``x``, where the output is in degrees .. function:: acosd(x) - :: - - acosd(x) - Compute the inverse cosine of ``x``, where the output is in degrees .. function:: atand(x) - :: - - atand(x) - Compute the inverse tangent of ``x``, where the output is in degrees .. function:: sec(x) - :: - - sec(x) - Compute the secant of ``x``, where ``x`` is in radians .. function:: csc(x) - :: - - csc(x) - Compute the cosecant of ``x``, where ``x`` is in radians .. function:: cot(x) - :: - - cot(x) - Compute the cotangent of ``x``, where ``x`` is in radians .. function:: secd(x) - :: - - secd(x) - Compute the secant of ``x``, where ``x`` is in degrees .. function:: cscd(x) - :: - - cscd(x) - Compute the cosecant of ``x``, where ``x`` is in degrees .. function:: cotd(x) - :: - - cotd(x) - Compute the cotangent of ``x``, where ``x`` is in degrees .. function:: asec(x) - :: - - asec(x) - Compute the inverse secant of ``x``, where the output is in radians .. function:: acsc(x) - :: - - acsc(x) - Compute the inverse cosecant of ``x``, where the output is in radians .. function:: acot(x) - :: - - acot(x) - Compute the inverse cotangent of ``x``, where the output is in radians .. function:: asecd(x) - :: - - asecd(x) - Compute the inverse secant of ``x``, where the output is in degrees .. function:: acscd(x) - :: - - acscd(x) - Compute the inverse cosecant of ``x``, where the output is in degrees .. function:: acotd(x) - :: - - acotd(x) - Compute the inverse cotangent of ``x``, where the output is in degrees .. function:: sech(x) - :: - - sech(x) - Compute the hyperbolic secant of ``x`` .. function:: csch(x) - :: - - csch(x) - Compute the hyperbolic cosecant of ``x`` .. function:: coth(x) - :: - - coth(x) - Compute the hyperbolic cotangent of ``x`` .. function:: asinh(x) - :: - - asinh(x) - Compute the inverse hyperbolic sine of ``x`` .. function:: acosh(x) - :: - - acosh(x) - Compute the inverse hyperbolic cosine of ``x`` .. function:: atanh(x) - :: - - atanh(x) - Compute the inverse hyperbolic tangent of ``x`` .. function:: asech(x) - :: - - asech(x) - Compute the inverse hyperbolic secant of ``x`` .. function:: acsch(x) - :: - - acsch(x) - Compute the inverse hyperbolic cosecant of ``x`` .. function:: acoth(x) - :: - - acoth(x) - Compute the inverse hyperbolic cotangent of ``x`` .. function:: sinc(x) - :: - - sinc(x) - Compute \sin(\pi x) / (\pi x) if x \neq 0, and 1 if x = 0. .. function:: cosc(x) - :: - - cosc(x) - Compute \cos(\pi x) / x - \sin(\pi x) / (\pi x^2) if x \neq 0, and 0 if x = 0. This is the derivative of ``sinc(x)``. .. function:: deg2rad(x) - :: - - deg2rad(x) - Convert ``x`` from degrees to radians .. function:: rad2deg(x) - :: - - rad2deg(x) - Convert ``x`` from radians to degrees .. function:: hypot(x, y) - :: - - hypot(x, y) - Compute the \sqrt{x^2+y^2} avoiding overflow and underflow -.. function:: log(x) +.. function:: log(b, x) - :: - - log(b, x) - Compute the base ``b`` logarithm of ``x``. Throws ``DomainError`` for negative ``Real`` arguments. -.. function:: log(b,x) +.. function:: log(b, x) - :: - - log(b, x) - Compute the base ``b`` logarithm of ``x``. Throws ``DomainError`` for negative ``Real`` arguments. .. function:: log2(x) - :: - - log2(x) - Compute the logarithm of ``x`` to base 2. Throws ``DomainError`` for negative ``Real`` arguments. .. function:: log10(x) - :: - - log10(x) - Compute the logarithm of ``x`` to base 10. Throws ``DomainError`` for negative ``Real`` arguments. .. function:: log1p(x) - :: - - log1p(x) - Accurate natural logarithm of ``1+x``. Throws ``DomainError`` for There is an experimental variant in the ``Base.Math.JuliaLibm`` module, which is typically faster and more accurate. .. function:: frexp(val) - :: - - frexp(val) - Return ``(x,exp)`` such that ``x`` has a magnitude in the interval .. function:: exp(x) - :: - - exp(x) - Compute e^x .. function:: exp2(x) - :: - - exp2(x) - Compute 2^x .. function:: exp10(x) - :: - - exp10(x) - Compute 10^x .. function:: ldexp(x, n) - :: - - ldexp(x, n) - Compute x \times 2^n .. function:: modf(x) - :: - - modf(x) - Return a tuple (fpart,ipart) of the fractional and integral parts of a number. Both parts have the same sign as the argument. .. function:: expm1(x) - :: - - expm1(x) - - Accurately compute e^x-1 + Accurately compute e^x-1 -.. function:: round([T,] x, [digits, [base]], [r::RoundingMode]) +.. function:: round(z, RoundingModeReal, RoundingModeImaginary) - :: - - round(z, RoundingModeReal, RoundingModeImaginary) - Returns the nearest integral value of the same type as the complex- valued ``z`` to ``z``, breaking ties using the specified the real components while the second is used for rounding the imaginary components. @@ -1302,778 +786,433 @@ Mathematical Functions .. function:: round(z, RoundingModeReal, RoundingModeImaginary) - :: - - round(z, RoundingModeReal, RoundingModeImaginary) - Returns the nearest integral value of the same type as the complex- valued ``z`` to ``z``, breaking ties using the specified the real components while the second is used for rounding the imaginary components. -.. function:: ceil([T,] x, [digits, [base]]) +.. function:: ceil([T], x[, digits[, base]]) - :: - - ceil([T], x[, digits[, base]]) -.. function:: floor([T,] x, [digits, [base]]) +.. function:: floor([T], x[, digits[, base]]) - :: - - floor([T], x[, digits[, base]]) -.. function:: trunc([T,] x, [digits, [base]]) +.. function:: trunc([T], x[, digits[, base]]) - :: - - trunc([T], x[, digits[, base]]) .. function:: unsafe_trunc(T, x) - :: - - unsafe_trunc(T, x) - value is not representable by ``T``, an arbitrary value will be returned. -.. function:: signif(x, digits, [base]) +.. function:: signif(x, digits[, base]) - :: - - signif(x, digits[, base]) - Rounds (in the sense of ``round``) ``x`` so that there are representation, default 10. E.g., ``signif(123.456, 2)`` is .. function:: min(x, y, ...) - :: - - min(x, y, ...) - Return the minimum of the arguments. Operates elementwise over arrays. .. function:: max(x, y, ...) - :: - - max(x, y, ...) - Return the maximum of the arguments. Operates elementwise over arrays. .. function:: minmax(x, y) - :: - - minmax(x, y) - Return ``(min(x,y), max(x,y))``. See also: ``extrema()`` that returns ``(minimum(x), maximum(x))`` .. function:: clamp(x, lo, hi) - :: - - clamp(x, lo, hi) - Return x if ``lo <= x <= hi``. If ``x < lo``, return ``lo``. If ``x Operates elementwise over `x`` if it is an array. .. function:: abs(x) - :: - - abs(x) - Absolute value of ``x`` .. function:: abs2(x) - :: - - abs2(x) - Squared absolute value of ``x`` .. function:: copysign(x, y) - :: - - copysign(x, y) - Return ``x`` such that it has the same sign as ``y`` .. function:: sign(x) - :: - - sign(x) - Return ``+1`` if ``x`` is positive, ``0`` if ``x == 0``, and ``-1`` if ``x`` is negative. .. function:: signbit(x) - :: - - signbit(x) - Returns ``true`` if the value of the sign of ``x`` is negative, otherwise ``false``. .. function:: flipsign(x, y) - :: - - flipsign(x, y) - Return ``x`` with its sign flipped if ``y`` is negative. For example ``abs(x) = flipsign(x,x)``. .. function:: sqrt(x) - :: - - sqrt(x) - Return \sqrt{x}. Throws ``DomainError`` for negative ``Real`` arguments. Use complex negative arguments instead. The prefix operator ``√`` is equivalent to ``sqrt``. .. function:: isqrt(n) - :: - - isqrt(n) - Integer square root: the largest integer ``m`` such that ``m*m <= n``. .. function:: cbrt(x) - :: - - cbrt(x) - Return x^{1/3}. The prefix operator ``∛`` is equivalent to .. function:: erf(x) - :: - - erf(x) - Compute the error function of ``x``, defined by .. function:: erfc(x) - :: - - erfc(x) - Compute the complementary error function of ``x``, defined by 1 - .. function:: erfcx(x) - :: - - erfcx(x) - Compute the scaled complementary error function of ``x``, defined by e^{x^2} \operatorname{erfc}(x). Note also that .. function:: erfi(x) - :: - - erfi(x) - Compute the imaginary error function of ``x``, defined by -i .. function:: dawson(x) - :: - - dawson(x) - Compute the Dawson function (scaled imaginary error function) of .. function:: erfinv(x) - :: - - erfinv(x) - Compute the inverse error function of a real ``x``, defined by .. function:: erfcinv(x) - :: - - erfcinv(x) - Compute the inverse error complementary function of a real ``x``, defined by \operatorname{erfc}(\operatorname{erfcinv}(x)) = x. .. function:: real(z) - :: - - real(z) - Return the real part of the complex number ``z`` .. function:: imag(z) - :: - - imag(z) - Return the imaginary part of the complex number ``z`` .. function:: reim(z) - :: - - reim(z) - Return both the real and imaginary parts of the complex number .. function:: conj(z) - :: - - conj(z) - Compute the complex conjugate of a complex number ``z`` .. function:: angle(z) - :: - - angle(z) - Compute the phase angle in radians of a complex number ``z`` .. function:: cis(z) - :: - - cis(z) - Return \exp(iz). -.. function:: binomial(n,k) +.. function:: binomial(n, k) - :: - - binomial(n, k) - Number of ways to choose ``k`` out of ``n`` items -.. function:: factorial(n) +.. function:: factorial(n, k) - :: - - factorial(n, k) - Compute ``factorial(n)/factorial(k)`` -.. function:: factorial(n,k) +.. function:: factorial(n, k) - :: - - factorial(n, k) - Compute ``factorial(n)/factorial(k)`` .. function:: factor(n) -> Dict - :: - - factor(n) -> Dict - Compute the prime factorization of an integer ``n``. Returns a dictionary. The keys of the dictionary correspond to the factors, and hence are of the same type as ``n``. The value associated with each key indicates the number of times the factor appears in the factorization. -.. function:: gcd(x,y) +.. function:: gcd(x, y) - :: - - gcd(x, y) - Greatest common (positive) divisor (or zero if x and y are both zero). -.. function:: lcm(x,y) +.. function:: lcm(x, y) - :: - - lcm(x, y) - Least common (non-negative) multiple. -.. function:: gcdx(x,y) +.. function:: gcdx(x, y) - :: - - gcdx(x, y) - Computes the greatest common (positive) divisor of ``x`` and ``y`` and their Bézout coefficients, i.e. the integer coefficients ``u`` and ``v`` that satisfy ux+vy = d = gcd(x,y). Note: Bézout coefficients are *not* uniquely defined. ``gcdx`` .. function:: ispow2(n) -> Bool - :: - - ispow2(n) -> Bool - Test whether ``n`` is a power of two .. function:: nextpow2(n) - :: - - nextpow2(n) - The smallest power of two not less than ``n``. Returns 0 for .. function:: prevpow2(n) - :: - - prevpow2(n) - The largest power of two not greater than ``n``. Returns 0 for .. function:: nextpow(a, x) - :: - - nextpow(a, x) - The smallest ``a^n`` not less than ``x``, where ``n`` is a non- negative integer. ``a`` must be greater than 1, and ``x`` must be greater than 0. .. function:: prevpow(a, x) - :: - - prevpow(a, x) - The largest ``a^n`` not greater than ``x``, where ``n`` is a non- negative integer. ``a`` must be greater than 1, and ``x`` must not be less than 1. -.. function:: nextprod([k_1,k_2,...], n) +.. function:: nextprod([k_1, k_2, ...], n) - :: - - nextprod([k_1, k_2, ...], n) - Next integer not less than ``n`` that can be written as \prod k_i^{p_i} for integers p_1, p_2, etc. -.. function:: prevprod([k_1,k_2,...], n) +.. function:: prevprod([k_1, k_2, ...], n) - :: - - prevprod([k_1, k_2, ...], n) - Previous integer not greater than ``n`` that can be written as -.. function:: invmod(x,m) +.. function:: invmod(x, m) - :: - - invmod(x, m) - Take the inverse of ``x`` modulo ``m``: ``y`` such that xy = 1 .. function:: powermod(x, p, m) - :: - - powermod(x, p, m) - Compute x^p \pmod m .. function:: gamma(x) - :: - - gamma(x) - Compute the gamma function of ``x`` .. function:: lgamma(x) - :: - - lgamma(x) - Compute the logarithm of the absolute value of ``gamma()`` for logarithm of ``gamma(x)``. .. function:: lfact(x) - :: - - lfact(x) - Compute the logarithmic factorial of ``x`` .. function:: digamma(x) - :: - - digamma(x) - Compute the digamma function of ``x`` (the logarithmic derivative of ``gamma(x)``) .. function:: invdigamma(x) - :: - - invdigamma(x) - Compute the inverse digamma function of ``x``. .. function:: trigamma(x) - :: - - trigamma(x) - Compute the trigamma function of ``x`` (the logarithmic second derivative of ``gamma(x)``) .. function:: polygamma(m, x) - :: - - polygamma(m, x) - Compute the polygamma function of order ``m`` of argument ``x`` -.. function:: airy(k,x) +.. function:: airy(k, x) - :: - - airy(k, x) - kth derivative of the Airy function \operatorname{Ai}(x). .. function:: airyai(x) - :: - - airyai(x) - Airy function \operatorname{Ai}(x). .. function:: airyprime(x) - :: - - airyprime(x) - Airy function derivative \operatorname{Ai}'(x). .. function:: airyaiprime(x) - :: - - airyaiprime(x) - Airy function derivative \operatorname{Ai}'(x). .. function:: airybi(x) - :: - - airybi(x) - Airy function \operatorname{Bi}(x). .. function:: airybiprime(x) - :: - - airybiprime(x) - Airy function derivative \operatorname{Bi}'(x). -.. function:: airyx(k,x) +.. function:: airyx(k, x) - :: - - airyx(k, x) - scaled kth derivative of the Airy function, return k == 1``, and \operatorname{Ai}(x) e^{- \left| \operatorname{Re} k == 3``. .. function:: besselj0(x) - :: - - besselj0(x) - Bessel function of the first kind of order 0, J_0(x). .. function:: besselj1(x) - :: - - besselj1(x) - Bessel function of the first kind of order 1, J_1(x). .. function:: besselj(nu, x) - :: - - besselj(nu, x) - Bessel function of the first kind of order ``nu``, J_\nu(x). .. function:: besseljx(nu, x) - :: - - besseljx(nu, x) - Scaled Bessel function of the first kind of order ``nu``, J_\nu(x) e^{- | \operatorname{Im}(x) |}. .. function:: bessely0(x) - :: - - bessely0(x) - Bessel function of the second kind of order 0, Y_0(x). .. function:: bessely1(x) - :: - - bessely1(x) - Bessel function of the second kind of order 1, Y_1(x). .. function:: bessely(nu, x) - :: - - bessely(nu, x) - Bessel function of the second kind of order ``nu``, Y_\nu(x). .. function:: besselyx(nu, x) - :: - - besselyx(nu, x) - Scaled Bessel function of the second kind of order ``nu``, Y_\nu(x) e^{- | \operatorname{Im}(x) |}. .. function:: hankelh1(nu, x) - :: - - hankelh1(nu, x) - Bessel function of the third kind of order ``nu``, H^{(1)}_\nu(x). .. function:: hankelh1x(nu, x) - :: - - hankelh1x(nu, x) - Scaled Bessel function of the third kind of order ``nu``, H^{(1)}_\nu(x) e^{-x i}. .. function:: hankelh2(nu, x) - :: - - hankelh2(nu, x) - Bessel function of the third kind of order ``nu``, H^{(2)}_\nu(x). .. function:: hankelh2x(nu, x) - :: - - hankelh2x(nu, x) - Scaled Bessel function of the third kind of order ``nu``, H^{(2)}_\nu(x) e^{x i}. .. function:: besselh(nu, k, x) - :: - - besselh(nu, k, x) - Bessel function of the third kind of order ``nu`` (Hankel function). ``k`` is either 1 or 2, selecting ``hankelh1`` or .. function:: besseli(nu, x) - :: - - besseli(nu, x) - Modified Bessel function of the first kind of order ``nu``, I_\nu(x). .. function:: besselix(nu, x) - :: - - besselix(nu, x) - Scaled modified Bessel function of the first kind of order ``nu``, I_\nu(x) e^{- | \operatorname{Re}(x) |}. .. function:: besselk(nu, x) - :: - - besselk(nu, x) - Modified Bessel function of the second kind of order ``nu``, K_\nu(x). .. function:: besselkx(nu, x) - :: - - besselkx(nu, x) - Scaled modified Bessel function of the second kind of order ``nu``, K_\nu(x) e^x. .. function:: beta(x, y) - :: - - beta(x, y) - Euler integral of the first kind \operatorname{B}(x,y) = .. function:: lbeta(x, y) - :: - - lbeta(x, y) - Natural logarithm of the absolute value of the beta function .. function:: eta(x) - :: - - eta(x) - Dirichlet eta function \eta(s) = -.. function:: zeta(s) +.. function:: zeta(s, z) - :: - - zeta(s, z) - Hurwitz zeta function \zeta(s, z). (This is equivalent to the Riemann zeta function \zeta(s) for the case of ``z=1``.) .. function:: zeta(s, z) - :: - - zeta(s, z) - Hurwitz zeta function \zeta(s, z). (This is equivalent to the Riemann zeta function \zeta(s) for the case of ``z=1``.) .. function:: ndigits(n, b) - :: - - ndigits(n, b) - Compute the number of digits in number ``n`` written in base ``b``. .. function:: widemul(x, y) - :: - - widemul(x, y) - Multiply ``x`` and ``y``, giving the result as a larger type. .. function:: @evalpoly(z, c...) - :: - - @evalpoly(z, c...) - Evaluate the polynomial \sum_k c[k] z^{k-1} for the coefficients ascending order by power of ``z``. This macro expands to efficient inline code that uses either Horner's method or, for complex ``z``, a more efficient Goertzel-like algorithm. @@ -2082,217 +1221,121 @@ Statistics .. function:: mean(v[, region]) - :: - - mean(v[, region]) - Compute the mean of whole array ``v``, or optionally along the dimensions in ``region``. Note: Julia does not ignore ``NaN`` values in the computation. For applications requiring the handling of missing data, the ``DataArray`` package is recommended. .. function:: mean!(r, v) - :: - - mean!(r, v) - Compute the mean of ``v`` over the singleton dimensions of ``r``, and write results to ``r``. .. function:: std(v[, region]) - :: - - std(v[, region]) - Compute the sample standard deviation of a vector or array ``v``, optionally along dimensions in ``region``. The algorithm returns an estimator of the generative distribution's standard deviation under the assumption that each entry of ``v`` is an IID drawn from that generative distribution. This computation is equivalent to calculating ``sqrt(sum((v - mean(v)).^2) / (length(v) - 1))``. Note: Julia does not ignore ``NaN`` values in the computation. For applications requiring the handling of missing data, the .. function:: stdm(v, m) - :: - - stdm(v, m) - Compute the sample standard deviation of a vector ``v`` with known mean ``m``. Note: Julia does not ignore ``NaN`` values in the computation. .. function:: var(v[, region]) - :: - - var(v[, region]) - Compute the sample variance of a vector or array ``v``, optionally along dimensions in ``region``. The algorithm will return an estimator of the generative distribution's variance under the assumption that each entry of ``v`` is an IID drawn from that generative distribution. This computation is equivalent to calculating ``sum((v - mean(v)).^2) / (length(v) - 1)``. Note: Julia does not ignore ``NaN`` values in the computation. For applications requiring the handling of missing data, the .. function:: varm(v, m) - :: - - varm(v, m) - Compute the sample variance of a vector ``v`` with known mean computation. -.. function:: middle(x) +.. function:: middle(array) - :: - - middle(array) - Compute the middle of an array, which consists in finding its extrema and then computing their mean. -.. function:: middle(x, y) +.. function:: middle(array) - :: - - middle(array) - Compute the middle of an array, which consists in finding its extrema and then computing their mean. -.. function:: middle(range) +.. function:: middle(array) - :: - - middle(array) - Compute the middle of an array, which consists in finding its extrema and then computing their mean. .. function:: middle(array) - :: - - middle(array) - Compute the middle of an array, which consists in finding its extrema and then computing their mean. .. function:: median(v) - :: - - median(v) - Compute the median of a vector ``v``. ``NaN`` is returned if the data contains any ``NaN`` values. For applications requiring the handling of missing data, the ``DataArrays`` package is recommended. .. function:: median!(v) - :: - - median!(v) - Like ``median``, but may overwrite the input vector. -.. function:: hist(v[, n]) -> e, counts +.. function:: hist(v, e) -> e, counts - :: - - hist(v, e) -> e, counts - Compute the histogram of ``v`` using a vector/range ``e`` as the edges for the bins. The result will be a vector of length satisfies ``sum(e[i] .< v .<= e[i+1])``. Note: Julia does not ignore ``NaN`` values in the computation. .. function:: hist(v, e) -> e, counts - :: - - hist(v, e) -> e, counts - Compute the histogram of ``v`` using a vector/range ``e`` as the edges for the bins. The result will be a vector of length satisfies ``sum(e[i] .< v .<= e[i+1])``. Note: Julia does not ignore ``NaN`` values in the computation. .. function:: hist!(counts, v, e) -> e, counts - :: - - hist!(counts, v, e) -> e, counts - Compute the histogram of ``v``, using a vector/range ``e`` as the edges for the bins. This function writes the resultant counts to a pre-allocated array ``counts``. .. function:: hist2d(M, e1, e2) -> (edge1, edge2, counts) - :: - - hist2d(M, e1, e2) -> (edge1, edge2, counts) - Compute a ``2d histogram`` of a set of N points specified by N-by-2 matrix ``M``. Arguments ``e1`` and ``e2`` are bins for each dimension, specified either as integer bin counts or vectors of bin edges. The result is a tuple of ``edge1`` (the bin edges used in the first dimension), ``edge2`` (the bin edges used in the second dimension), and ``counts``, a histogram matrix of size .. function:: hist2d!(counts, M, e1, e2) -> (e1, e2, counts) - :: - - hist2d!(counts, M, e1, e2) -> (e1, e2, counts) - Compute a ``2d histogram`` with respect to the bins delimited by the edges given in ``e1`` and ``e2``. This function writes the results to a pre-allocated array ``counts``. .. function:: histrange(v, n) - :: - - histrange(v, n) - Compute *nice* bin ranges for the edges of a histogram of ``v``, using approximately ``n`` bins. The resulting step sizes will be 1, 2 or 5 multiplied by a power of 10. Note: Julia does not ignore .. function:: midpoints(e) - :: - - midpoints(e) - Compute the midpoints of the bins with edges ``e``. The result is a vector/range of length ``length(e) - 1``. Note: Julia does not ignore ``NaN`` values in the computation. .. function:: quantile(v, p) - :: - - quantile(v, p) - Compute the quantile of a vector ``v`` at the probability ``p``. Note: Julia does not ignore ``NaN`` values in the computation. .. function:: quantile(v, p) - :: - - quantile(v, p) - Compute the quantile of a vector ``v`` at the probability ``p``. Note: Julia does not ignore ``NaN`` values in the computation. .. function:: quantile!(v, p) - :: - - quantile!(v, p) - Like ``quantile``, but overwrites the input vector. .. function:: cov(v1[, v2][, vardim=1, corrected=true, mean=nothing]) - :: - - cov(v1[, v2][, vardim=1, corrected=true, mean=nothing]) - Compute the Pearson covariance between the vector(s) in ``v1`` and This function accepts three keyword arguments: The size of the result depends on the size of ``v1`` and ``v2``. When both ``v1`` and ``v2`` are vectors, it returns the covariance between them as a scalar. When either one is a matrix, it returns a covariance matrix of size ``(n1, n2)``, where ``n1`` and ``n2`` are the numbers of slices in ``v1`` and ``v2``, which depend on the setting of ``vardim``. Note: ``v2`` can be omitted, which indicates ``v2 = v1``. .. function:: cor(v1[, v2][, vardim=1, mean=nothing]) - :: - - cor(v1[, v2][, vardim=1, mean=nothing]) - Compute the Pearson correlation between the vector(s) in ``v1`` and Users can use the keyword argument ``vardim`` to specify the variable dimension, and ``mean`` to supply pre-computed mean values. @@ -2305,327 +1348,183 @@ implemented by calling functions from `FFTW FFTW. Higher performance may be obtained by experimenting with multi-threading. Use `FFTW.set_num_threads(np)` to use `np` threads. -.. function:: fft(A [, dims]) +.. function:: fft(A[, dims]) - :: - - fft(A[, dims]) - Performs a multidimensional FFT of the array ``A``. The optional an integer, range, tuple, or array) to transform along. Most efficient if the size of ``A`` along the transformed dimensions is a product of small primes; see ``nextprod()``. See also A one-dimensional FFT computes the one-dimensional discrete Fourier transform (DFT) as defined by A multidimensional FFT simply performs this operation along each transformed dimension of ``A``. Higher performance is usually possible with multi-threading. Use processors. -.. function:: fft!(A [, dims]) +.. function:: fft!(A[, dims]) - :: - - fft!(A[, dims]) - Same as ``fft()``, but operates in-place on ``A``, which must be an array of complex floating-point numbers. -.. function:: ifft(A [, dims]) +.. function:: ifft(A[, dims]) - :: - - ifft(A[, dims]) - Multidimensional inverse FFT. A one-dimensional inverse FFT computes A multidimensional inverse FFT simply performs this operation along each transformed dimension of ``A``. -.. function:: ifft!(A [, dims]) +.. function:: ifft!(A[, dims]) - :: - - ifft!(A[, dims]) - Same as ``ifft()``, but operates in-place on ``A``. -.. function:: bfft(A [, dims]) +.. function:: bfft(A[, dims]) - :: - - bfft(A[, dims]) - Similar to ``ifft()``, but computes an unnormalized inverse sizes of the transformed dimensions in order to obtain the inverse. scaling step, which in some applications can be combined with other computational steps elsewhere.) -.. function:: bfft!(A [, dims]) +.. function:: bfft!(A[, dims]) - :: - - bfft!(A[, dims]) - Same as ``bfft()``, but operates in-place on ``A``. -.. function:: plan_fft(A [, dims [, flags [, timelimit]]]) +.. function:: plan_fft(A[, dims[, flags[, timelimit]]]) - :: - - plan_fft(A[, dims[, flags[, timelimit]]]) - Pre-plan an optimized FFT along given dimensions (``dims``) of arrays matching the shape and type of ``A``. (The first two arguments have the same meaning as for ``fft()``.) Returns a function ``plan(A)`` that computes ``fft(A, dims)`` quickly. The ``flags`` argument is a bitwise-or of FFTW planner flags, defaulting to ``FFTW.ESTIMATE``. e.g. passing ``FFTW.MEASURE`` or benchmarking different possible FFT algorithms and picking the fastest one; see the FFTW manual for more information on planner flags. The optional ``timelimit`` argument specifies a rough upper bound on the allowed planning time, in seconds. Passing that operates in-place on its argument (which must be an array of complex floating-point numbers). ``plan_ifft()`` and so on are similar but produce plans that perform the equivalent of the inverse transforms ``ifft()`` and so on. -.. function:: plan_ifft(A [, dims [, flags [, timelimit]]]) +.. function:: plan_ifft(A[, dims[, flags[, timelimit]]]) - :: - - plan_ifft(A[, dims[, flags[, timelimit]]]) - Same as ``plan_fft()``, but produces a plan that performs inverse transforms ``ifft()``. -.. function:: plan_bfft(A [, dims [, flags [, timelimit]]]) +.. function:: plan_bfft(A[, dims[, flags[, timelimit]]]) - :: - - plan_bfft(A[, dims[, flags[, timelimit]]]) - Same as ``plan_fft()``, but produces a plan that performs an unnormalized backwards transform ``bfft()``. -.. function:: plan_fft!(A [, dims [, flags [, timelimit]]]) +.. function:: plan_fft!(A[, dims[, flags[, timelimit]]]) - :: - - plan_fft!(A[, dims[, flags[, timelimit]]]) - Same as ``plan_fft()``, but operates in-place on ``A``. -.. function:: plan_ifft!(A [, dims [, flags [, timelimit]]]) +.. function:: plan_ifft!(A[, dims[, flags[, timelimit]]]) - :: - - plan_ifft!(A[, dims[, flags[, timelimit]]]) - Same as ``plan_ifft()``, but operates in-place on ``A``. -.. function:: plan_bfft!(A [, dims [, flags [, timelimit]]]) +.. function:: plan_bfft!(A[, dims[, flags[, timelimit]]]) - :: - - plan_bfft!(A[, dims[, flags[, timelimit]]]) - Same as ``plan_bfft()``, but operates in-place on ``A``. -.. function:: rfft(A [, dims]) +.. function:: rfft(A[, dims]) - :: - - rfft(A[, dims]) - Multidimensional FFT of a real array A, exploiting the fact that the transform has conjugate symmetry in order to save roughly half the computational time and storage costs compared with ``fft()``. If ``A`` has size ``(n_1, ..., n_d)``, the result has size The optional ``dims`` argument specifies an iterable subset of one or more dimensions of ``A`` to transform, similar to ``fft()``. Instead of (roughly) halving the first dimension of ``A`` in the result, the ``dims[1]`` dimension is (roughly) halved in the same way. -.. function:: irfft(A, d [, dims]) +.. function:: irfft(A, d[, dims]) - :: - - irfft(A, d[, dims]) - Inverse of ``rfft()``: for a complex array ``A``, gives the corresponding real array whose FFT yields ``A`` in the first half. As for ``rfft()``, ``dims`` is an optional subset of dimensions to transform, defaulting to ``1:ndims(A)``. floor(size(A,dims[1])/2)+1``. (This parameter cannot be inferred from `size(A)`` due to the possibility of rounding by the -.. function:: brfft(A, d [, dims]) +.. function:: brfft(A, d[, dims]) - :: - - brfft(A, d[, dims]) - Similar to ``irfft()`` but computes an unnormalized inverse transform (similar to ``bfft()``), which must be divided by the product of the sizes of the transformed dimensions (of the real output array) in order to obtain the inverse transform. -.. function:: plan_rfft(A [, dims [, flags [, timelimit]]]) +.. function:: plan_rfft(A[, dims[, flags[, timelimit]]]) - :: - - plan_rfft(A[, dims[, flags[, timelimit]]]) - Pre-plan an optimized real-input FFT, similar to ``plan_fft()`` except for ``rfft()`` instead of ``fft()``. The first two arguments, and the size of the transformed result, are the same as for ``rfft()``. -.. function:: plan_brfft(A, d [, dims [, flags [, timelimit]]]) +.. function:: plan_brfft(A, d[, dims[, flags[, timelimit]]]) - :: - - plan_brfft(A, d[, dims[, flags[, timelimit]]]) - Pre-plan an optimized real-input unnormalized transform, similar to first two arguments and the size of the transformed result, are the same as for ``brfft()``. -.. function:: plan_irfft(A, d [, dims [, flags [, timelimit]]]) +.. function:: plan_irfft(A, d[, dims[, flags[, timelimit]]]) - :: - - plan_irfft(A, d[, dims[, flags[, timelimit]]]) - Pre-plan an optimized inverse real-input FFT, similar to respectively. The first three arguments have the same meaning as for ``irfft()``. -.. function:: dct(A [, dims]) +.. function:: dct(A[, dims]) - :: - - dct(A[, dims]) - Performs a multidimensional type-II discrete cosine transform (DCT) of the array ``A``, using the unitary normalization of the DCT. The optional ``dims`` argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size of ``A`` along the transformed dimensions is a product of small primes; see ``nextprod()``. See also ``plan_dct()`` for even greater efficiency. -.. function:: dct!(A [, dims]) +.. function:: dct!(A[, dims]) - :: - - dct!(A[, dims]) - Same as ``dct!()``, except that it operates in-place on ``A``, which must be an array of real or complex floating-point values. -.. function:: idct(A [, dims]) +.. function:: idct(A[, dims]) - :: - - idct(A[, dims]) - Computes the multidimensional inverse discrete cosine transform unitary normalization). The optional ``dims`` argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size of ``A`` along the transformed dimensions is a product of small primes; see efficiency. -.. function:: idct!(A [, dims]) +.. function:: idct!(A[, dims]) - :: - - idct!(A[, dims]) - Same as ``idct!()``, but operates in-place on ``A``. -.. function:: plan_dct(A [, dims [, flags [, timelimit]]]) +.. function:: plan_dct(A[, dims[, flags[, timelimit]]]) - :: - - plan_dct(A[, dims[, flags[, timelimit]]]) - Pre-plan an optimized discrete cosine transform (DCT), similar to The first two arguments have the same meaning as for ``dct()``. -.. function:: plan_dct!(A [, dims [, flags [, timelimit]]]) +.. function:: plan_dct!(A[, dims[, flags[, timelimit]]]) - :: - - plan_dct!(A[, dims[, flags[, timelimit]]]) - Same as ``plan_dct()``, but operates in-place on ``A``. -.. function:: plan_idct(A [, dims [, flags [, timelimit]]]) +.. function:: plan_idct(A[, dims[, flags[, timelimit]]]) - :: - - plan_idct(A[, dims[, flags[, timelimit]]]) - Pre-plan an optimized inverse discrete cosine transform (DCT), similar to ``plan_fft()`` except producing a function that computes -.. function:: plan_idct!(A [, dims [, flags [, timelimit]]]) +.. function:: plan_idct!(A[, dims[, flags[, timelimit]]]) - :: - - plan_idct!(A[, dims[, flags[, timelimit]]]) - Same as ``plan_idct()``, but operates in-place on ``A``. -.. function:: fftshift(x) +.. function:: fftshift(x, dim) - :: - - fftshift(x, dim) - Swap the first and second halves of the given dimension of array -.. function:: fftshift(x,dim) +.. function:: fftshift(x, dim) - :: - - fftshift(x, dim) - Swap the first and second halves of the given dimension of array -.. function:: ifftshift(x, [dim]) +.. function:: ifftshift(x[, dim]) - :: - - ifftshift(x[, dim]) - Undoes the effect of ``fftshift``. -.. function:: filt(b, a, x, [si]) +.. function:: filt(b, a, x[, si]) - :: - - filt(b, a, x[, si]) - Apply filter described by vectors ``a`` and ``b`` to vector ``x``, with an optional initial filter state vector ``si`` (defaults to zeros). -.. function:: filt!(out, b, a, x, [si]) +.. function:: filt!(out, b, a, x[, si]) - :: - - filt!(out, b, a, x[, si]) - Same as ``filt()`` but writes the result into the ``out`` argument, which may alias the input ``x`` to modify it in-place. -.. function:: deconv(b,a) +.. function:: deconv(b, a) - :: - - deconv(b, a) - Construct vector ``c`` such that ``b = conv(a,c) + r``. Equivalent to polynomial division. -.. function:: conv(u,v) +.. function:: conv(u, v) - :: - - conv(u, v) - Convolution of two vectors. Uses FFT algorithm. -.. function:: conv2(u,v,A) +.. function:: conv2(B, A) - :: - - conv2(B, A) - 2-D convolution of the matrix ``B`` with the matrix ``A``. Uses 2-D FFT algorithm -.. function:: conv2(B,A) +.. function:: conv2(B, A) - :: - - conv2(B, A) - 2-D convolution of the matrix ``B`` with the matrix ``A``. Uses 2-D FFT algorithm -.. function:: xcorr(u,v) +.. function:: xcorr(u, v) - :: - - xcorr(u, v) - Compute the cross-correlation of two vectors. @@ -2633,39 +1532,23 @@ The following functions are defined within the ``Base.FFTW`` module. .. currentmodule:: Base.FFTW -.. function:: r2r(A, kind [, dims]) +.. function:: r2r(A, kind[, dims]) - :: - - r2r(A, kind[, dims]) - Performs a multidimensional real-input/real-output (r2r) transform of type ``kind`` of the array ``A``, as defined in the FFTW manual. types (``FFTW.REDFT00``, ``FFTW.REDFT01``, ``FFTW.REDFT10``, or Hartley transform (``FFTW.DHT``). The ``kind`` argument may be an array or tuple in order to specify different transform types along the different dimensions of ``A``; ``kind[end]`` is used for any unspecified dimensions. See the FFTW manual for precise definitions of these transform types, at http://www.fftw.org/doc. The optional ``dims`` argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. ``kind[i]`` is then the transform type for ``dims[i]``, with See also ``plan_r2r()`` to pre-plan optimized r2r transforms. -.. function:: r2r!(A, kind [, dims]) +.. function:: r2r!(A, kind[, dims]) - :: - - r2r!(A, kind[, dims]) - Same as ``r2r()``, but operates in-place on ``A``, which must be an array of real or complex floating-point numbers. -.. function:: plan_r2r(A, kind [, dims [, flags [, timelimit]]]) +.. function:: plan_r2r(A, kind[, dims[, flags[, timelimit]]]) - :: - - plan_r2r(A, kind[, dims[, flags[, timelimit]]]) - Pre-plan an optimized r2r transform, similar to ``Base.plan_fft()`` except that the transforms (and the first three arguments) correspond to ``r2r()`` and ``r2r!()``, respectively. -.. function:: plan_r2r!(A, kind [, dims [, flags [, timelimit]]]) +.. function:: plan_r2r!(A, kind[, dims[, flags[, timelimit]]]) - :: - - plan_r2r!(A, kind[, dims[, flags[, timelimit]]]) - Similar to ``Base.plan_fft()``, but corresponds to ``r2r!()``. @@ -2677,12 +1560,8 @@ Although several external packages are available for numeric integration and solution of ordinary differential equations, we also provide some built-in integration support in Julia. -.. function:: quadgk(f, a,b,c...; reltol=sqrt(eps), abstol=0, maxevals=10^7, order=7, norm=vecnorm) +.. function:: quadgk(f, a, b, c...; reltol=sqrt(eps), abstol=0, maxevals=10^7, order=7, norm=vecnorm) - :: - - quadgk(f, a, b, c...; reltol=sqrt(eps), abstol=0, maxevals=10^7, order=7, norm=vecnorm) - Numerically integrate the function ``f(x)`` from ``a`` to ``b``, and optionally over additional intervals ``b`` to ``c`` and so on. Keyword options include a relative error tolerance ``reltol`` absolute error tolerance ``abstol`` (defaults to 0), a maximum number of function evaluations ``maxevals`` (defaults to ``10^7``), and the ``order`` of the integration rule (defaults to 7). Returns a pair ``(I,E)`` of the estimated integral ``I`` and an estimated upper bound on the absolute error ``E``. If ``maxevals`` is not exceeded then ``E <= max(abstol, reltol*norm(I))`` will hold. (Note that it is useful to specify a positive ``abstol`` in cases where ``norm(I)`` may be zero.) The endpoints ``a`` etcetera can also be complex (in which case the integral is performed over straight-line segments in the complex plane). If the endpoints are ``BigFloat``, then the integration will be performed in ``BigFloat`` precision as well (note: it is advisable to increase the integration ``order`` in rough proportion to the precision, for smooth integrands). More generally, the precision is set by the precision of the integration endpoints The integrand ``f(x)`` can return any numeric scalar, vector, or matrix type, or in fact any type supporting ``+``, ``-``, multiplication by real values, and a ``norm`` (i.e., any normed vector space). Alternatively, a different norm can be specified by passing a *norm*-like function as the *norm* keyword argument multi-dimensional integration (cubature), there are many different algorithms (often much better than simple nested 1d integrals) and the optimal choice tends to be very problem-dependent. See the Julia external-package listing for available algorithms for multidimensional integration or other specialized tasks (such as integrals of highly oscillatory or singular functions).] The algorithm is an adaptive Gauss-Kronrod integration technique: the integral in each interval is estimated using a Kronrod rule Gauss rule (``order`` points). The interval with the largest error is then subdivided into two intervals and the process is repeated until the desired error tolerance is achieved. These quadrature rules work best for smooth functions within each interval, so if your function has a known discontinuity or other singularity, it is best to subdivide your interval to put the singularity at an endpoint. For example, if ``f`` has a discontinuity at ``x=0.7`` and you want to integrate from 0 to 1, you should use ``quadgk(f, 0,0.7,1)`` to subdivide the interval at the point of discontinuity. The integrand is never evaluated exactly at the endpoints of the intervals, so it is possible to integrate functions that diverge at the endpoints as long as the singularity is integrable (for example, a ``log(x)`` or For real-valued endpoints, the starting and/or ending points may be infinite. (A coordinate transformation is performed internally to map the infinite interval to a finite one.) diff --git a/doc/stdlib/numbers.rst b/doc/stdlib/numbers.rst index f74e014bed0e7..aac9e41d7d68f 100644 --- a/doc/stdlib/numbers.rst +++ b/doc/stdlib/numbers.rst @@ -12,201 +12,113 @@ Standard Numeric Types Data Formats ------------ -.. function:: bin(n, [pad]) +.. function:: bin(n[, pad]) - :: - - bin(n[, pad]) - Convert an integer to a binary string, optionally specifying a number of digits to pad to. -.. function:: hex(n, [pad]) +.. function:: hex(n[, pad]) - :: - - hex(n[, pad]) - Convert an integer to a hexadecimal string, optionally specifying a number of digits to pad to. -.. function:: dec(n, [pad]) +.. function:: dec(n[, pad]) - :: - - dec(n[, pad]) - Convert an integer to a decimal string, optionally specifying a number of digits to pad to. -.. function:: oct(n, [pad]) +.. function:: oct(n[, pad]) - :: - - oct(n[, pad]) - Convert an integer to an octal string, optionally specifying a number of digits to pad to. -.. function:: base(base, n, [pad]) +.. function:: base(base, n[, pad]) - :: - - base(base, n[, pad]) - Convert an integer to a string in the given base, optionally specifying a number of digits to pad to. The base can be specified as either an integer, or as a ``UInt8`` array of character values to use as digit symbols. -.. function:: digits(n, [base], [pad]) +.. function:: digits(n[, base][, pad]) - :: - - digits(n[, base][, pad]) - Returns an array of the digits of ``n`` in the given base, optionally padded with zeros to a specified size. More significant digits are at higher indexes, such that ``n == sum([digits[k]*base^(k-1) for k=1:length(digits)])``. -.. function:: digits!(array, n, [base]) +.. function:: digits!(array, n[, base]) - :: - - digits!(array, n[, base]) - Fills an array of the digits of ``n`` in the given base. More significant digits are at higher indexes. If the array length is insufficient, the least significant digits are filled up to the array length. If the array length is excessive, the excess portion is filled with zeros. .. function:: bits(n) - :: - - bits(n) - A string giving the literal bit representation of a number. -.. function:: parse(type, str, [base]) +.. function:: parse(type, str[, base]) - :: - - parse(type, str[, base]) - Parse a string as a number. If the type is an integer type, then a base can be specified (the default is 10). If the type is a floating point type, the string is parsed as a decimal floating point number. If the string does not contain a valid number, an error is raised. -.. function:: tryparse(type, str, [base]) +.. function:: tryparse(type, str[, base]) - :: - - tryparse(type, str[, base]) - Like ``parse``, but returns a ``Nullable`` of the requested type. The result will be null if the string does not contain a valid number. .. function:: big(x) - :: - - big(x) - Convert a number to a maximum precision representation (typically some pitfalls with floating-point numbers. .. function:: signed(x) - :: - - signed(x) - Convert a number to a signed integer. If the argument is unsigned, it is reinterpreted as signed without checking for overflow. .. function:: unsigned(x) -> Unsigned - :: - - unsigned(x) -> Unsigned - Convert a number to an unsigned integer. If the argument is signed, it is reinterpreted as unsigned without checking for negative values. .. function:: float(x) - :: - - float(x) - Convert a number, array, or string to a ``FloatingPoint`` data type. For numeric data, the smallest suitable ``FloatingPoint`` type is used. Converts strings to ``Float64``. .. function:: significand(x) - :: - - significand(x) - Extract the significand(s) (a.k.a. mantissa), in binary representation, of a floating-point number or array. If ``x`` is a non-zero finite number, than the result will be a number of the same type on the interval [1,2). Otherwise ``x`` is returned. .. function:: exponent(x) -> Int - :: - - exponent(x) -> Int - Get the exponent of a normalized floating-point number. -.. function:: complex(r, [i]) +.. function:: complex(r[, i]) - :: - - complex(r[, i]) - Convert real numbers or arrays to complex. ``i`` defaults to zero. .. function:: bswap(n) - :: - - bswap(n) - Byte-swap an integer .. function:: num2hex(f) - :: - - num2hex(f) - Get a hexadecimal string of the binary representation of a floating point number .. function:: hex2num(str) - :: - - hex2num(str) - Convert a hexadecimal string to the floating point number it represents .. function:: hex2bytes(s::ASCIIString) - :: - - hex2bytes(s::ASCIIString) - Convert an arbitrarily long hexadecimal string to its binary representation. Returns an Array{UInt8, 1}, i.e. an array of bytes. .. function:: bytes2hex(bin_arr::Array{UInt8, 1}) - :: - - bytes2hex(bin_arr::Array{UInt8, 1}) - Convert an array of bytes to its hexadecimal representation. All characters are in lower-case. Returns an ASCIIString. @@ -215,19 +127,11 @@ General Number Functions and Constants .. function:: one(x) - :: - - one(x) - Get the multiplicative identity element for the type of x (x can also specify the type itself). For matrices, returns an identity matrix of the appropriate size and type. .. function:: zero(x) - :: - - zero(x) - Get the additive identity element for the type of x (x can also specify the type itself). @@ -285,154 +189,86 @@ General Number Functions and Constants .. function:: issubnormal(f) -> Bool - :: - - issubnormal(f) -> Bool - Test whether a floating point number is subnormal .. function:: isfinite(f) -> Bool - :: - - isfinite(f) -> Bool - Test whether a number is finite .. function:: isinf(f) -> Bool - :: - - isinf(f) -> Bool - Test whether a number is infinite .. function:: isnan(f) -> Bool - :: - - isnan(f) -> Bool - Test whether a floating point number is not a number (NaN) .. function:: inf(f) - :: - - inf(f) - Returns positive infinity of the floating point type ``f`` or of the same floating point type as ``f`` .. function:: nan(f) - :: - - nan(f) - Returns NaN (not-a-number) of the floating point type ``f`` or of the same floating point type as ``f`` .. function:: nextfloat(f) - :: - - nextfloat(f) - Get the next floating point number in lexicographic order .. function:: prevfloat(f) -> FloatingPoint - :: - - prevfloat(f) -> FloatingPoint - Get the previous floating point number in lexicographic order .. function:: isinteger(x) -> Bool - :: - - isinteger(x) -> Bool - Test whether ``x`` or all its elements are numerically equal to some integer .. function:: isreal(x) -> Bool - :: - - isreal(x) -> Bool - Test whether ``x`` or all its elements are numerically equal to some real number -.. function:: Float32(x [, mode::RoundingMode]) +.. function:: Float32(x[, mode::RoundingMode]) - :: - - Float32(x[, mode::RoundingMode]) - Create a Float32 from ``x``. If ``x`` is not exactly representable then ``mode`` determines how ``x`` is rounded. See ``get_rounding`` for available rounding modes. -.. function:: Float64(x [, mode::RoundingMode]) +.. function:: Float64(x[, mode::RoundingMode]) - :: - - Float64(x[, mode::RoundingMode]) - Create a Float64 from ``x``. If ``x`` is not exactly representable then ``mode`` determines how ``x`` is rounded. See ``get_rounding`` for available rounding modes. .. function:: BigInt(x) - :: - - BigInt(x) - Create an arbitrary precision integer. ``x`` may be an ``Int`` (or anything that can be converted to an ``Int``). The usual mathematical operators are defined for this type, and results are promoted to a ``BigInt``. Instances can be constructed from strings via ``parse()``, or using the ``big`` string literal. .. function:: BigFloat(x) - :: - - BigFloat(x) - Create an arbitrary precision floating point number. ``x`` may be an ``Integer``, a ``Float64`` or a ``BigInt``. The usual mathematical operators are defined for this type, and results are promoted to a ``BigFloat``. Note that because decimal literals are converted to floating point numbers when parsed, ``BigFloat(2.1)`` may not yield what you expect. You may instead prefer to initialize constants from strings via ``parse()``, or using the ``big`` string literal. .. function:: get_rounding(T) - :: - - get_rounding(T) - Get the current floating point rounding mode for type ``T``, controlling the rounding of basic arithmetic functions (``+()``, Valid modes are ``RoundNearest``, ``RoundToZero``, ``RoundUp``, .. function:: set_rounding(T, mode) - :: - - set_rounding(T, mode) - Set the rounding mode of floating point type ``T``, controlling the rounding of basic arithmetic functions (``+()``, ``-()``, ``*()``, Note that this may affect other types, for instance changing the rounding mode of ``Float64`` will change the rounding mode of .. function:: with_rounding(f::Function, T, mode) - :: - - with_rounding(f::Function, T, mode) - Change the rounding mode of floating point type ``T`` for the duration of ``f``. It is logically equivalent to: See ``get_rounding`` for available rounding modes. @@ -441,100 +277,56 @@ Integers .. function:: count_ones(x::Integer) -> Integer - :: - - count_ones(x::Integer) -> Integer - Number of ones in the binary representation of ``x``. .. function:: count_zeros(x::Integer) -> Integer - :: - - count_zeros(x::Integer) -> Integer - Number of zeros in the binary representation of ``x``. .. function:: leading_zeros(x::Integer) -> Integer - :: - - leading_zeros(x::Integer) -> Integer - Number of zeros leading the binary representation of ``x``. .. function:: leading_ones(x::Integer) -> Integer - :: - - leading_ones(x::Integer) -> Integer - Number of ones leading the binary representation of ``x``. .. function:: trailing_zeros(x::Integer) -> Integer - :: - - trailing_zeros(x::Integer) -> Integer - Number of zeros trailing the binary representation of ``x``. .. function:: trailing_ones(x::Integer) -> Integer - :: - - trailing_ones(x::Integer) -> Integer - Number of ones trailing the binary representation of ``x``. -.. function:: isprime(x::Integer) -> Bool +.. function:: isprime(x::BigInt[, reps = 25]) -> Bool - :: - - isprime(x::BigInt[, reps = 25]) -> Bool - Probabilistic primality test. Returns ``true`` if ``x`` is prime; and ``false`` if ``x`` is not prime with high probability. The false positive rate is about ``0.25^reps``. ``reps = 25`` is considered safe for cryptographic applications (Knuth, Seminumerical Algorithms). -.. function:: isprime(x::BigInt, [reps = 25]) -> Bool +.. function:: isprime(x::BigInt[, reps = 25]) -> Bool - :: - - isprime(x::BigInt[, reps = 25]) -> Bool - Probabilistic primality test. Returns ``true`` if ``x`` is prime; and ``false`` if ``x`` is not prime with high probability. The false positive rate is about ``0.25^reps``. ``reps = 25`` is considered safe for cryptographic applications (Knuth, Seminumerical Algorithms). .. function:: primes(n) - :: - - primes(n) - Returns a collection of the prime numbers <= ``n``. .. function:: isodd(x::Integer) -> Bool - :: - - isodd(x::Integer) -> Bool - Returns ``true`` if ``x`` is odd (that is, not divisible by 2), and .. function:: iseven(x::Integer) -> Bool - :: - - iseven(x::Integer) -> Bool - Returns ``true`` is ``x`` is even (that is, divisible by 2), and @@ -544,37 +336,21 @@ The `BigFloat` type implements arbitrary-precision floating-point arithmetic usi .. function:: precision(num::FloatingPoint) - :: - - precision(num::FloatingPoint) - Get the precision of a floating point number, as defined by the effective number of bits in the mantissa. .. function:: get_bigfloat_precision() - :: - - get_bigfloat_precision() - Get the precision (in bits) currently used for BigFloat arithmetic. .. function:: set_bigfloat_precision(x::Int64) - :: - - set_bigfloat_precision(x::Int64) - Set the precision (in bits) to be used to BigFloat arithmetic. -.. function:: with_bigfloat_precision(f::Function,precision::Integer) +.. function:: with_bigfloat_precision(f::Function, precision::Integer) - :: - - with_bigfloat_precision(f::Function, precision::Integer) - Change the BigFloat arithmetic precision (in bits) for the duration of ``f``. It is logically equivalent to: @@ -597,93 +373,53 @@ A ``MersenneTwister`` or ``RandomDevice`` RNG can generate random numbers of the (or complex numbers of those types). Random floating point numbers are generated uniformly in [0,1). As ``BigInt`` represents unbounded integers, the interval must be specified (e.g. ``rand(big(1:6))``). -.. function:: srand([rng], [seed]) +.. function:: srand([rng][, seed]) - :: - - srand([rng][, seed]) - Reseed the random number generator. If a ``seed`` is provided, the RNG will give a reproducible sequence of numbers, otherwise Julia will get entropy from the system. For ``MersenneTwister``, the integers or a filename, in which case the seed is read from a file. .. function:: MersenneTwister([seed]) - :: - - MersenneTwister([seed]) - Create a ``MersenneTwister`` RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers. .. function:: RandomDevice() - :: - - RandomDevice() - Create a ``RandomDevice`` RNG object. Two such objects will always generate different streams of random numbers. -.. function:: rand([rng], [S], [dims...]) +.. function:: rand([rng][, S][, dims...]) - :: - - rand([rng][, S][, dims...]) - Pick a random element or array of random elements from the set of values specified by ``S``; ``S`` can be -.. function:: rand!([rng], A, [coll]) +.. function:: rand!([rng], A[, coll]) - :: - - rand!([rng], A[, coll]) - Populate the array A with random values. If the indexable collection ``coll`` is specified, the values are picked randomly from ``coll``. This is equivalent to ``copy!(A, rand(rng, coll, size(A)))`` or ``copy!(A, rand(rng, eltype(A), size(A)))`` but without allocating a new array. -.. function:: bitrand([rng], [dims...]) +.. function:: bitrand([rng][, dims...]) - :: - - bitrand([rng][, dims...]) - Generate a ``BitArray`` of random boolean values. -.. function:: randn([rng], [dims...]) +.. function:: randn([rng][, dims...]) - :: - - randn([rng][, dims...]) - Generate a normally-distributed random number with mean 0 and standard deviation 1. Optionally generate an array of normally- distributed random numbers. -.. function:: randn!([rng], A::Array{Float64,N}) +.. function:: randn!([rng], A::Array{Float64, N}) - :: - - randn!([rng], A::Array{Float64, N}) - Fill the array A with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the rand function. -.. function:: randexp([rng], [dims...]) +.. function:: randexp([rng][, dims...]) - :: - - randexp([rng][, dims...]) - Generate a random number according to the exponential distribution with scale 1. Optionally generate an array of such random numbers. -.. function:: randexp!([rng], A::Array{Float64,N}) +.. function:: randexp!([rng], A::Array{Float64, N}) - :: - - randexp!([rng], A::Array{Float64, N}) - Fill the array A with random numbers following the exponential distribution (with scale 1). diff --git a/doc/stdlib/parallel.rst b/doc/stdlib/parallel.rst index 89b22a59e4409..0b1319d7e2308 100644 --- a/doc/stdlib/parallel.rst +++ b/doc/stdlib/parallel.rst @@ -9,454 +9,254 @@ Tasks .. function:: Task(func) - :: - - Task(func) - Create a ``Task`` (i.e. thread, or coroutine) to execute the given function (which must be callable with no arguments). The task exits when this function returns. .. function:: yieldto(task, arg = nothing) - :: - - yieldto(task, arg = nothing) - Switch to the given task. The first time a task is switched to, the task's function is called with no arguments. On subsequent switches, ``arg`` is returned from the task's last call to considering states or scheduling in any way. Its use is discouraged. .. function:: current_task() - :: - - current_task() - Get the currently running Task. .. function:: istaskdone(task) -> Bool - :: - - istaskdone(task) -> Bool - Tell whether a task has exited. .. function:: istaskstarted(task) -> Bool - :: - - istaskstarted(task) -> Bool - Tell whether a task has started executing. .. function:: consume(task, values...) - :: - - consume(task, values...) - Receive the next value passed to ``produce`` by the specified task. Additional arguments may be passed, to be returned from the last .. function:: produce(value) - :: - - produce(value) - Send the given value to the last ``consume`` call, switching to the consumer task. If the next ``consume`` call passes any values, they are returned by ``produce``. .. function:: yield() - :: - - yield() - Switch to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable, and will be restarted immediately if there are no other runnable tasks. -.. function:: task_local_storage(symbol) +.. function:: task_local_storage(body, symbol, value) - :: - - task_local_storage(body, symbol, value) - Call the function ``body`` with a modified task-local storage, in which ``value`` is assigned to ``symbol``; the previous value of emulating dynamic scoping. -.. function:: task_local_storage(symbol, value) +.. function:: task_local_storage(body, symbol, value) - :: - - task_local_storage(body, symbol, value) - Call the function ``body`` with a modified task-local storage, in which ``value`` is assigned to ``symbol``; the previous value of emulating dynamic scoping. .. function:: task_local_storage(body, symbol, value) - :: - - task_local_storage(body, symbol, value) - Call the function ``body`` with a modified task-local storage, in which ``value`` is assigned to ``symbol``; the previous value of emulating dynamic scoping. .. function:: Condition() - :: - - Condition() - Create an edge-triggered event source that tasks can wait for. Tasks that call ``wait`` on a ``Condition`` are suspended and queued. Tasks are woken up when ``notify`` is later called on the time ``notify`` is called can be woken up. For level-triggered notifications, you must keep extra state to keep track of whether a notification has happened. The ``RemoteRef`` type does this, and so can be used for level-triggered events. .. function:: notify(condition, val=nothing; all=true, error=false) - :: - - notify(condition, val=nothing; all=true, error=false) - Wake up tasks waiting for a condition, passing them ``val``. If otherwise only one is. If ``error`` is true, the passed value is raised as an exception in the woken tasks. .. function:: schedule(t::Task, [val]; error=false) - :: - - schedule(t::Task, [val]; error=false) - Add a task to the scheduler's queue. This causes the task to run constantly when the system is otherwise idle, unless the task performs a blocking operation such as ``wait``. If a second argument is provided, it will be passed to the task task. -.. function:: @schedule +.. function:: @schedule() - :: - - @schedule() - Wrap an expression in a Task and add it to the scheduler's queue. -.. function:: @task +.. function:: @task() - :: - - @task() - Wrap an expression in a Task without executing it, and return the Task. This only creates a task, and does not run it. .. function:: sleep(seconds) - :: - - sleep(seconds) - Block the current task for a specified number of seconds. The minimum sleep time is 1 millisecond or input of ``0.001``. .. function:: ReentrantLock() - :: - - ReentrantLock() - Creates a reentrant lock. The same task can acquire the lock as many times as required. Each lock must be matched with an unlock. .. function:: lock(l::ReentrantLock) - :: - - lock(l::ReentrantLock) - Associates ``l`` with the current task. If ``l`` is already locked by a different task, waits for it to become available. The same task can acquire the lock multiple times. Each ``lock`` must be matched by an ``unlock`` .. function:: unlock(l::ReentrantLock) - :: - - unlock(l::ReentrantLock) - Releases ownership of the lock by the current task. If the lock had been acquired before, it just decrements an internal counter and returns immediately. General Parallel Computing Support ---------------------------------- -.. function:: addprocs(n::Integer; exeflags=``) -> List of process identifiers +.. function:: addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - :: - - addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - Launches worker processes via the specified cluster manager. For example Beowulf clusters are supported via a custom cluster manager implemented in package ``ClusterManagers``. The number of seconds a newly launched worker waits for connection establishment from the master can be specified via variable Relevant only when using TCP/IP as transport. -.. function:: addprocs() -> List of process identifiers +.. function:: addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - :: - - addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - Launches worker processes via the specified cluster manager. For example Beowulf clusters are supported via a custom cluster manager implemented in package ``ClusterManagers``. The number of seconds a newly launched worker waits for connection establishment from the master can be specified via variable Relevant only when using TCP/IP as transport. -.. function:: addprocs(machines; tunnel=false, sshflags=``, max_parallel=10, exeflags=``) -> List of process identifiers +.. function:: addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - :: - - addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - Launches worker processes via the specified cluster manager. For example Beowulf clusters are supported via a custom cluster manager implemented in package ``ClusterManagers``. The number of seconds a newly launched worker waits for connection establishment from the master can be specified via variable Relevant only when using TCP/IP as transport. .. function:: addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - :: - - addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - Launches worker processes via the specified cluster manager. For example Beowulf clusters are supported via a custom cluster manager implemented in package ``ClusterManagers``. The number of seconds a newly launched worker waits for connection establishment from the master can be specified via variable Relevant only when using TCP/IP as transport. .. function:: nprocs() - :: - - nprocs() - Get the number of available processes. .. function:: nworkers() - :: - - nworkers() - Get the number of available worker processes. This is one less than nprocs(). Equal to nprocs() if nprocs() == 1. -.. function:: procs() +.. function:: procs(S::SharedArray) - :: - - procs(S::SharedArray) - Get the vector of processes that have mapped the shared array .. function:: workers() - :: - - workers() - Returns a list of all worker process identifiers. .. function:: rmprocs(pids...) - :: - - rmprocs(pids...) - Removes the specified workers. .. function:: interrupt([pids...]) - :: - - interrupt([pids...]) - Interrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted. .. function:: myid() - :: - - myid() - Get the id of the current process. .. function:: pmap(f, lsts...; err_retry=true, err_stop=false, pids=workers()) - :: - - pmap(f, lsts...; err_retry=true, err_stop=false, pids=workers()) - Transform collections ``lsts`` by applying ``f`` to each element in parallel. If ``nprocs() > 1``, the calling process will be dedicated to assigning tasks. All other available processes will be used as parallel workers, or on the processes specified by If ``err_retry`` is true, it retries a failed application of ``f`` on a different worker. If ``err_stop`` is true, it takes precedence over the value of ``err_retry`` and ``pmap`` stops execution on the first error. .. function:: remotecall(id, func, args...) - :: - - remotecall(id, func, args...) - Call a function asynchronously on the given arguments on the specified process. Returns a ``RemoteRef``. .. function:: wait([x]) - :: - - wait([x]) - Block the current task until some event occurs, depending on the type of the argument: If no argument is passed, the task blocks for an undefined period. If the task's state is set to ``:waiting``, it can only be restarted by an explicit call to ``schedule`` or ``yieldto``. If the task's state is ``:runnable``, it might be restarted unpredictably. Often ``wait`` is called within a ``while`` loop to ensure a waited-for condition is met before proceeding. .. function:: fetch(RemoteRef) - :: - - fetch(RemoteRef) - Wait for and get the value of a remote reference. .. function:: remotecall_wait(id, func, args...) - :: - - remotecall_wait(id, func, args...) - Perform ``wait(remotecall(...))`` in one message. .. function:: remotecall_fetch(id, func, args...) - :: - - remotecall_fetch(id, func, args...) - Perform ``fetch(remotecall(...))`` in one message. .. function:: put!(RemoteRef, value) - :: - - put!(RemoteRef, value) - Store a value to a remote reference. Implements ``shared queue of length 1`` semantics: if a value is already present, blocks until the value is removed with ``take!``. Returns its first argument. .. function:: take!(RemoteRef) - :: - - take!(RemoteRef) - Fetch the value of a remote reference, removing it so that the reference is empty again. .. function:: isready(r::RemoteRef) - :: - - isready(r::RemoteRef) - Determine whether a ``RemoteRef`` has a value stored to it. Note that this function can cause race conditions, since by the time you receive its result it may no longer be true. It is recommended that this function only be used on a ``RemoteRef`` that is assigned once. If the argument ``RemoteRef`` is owned by a different node, this call will block to wait for the answer. It is recommended to wait for ``r`` in a separate task instead, or to use a local -.. function:: RemoteRef() +.. function:: RemoteRef(n) - :: - - RemoteRef(n) - Make an uninitialized remote reference on process ``n``. .. function:: RemoteRef(n) - :: - - RemoteRef(n) - Make an uninitialized remote reference on process ``n``. .. function:: timedwait(testcb::Function, secs::Float64; pollint::Float64=0.1) - :: - - timedwait(testcb::Function, secs::Float64; pollint::Float64=0.1) - - Waits till ``testcb`` returns ``true`` or for ``secs`` seconds, whichever is earlier. `testcb`` is polled every ``pollint`` seconds. + Waits till ``testcb`` returns ``true`` or for ``secs`` seconds, whichever is earlier. ``testcb`` is polled every ``pollint`` seconds. -.. function:: @spawn +.. function:: @spawn() - :: - - @spawn() - Execute an expression on an automatically-chosen process, returning a ``RemoteRef`` to the result. -.. function:: @spawnat +.. function:: @spawnat() - :: - - @spawnat() - Accepts two arguments, ``p`` and an expression, and runs the expression asynchronously on process ``p``, returning a -.. function:: @fetch +.. function:: @fetch() - :: - - @fetch() - Equivalent to ``fetch(@spawn expr)``. -.. function:: @fetchfrom +.. function:: @fetchfrom() - :: - - @fetchfrom() - Equivalent to ``fetch(@spawnat p expr)``. -.. function:: @async +.. function:: @async() - :: - - @async() - Schedule an expression to run on the local machine, also adding it to the set of items that the nearest enclosing ``@sync`` waits for. -.. function:: @sync +.. function:: @sync() - :: - - @sync() - Wait until all dynamically-enclosed uses of ``@async``, ``@spawn``, -.. function:: @parallel +.. function:: @parallel() - :: - - @parallel() - A parallel for loop of the form The specified range is partitioned and locally executed across all workers. In case an optional reducer function is specified, reduction on the calling process. Note that without a reducer function, @parallel executes asynchronously, i.e. it spawns independent tasks on all available workers and returns immediately without waiting for completion. To wait for completion, prefix the call with ``@sync``, like @@ -465,37 +265,21 @@ Shared Arrays (Experimental, UNIX-only feature) .. function:: SharedArray(T::Type, dims::NTuple; init=false, pids=Int[]) - :: - - SharedArray(T::Type, dims::NTuple; init=false, pids=Int[]) - Construct a SharedArray of a bitstype ``T`` and size ``dims`` across the processes specified by ``pids`` - all of which have to be on the same host. If ``pids`` is left unspecified, the shared array will be mapped across all processes on the current host, including the master. But, ``localindexes`` and ``indexpids`` will only refer to worker processes. This facilitates work distribution code to use workers for actual computation with the master process acting as a driver. If an ``init`` function of the type ``initfn(S::SharedArray)`` is specified, it is called on all the participating workers. .. function:: procs(S::SharedArray) - :: - - procs(S::SharedArray) - Get the vector of processes that have mapped the shared array .. function:: sdata(S::SharedArray) - :: - - sdata(S::SharedArray) - Returns the actual ``Array`` object backing ``S`` .. function:: indexpids(S::SharedArray) - :: - - indexpids(S::SharedArray) - Returns the index of the current worker into the ``pids`` vector, i.e., the list of workers mapping the SharedArray @@ -508,46 +292,26 @@ Cluster Manager Interface .. function:: launch(manager::FooManager, params::Dict, launched::Vector{WorkerConfig}, launch_ntfy::Condition) - :: - - launch(manager::FooManager, params::Dict, launched::Vector{WorkerConfig}, launch_ntfy::Condition) - Implemented by cluster managers. For every Julia worker launched by this function, it should append a ``WorkerConfig`` entry to once all workers, requested by ``manager`` have been launched. was called with. .. function:: manage(manager::FooManager, pid::Int, config::WorkerConfig. op::Symbol) - :: - - manage(manager::FooManager, pid::Int, config::WorkerConfig. op::Symbol) - Implemented by cluster managers. It is called on the master process, during a worker's lifetime, with appropriate ``op`` values: .. function:: kill(manager::FooManager, pid::Int, config::WorkerConfig) - :: - - kill(manager::FooManager, pid::Int, config::WorkerConfig) - Implemented by cluster managers. It is called on the master process, by ``rmprocs``. It should cause the remote worker specified by ``pid`` to exit. .. function:: init_worker(manager::FooManager) - :: - - init_worker(manager::FooManager) - Called by cluster managers implementing custom transports. It initializes a newly launched process as a worker. Command line argument ``--worker`` has the effect of initializing a process as a worker using TCP/IP sockets for transport. .. function:: connect(manager::FooManager, pid::Int, config::WorkerConfig) -> (instrm::AsyncStream, outstrm::AsyncStream) - :: - - connect(manager::FooManager, pid::Int, config::WorkerConfig) -> (instrm::AsyncStream, outstrm::AsyncStream) - Implemented by cluster managers using custom transports. It should establish a logical connection to worker with id ``pid``, specified by ``config`` and return a pair of ``AsyncStream`` objects. Messages from ``pid`` to current process will be read off messages are delivered and received completely and in order. socket connections in-between workers. diff --git a/doc/stdlib/pkg.rst b/doc/stdlib/pkg.rst index d1bcf1e8b74b0..36a41338871ce 100644 --- a/doc/stdlib/pkg.rst +++ b/doc/stdlib/pkg.rst @@ -7,246 +7,138 @@ All package manager functions are defined in the ``Pkg`` module. None of the ``Pkg`` module's functions are exported; to use them, you'll need to prefix each function call with an explicit ``Pkg.``, e.g. ``Pkg.status()`` or ``Pkg.dir()``. -.. function:: dir() -> AbstractString +.. function:: dir(names...) -> AbstractString - :: - - dir(names...) -> AbstractString - Equivalent to ``normpath(Pkg.dir(),names...)`` – i.e. it appends path components to the package directory and normalizes the resulting path. In particular, ``Pkg.dir(pkg)`` returns the path to the package ``pkg``. .. function:: dir(names...) -> AbstractString - :: - - dir(names...) -> AbstractString - Equivalent to ``normpath(Pkg.dir(),names...)`` – i.e. it appends path components to the package directory and normalizes the resulting path. In particular, ``Pkg.dir(pkg)`` returns the path to the package ``pkg``. .. function:: init(meta::AbstractString=DEFAULT_META, branch::AbstractString=META_BRANCH) - :: - - init(meta::AbstractString=DEFAULT_META, branch::AbstractString=META_BRANCH) - Initialize ``Pkg.dir()`` as a package directory. This will be done automatically when the ``JULIA_PKGDIR`` is not set and clones a local METADATA git repository from the site and branch specified by its arguments, which are typically not provided. Explicit (non-default) arguments can be used to support a custom METADATA setup. .. function:: resolve() - :: - - resolve() - Determines an optimal, consistent set of package versions to install or upgrade to. The optimal set of package versions is based on the contents of ``Pkg.dir(``REQUIRE``)`` and the state of installed packages in ``Pkg.dir()``, Packages that are no longer required are moved into ``Pkg.dir(``.trash``)``. .. function:: edit() - :: - - edit() - Opens ``Pkg.dir(``REQUIRE``)`` in the editor specified by the command returns, it runs ``Pkg.resolve()`` to determine and install a new optimal set of installed package versions. .. function:: add(pkg, vers...) - :: - - add(pkg, vers...) - Add a requirement entry for ``pkg`` to ``Pkg.dir(``REQUIRE``)`` and call ``Pkg.resolve()``. If ``vers`` are given, they must be intervals for ``pkg``. .. function:: rm(pkg) - :: - - rm(pkg) - Remove all requirement entries for ``pkg`` from -.. function:: clone(url, [pkg]) +.. function:: clone(pkg) - :: - - clone(pkg) - If ``pkg`` has a URL registered in ``Pkg.dir(``METADATA``)``, clone it from that URL on the default branch. The package does not need to have any registered versions. .. function:: clone(pkg) - :: - - clone(pkg) - If ``pkg`` has a URL registered in ``Pkg.dir(``METADATA``)``, clone it from that URL on the default branch. The package does not need to have any registered versions. -.. function:: available() -> Vector{ASCIIString} +.. function:: available(pkg) -> Vector{VersionNumber} - :: - - available(pkg) -> Vector{VersionNumber} - Returns the version numbers available for package ``pkg``. .. function:: available(pkg) -> Vector{VersionNumber} - :: - - available(pkg) -> Vector{VersionNumber} - Returns the version numbers available for package ``pkg``. -.. function:: installed() -> Dict{ASCIIString,VersionNumber} +.. function:: installed(pkg) -> Void | VersionNumber - :: - - installed(pkg) -> Void | VersionNumber - If ``pkg`` is installed, return the installed version number, otherwise return ``nothing``. .. function:: installed(pkg) -> Void | VersionNumber - :: - - installed(pkg) -> Void | VersionNumber - If ``pkg`` is installed, return the installed version number, otherwise return ``nothing``. .. function:: status() - :: - - status() - Prints out a summary of what packages are installed and what version and state they're in. .. function:: update() - :: - - update() - Update package the metadata repo – kept in safely be pulled from their origin; then call ``Pkg.resolve()`` to determine a new optimal set of packages versions. -.. function:: checkout(pkg, [branch="master"]) +.. function:: checkout(pkg[, branch="master"]) - :: - - checkout(pkg[, branch="master"]) - Checkout the ``Pkg.dir(pkg)`` repo to the branch ``branch``. Defaults to checking out the ``master`` branch. To go back to using the newest compatible released version, use ``Pkg.free(pkg)`` -.. function:: pin(pkg) +.. function:: pin(pkg, version) - :: - - pin(pkg, version) - Pin ``pkg`` at registered version ``version``. .. function:: pin(pkg, version) - :: - - pin(pkg, version) - Pin ``pkg`` at registered version ``version``. .. function:: free(pkg) - :: - - free(pkg) - Free the package ``pkg`` to be managed by the package manager again. It calls ``Pkg.resolve()`` to determine optimal package versions after. This is an inverse for both ``Pkg.checkout`` and You can also supply an iterable collection of package names, e.g., once. -.. function:: build() +.. function:: build(pkgs...) - :: - - build(pkgs...) - Run the build script in ``deps/build.jl`` for each package in order. This is called automatically by ``Pkg.resolve()`` on all installed or updated packages. .. function:: build(pkgs...) - :: - - build(pkgs...) - Run the build script in ``deps/build.jl`` for each package in order. This is called automatically by ``Pkg.resolve()`` on all installed or updated packages. -.. function:: generate(pkg,license) +.. function:: generate(pkg, license) - :: - - generate(pkg, license) - Generate a new package named ``pkg`` with one of these license keys: ``MIT``, ``BSD`` or ``ASL``. If you want to make a package with a different license, you can edit it afterwards. Generate creates a git repo at ``Pkg.dir(pkg)`` for the package and inside it ``LICENSE.md``, ``README.md``, the julia entrypoint -.. function:: register(pkg, [url]) +.. function:: register(pkg[, url]) - :: - - register(pkg[, url]) - Register ``pkg`` at the git URL ``url``, defaulting to the configured origin URL of the git repo ``Pkg.dir(pkg)``. -.. function:: tag(pkg, [ver, [commit]]) +.. function:: tag(pkg[, ver[, commit]]) - :: - - tag(pkg[, ver[, commit]]) - Tag ``commit`` as version ``ver`` of package ``pkg`` and create a version entry in ``METADATA``. If not provided, ``commit`` defaults to the current commit of the ``pkg`` repo. If ``ver`` is one of the symbols ``:patch``, ``:minor``, ``:major`` the next patch, minor or major version is used. If ``ver`` is not provided, it defaults to .. function:: publish() - :: - - publish() - For each new package version tagged in ``METADATA`` not already published, make sure that the tagged package commits have been pushed to the repo at the registered URL for the package and if they all have, open a pull request to ``METADATA``. -.. function:: test() +.. function:: test(pkgs...) - :: - - test(pkgs...) - Run the tests for each package in ``pkgs`` ensuring that each package's test dependencies are installed for the duration of the test. A package is tested by running its ``test/runtests.jl`` file and test dependencies are specified in ``test/REQUIRE``. .. function:: test(pkgs...) - :: - - test(pkgs...) - Run the tests for each package in ``pkgs`` ensuring that each package's test dependencies are installed for the duration of the test. A package is tested by running its ``test/runtests.jl`` file and test dependencies are specified in ``test/REQUIRE``. diff --git a/doc/stdlib/profile.rst b/doc/stdlib/profile.rst index 60b010eb02a4e..e214e1183badf 100644 --- a/doc/stdlib/profile.rst +++ b/doc/stdlib/profile.rst @@ -8,12 +8,8 @@ .. currentmodule:: Base -.. function:: @profile +.. function:: @profile() - :: - - @profile() - periodic backtraces. These are appended to an internal buffer of backtraces. @@ -22,73 +18,41 @@ The methods in :mod:`Base.Profile` are not exported and need to be called e.g. a .. function:: clear() - :: - - clear() - Clear any existing backtraces from the internal buffer. -.. function:: print([io::IO = STDOUT,] [data::Vector]; format = :tree, C = false, combine = true, cols = tty_cols()) +.. function:: print([io::IO = STDOUT], data::Vector, lidict::Dict; format = :tree, combine = true, cols = tty_cols()) - :: - - print([io::IO = STDOUT], data::Vector, lidict::Dict; format = :tree, combine = true, cols = tty_cols()) - Prints profiling results to ``io``. This variant is used to examine results exported by a previous call to ``retrieve()``. Supply the vector ``data`` of backtraces and a dictionary ``lidict`` of line information. -.. function:: print([io::IO = STDOUT,] data::Vector, lidict::Dict; format = :tree, combine = true, cols = tty_cols()) +.. function:: print([io::IO = STDOUT], data::Vector, lidict::Dict; format = :tree, combine = true, cols = tty_cols()) - :: - - print([io::IO = STDOUT], data::Vector, lidict::Dict; format = :tree, combine = true, cols = tty_cols()) - Prints profiling results to ``io``. This variant is used to examine results exported by a previous call to ``retrieve()``. Supply the vector ``data`` of backtraces and a dictionary ``lidict`` of line information. .. function:: init(; n::Integer, delay::Float64) - :: - - init(; n::Integer, delay::Float64) - Configure the ``delay`` between backtraces (measured in seconds), and the number ``n`` of instruction pointers that may be stored. Each instruction pointer corresponds to a single line of code; backtraces generally consist of a long list of instruction pointers. Default settings can be obtained by calling this function with no arguments, and each can be set independently using keywords or in the order ``(n, delay)``. .. function:: fetch() -> data - :: - - fetch() -> data - Returns a reference to the internal buffer of backtraces. Note that subsequent operations, like ``clear()``, can affect ``data`` unless you first make a copy. Note that the values in ``data`` have meaning only on this machine in the current session, because it depends on the exact memory addresses used in JIT-compiling. This function is primarily for internal use; ``retrieve()`` may be a better choice for most users. .. function:: retrieve() -> data, lidict - :: - - retrieve() -> data, lidict - set of all backtraces (``data``) and a dictionary that maps the values that store the file name, function name, and line number. This function allows you to save profiling results for future analysis. -.. function:: callers(funcname, [data, lidict], [filename=], [linerange=]) -> Vector{Tuple{count, linfo}} +.. function:: callers(funcname[, data, lidict][, filename=][, linerange=]) -> Vector{Tuple{count, linfo}} - :: - - callers(funcname[, data, lidict][, filename=][, linerange=]) -> Vector{Tuple{count, linfo}} - Given a previous profiling run, determine who called a particular function. Supplying the filename (and optionally, range of line numbers over which the function is defined) allows you to disambiguate an overloaded method. The returned value is a vector containing a count of the number of calls and line information about the caller. One can optionally supply backtrace data obtained from ``retrieve()``; otherwise, the current internal profile buffer is used. .. function:: clear_malloc_data() - :: - - clear_malloc_data() - Clears any stored memory allocation data when running julia with ` force JIT-compilation), then call ``clear_malloc_data()``. Then execute your command(s) again, quit Julia, and examine the resulting ``*.mem`` files. diff --git a/doc/stdlib/sort.rst b/doc/stdlib/sort.rst index 6d63982e9f15e..8ef13f75c3302 100644 --- a/doc/stdlib/sort.rst +++ b/doc/stdlib/sort.rst @@ -119,64 +119,36 @@ Sorting Functions .. function:: sort!(v, [alg=,] [by=,] [lt=,] [rev=false]) - :: - - sort!(v, [alg=,] [by=,] [lt=,] [rev=false]) - Sort the vector ``v`` in place. ``QuickSort`` is used by default for numeric arrays while ``MergeSort`` is used for other arrays. You can specify an algorithm to use via the ``alg`` keyword (see Sorting Algorithms for available algorithms). The ``by`` keyword lets you provide a function that will be applied to each element before comparison; the ``lt`` keyword allows providing a custom order. These options are independent and can be used together in all possible combinations: if both ``by`` and ``lt`` are specified, the ``lt`` function is applied to the result of the ``by`` function; ``rev=true`` reverses whatever ordering specified via the -.. function:: sort(v, [alg=,] [by=,] [lt=,] [rev=false]) +.. function:: sort(A, dim, [alg=,] [by=,] [lt=,] [rev=false]) - :: - - sort(A, dim, [alg=,] [by=,] [lt=,] [rev=false]) - Sort a multidimensional array ``A`` along the given dimension. .. function:: sort(A, dim, [alg=,] [by=,] [lt=,] [rev=false]) - :: - - sort(A, dim, [alg=,] [by=,] [lt=,] [rev=false]) - Sort a multidimensional array ``A`` along the given dimension. .. function:: sortperm(v, [alg=,] [by=,] [lt=,] [rev=false]) - :: - - sortperm(v, [alg=,] [by=,] [lt=,] [rev=false]) - Return a permutation vector of indices of ``v`` that puts it in sorted order. Specify ``alg`` to choose a particular sorting algorithm (see Sorting Algorithms). ``MergeSort`` is used by default, and since it is stable, the resulting permutation will be the lexicographically first one that puts the input array into sorted order – i.e. indices of equal elements appear in ascending order. If you choose a non-stable sorting algorithm such as order may be returned. The order is specified using the same keywords as ``sort!``. See also ``sortperm!()`` .. function:: sortperm!(ix, v, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false]) - :: - - sortperm!(ix, v, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false]) - Like ``sortperm``, but accepts a preallocated index vector ``ix``. If ``initialized`` is ``false`` (the default), ix is initialized to contain the values ``1:length(v)``. See also ``sortperm()`` .. function:: sortrows(A, [alg=,] [by=,] [lt=,] [rev=false]) - :: - - sortrows(A, [alg=,] [by=,] [lt=,] [rev=false]) - Sort the rows of matrix ``A`` lexicographically. .. function:: sortcols(A, [alg=,] [by=,] [lt=,] [rev=false]) - :: - - sortcols(A, [alg=,] [by=,] [lt=,] [rev=false]) - Sort the columns of matrix ``A`` lexicographically. @@ -185,55 +157,31 @@ Order-Related Functions .. function:: issorted(v, [by=,] [lt=,] [rev=false]) - :: - - issorted(v, [by=,] [lt=,] [rev=false]) - Test whether a vector is in sorted order. The ``by``, ``lt`` and as they do for ``sort``. .. function:: searchsorted(a, x, [by=,] [lt=,] [rev=false]) - :: - - searchsorted(a, x, [by=,] [lt=,] [rev=false]) - Returns the range of indices of ``a`` which compare as equal to order. Returns an empty range located at the insertion point if .. function:: searchsortedfirst(a, x, [by=,] [lt=,] [rev=false]) - :: - - searchsortedfirst(a, x, [by=,] [lt=,] [rev=false]) - Returns the index of the first value in ``a`` greater than or equal to ``x``, according to the specified order. Returns ``length(a)+1`` if ``x`` is greater than all values in ``a``. .. function:: searchsortedlast(a, x, [by=,] [lt=,] [rev=false]) - :: - - searchsortedlast(a, x, [by=,] [lt=,] [rev=false]) - Returns the index of the last value in ``a`` less than or equal to less than all values in ``a``. .. function:: select!(v, k, [by=,] [lt=,] [rev=false]) - :: - - select!(v, k, [by=,] [lt=,] [rev=false]) - Partially sort the vector ``v`` in place, according to the order specified by ``by``, ``lt`` and ``rev`` so that the value at index the position where it would appear if the array were fully sorted via a non-stable algorithm. If ``k`` is a single index, that value is returned; if ``k`` is a range, an array of values at those indices is returned. Note that ``select!`` does not fully sort the input array. .. function:: select(v, k, [by=,] [lt=,] [rev=false]) - :: - - select(v, k, [by=,] [lt=,] [rev=false]) - Variant of ``select!`` which copies ``v`` before partially sorting it, thereby returning the same thing as ``select!`` but leaving diff --git a/doc/stdlib/strings.rst b/doc/stdlib/strings.rst index 04e11ea903f81..d59f309ed1257 100644 --- a/doc/stdlib/strings.rst +++ b/doc/stdlib/strings.rst @@ -6,28 +6,16 @@ .. function:: length(s) - :: - - length(s) - The number of characters in string ``s``. .. function:: sizeof(s::AbstractString) - :: - - sizeof(s::AbstractString) - The number of bytes in string ``s``. .. function:: *(s, t) - :: - - *(s, t) - Concatenate strings. The ``*`` operator is an alias to this function. @@ -36,640 +24,356 @@ .. function:: ^(s, n) - :: - - ^(s, n) - Repeat ``n`` times the string ``s``. The ``^`` operator is an alias to this function. .. function:: string(xs...) - :: - - string(xs...) - Create a string from any values using the ``print`` function. .. function:: repr(x) - :: - - repr(x) - Create a string from any value using the ``showall`` function. -.. function:: bytestring(::Ptr{UInt8}, [length]) +.. function:: bytestring(s) - :: - - bytestring(s) - Convert a string to a contiguous byte array representation appropriate for passing it to C functions. The string will be encoded as either ASCII or UTF-8. .. function:: bytestring(s) - :: - - bytestring(s) - Convert a string to a contiguous byte array representation appropriate for passing it to C functions. The string will be encoded as either ASCII or UTF-8. -.. function:: ascii(::Array{UInt8,1}) +.. function:: ascii(::Ptr{UInt8}[, length]) - :: - - ascii(::Ptr{UInt8}[, length]) - Create an ASCII string from the address of a C (0-terminated) string encoded in ASCII. A copy is made; the ptr can be safely freed. If ``length`` is specified, the string does not have to be 0-terminated. -.. function:: ascii(s) +.. function:: ascii(::Ptr{UInt8}[, length]) - :: - - ascii(::Ptr{UInt8}[, length]) - Create an ASCII string from the address of a C (0-terminated) string encoded in ASCII. A copy is made; the ptr can be safely freed. If ``length`` is specified, the string does not have to be 0-terminated. -.. function:: ascii(::Ptr{UInt8}, [length]) +.. function:: ascii(::Ptr{UInt8}[, length]) - :: - - ascii(::Ptr{UInt8}[, length]) - Create an ASCII string from the address of a C (0-terminated) string encoded in ASCII. A copy is made; the ptr can be safely freed. If ``length`` is specified, the string does not have to be 0-terminated. -.. function:: utf8(::Array{UInt8,1}) +.. function:: utf8(s) - :: - - utf8(s) - Convert a string to a contiguous UTF-8 string (all characters must be valid UTF-8 characters). -.. function:: utf8(::Ptr{UInt8}, [length]) +.. function:: utf8(s) - :: - - utf8(s) - Convert a string to a contiguous UTF-8 string (all characters must be valid UTF-8 characters). .. function:: utf8(s) - :: - - utf8(s) - Convert a string to a contiguous UTF-8 string (all characters must be valid UTF-8 characters). .. function:: normalize_string(s, normalform::Symbol) - :: - - normalize_string(s, normalform::Symbol) - Normalize the string ``s`` according to one of the four ``normal forms`` of the Unicode standard: ``normalform`` can be ``:NFC``, composition) and D (canonical decomposition) convert different visually identical representations of the same abstract string into a single canonical form, with form C being more compact. Normal forms KC and KD additionally canonicalize ``compatibility equivalents``: they convert characters that are abstractly similar but visually distinct into a single canonical choice (e.g. they expand ligatures into the individual characters), with form KC being more compact. Alternatively, finer control and additional transformations may be be obtained by calling *normalize_string(s; keywords...)*, where any number of the following boolean keywords options (which all default to ``false`` except for ``compose``) are specified: For example, NFKC corresponds to the options ``compose=true, compat=true, stable=true``. .. function:: graphemes(s) -> iterator over substrings of s - :: - - graphemes(s) -> iterator over substrings of s - Returns an iterator over substrings of ``s`` that correspond to the extended graphemes in the string, as defined by Unicode UAX #29. even though they may contain more than one codepoint; for example a letter combined with an accent mark is a single grapheme.) -.. function:: isvalid(value) -> Bool +.. function:: isvalid(str, i) - :: - - isvalid(str, i) - Tells whether index ``i`` is valid for the given string -.. function:: isvalid(T, value) -> Bool +.. function:: isvalid(str, i) - :: - - isvalid(str, i) - Tells whether index ``i`` is valid for the given string .. function:: is_assigned_char(c) -> Bool - :: - - is_assigned_char(c) -> Bool - Returns true if the given char or integer is an assigned Unicode code point. .. function:: ismatch(r::Regex, s::AbstractString) -> Bool - :: - - ismatch(r::Regex, s::AbstractString) -> Bool - Test whether a string contains a match of the given regular expression. .. function:: match(r::Regex, s::AbstractString[, idx::Integer[, addopts]]) - :: - - match(r::Regex, s::AbstractString[, idx::Integer[, addopts]]) - Search for the first match of the regular expression ``r`` in ``s`` and return a RegexMatch object containing the match, or nothing if the match failed. The matching substring can be retrieved by accessing ``m.match`` and the captured sequences can be retrieved by accessing ``m.captures`` The optional ``idx`` argument specifies an index at which to start the search. .. function:: eachmatch(r::Regex, s::AbstractString[, overlap::Bool=false]) - :: - - eachmatch(r::Regex, s::AbstractString[, overlap::Bool=false]) - Search for all matches of a the regular expression ``r`` in ``s`` and return a iterator over the matches. If overlap is true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from distinct character ranges. .. function:: matchall(r::Regex, s::AbstractString[, overlap::Bool=false]) -> Vector{AbstractString} - :: - - matchall(r::Regex, s::AbstractString[, overlap::Bool=false]) -> Vector{AbstractString} - Return a vector of the matching substrings from eachmatch. .. function:: lpad(string, n, p) - :: - - lpad(string, n, p) - Make a string at least ``n`` columns wide when printed, by padding on the left with copies of ``p``. .. function:: rpad(string, n, p) - :: - - rpad(string, n, p) - Make a string at least ``n`` columns wide when printed, by padding on the right with copies of ``p``. -.. function:: search(string, chars, [start]) +.. function:: search(string, chars[, start]) - :: - - search(string, chars[, start]) - Search for the first occurrence of the given characters within the given string. The second argument may be a single character, a vector or a set of characters, a string, or a regular expression such as ASCII or UTF-8 strings). The third argument optionally specifies a starting index. The return value is a range of indexes where the matching sequence is found, such that ``s[search(s,x)] == x``: -.. function:: rsearch(string, chars, [start]) +.. function:: rsearch(string, chars[, start]) - :: - - rsearch(string, chars[, start]) - Similar to ``search``, but returning the last occurrence of the given characters within the given string, searching in reverse from -.. function:: searchindex(string, substring, [start]) +.. function:: searchindex(string, substring[, start]) - :: - - searchindex(string, substring[, start]) - Similar to ``search``, but return only the start index at which the substring is found, or 0 if it is not. -.. function:: rsearchindex(string, substring, [start]) +.. function:: rsearchindex(string, substring[, start]) - :: - - rsearchindex(string, substring[, start]) - Similar to ``rsearch``, but return only the start index at which the substring is found, or 0 if it is not. .. function:: contains(haystack, needle) - :: - - contains(haystack, needle) - Determine whether the second argument is a substring of the first. .. function:: replace(string, pat, r[, n]) - :: - - replace(string, pat, r[, n]) - Search for the given pattern ``pat``, and replace each occurrence with ``r``. If ``n`` is provided, replace at most ``n`` occurrences. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. If ``r`` is a function, each occurrence is replaced with ``r(s)`` where ``s`` is the matched substring. .. function:: split(string, [chars]; limit=0, keep=true) - :: - - split(string, [chars]; limit=0, keep=true) - Return an array of substrings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by ``search``'s second argument (i.e. a single character, collection of characters, string, or regular expression). If ``chars`` is omitted, it defaults to the set of all space characters, and ``keep`` is taken to be false. The two keyword arguments are optional: they are are a maximum size for the result and a flag determining whether empty fields should be kept in the result. .. function:: rsplit(string, [chars]; limit=0, keep=true) - :: - - rsplit(string, [chars]; limit=0, keep=true) - Similar to ``split``, but starting from the end of the string. -.. function:: strip(string, [chars]) +.. function:: strip(string[, chars]) - :: - - strip(string[, chars]) - Return ``string`` with any leading and trailing whitespace removed. If ``chars`` (a character, or vector or set of characters) is provided, instead remove characters contained in it. -.. function:: lstrip(string, [chars]) +.. function:: lstrip(string[, chars]) - :: - - lstrip(string[, chars]) - Return ``string`` with any leading whitespace removed. If ``chars`` remove characters contained in it. -.. function:: rstrip(string, [chars]) +.. function:: rstrip(string[, chars]) - :: - - rstrip(string[, chars]) - Return ``string`` with any trailing whitespace removed. If provided, instead remove characters contained in it. .. function:: startswith(string, prefix | chars) - :: - - startswith(string, prefix | chars) - Returns ``true`` if ``string`` starts with ``prefix``. If the second argument is a vector or set of characters, tests whether the first character of ``string`` belongs to that set. .. function:: endswith(string, suffix | chars) - :: - - endswith(string, suffix | chars) - Returns ``true`` if ``string`` ends with ``suffix``. If the second argument is a vector or set of characters, tests whether the last character of ``string`` belongs to that set. .. function:: uppercase(string) - :: - - uppercase(string) - Returns ``string`` with all characters converted to uppercase. .. function:: lowercase(string) - :: - - lowercase(string) - Returns ``string`` with all characters converted to lowercase. .. function:: ucfirst(string) - :: - - ucfirst(string) - Returns ``string`` with the first character converted to uppercase. .. function:: lcfirst(string) - :: - - lcfirst(string) - Returns ``string`` with the first character converted to lowercase. -.. function:: join(strings, delim, [last]) +.. function:: join(strings, delim[, last]) - :: - - join(strings, delim[, last]) - Join an array of ``strings`` into a single string, inserting the given delimiter between adjacent strings. If ``last`` is given, it will be used instead of ``delim`` between the last two strings. For example, ``join([``apples``, `bananas``, ``pineapples``], ``, `, convertible to strings via `print(io::IOBuffer, x)``. .. function:: chop(string) - :: - - chop(string) - Remove the last character from a string .. function:: chomp(string) - :: - - chomp(string) - Remove a trailing newline from a string .. function:: ind2chr(string, i) - :: - - ind2chr(string, i) - Convert a byte index to a character index .. function:: chr2ind(string, i) - :: - - chr2ind(string, i) - Convert a character index to a byte index .. function:: isvalid(str, i) - :: - - isvalid(str, i) - Tells whether index ``i`` is valid for the given string .. function:: nextind(str, i) - :: - - nextind(str, i) - Get the next valid string index after ``i``. Returns a value greater than ``endof(str)`` at or after the end of the string. .. function:: prevind(str, i) - :: - - prevind(str, i) - Get the previous valid string index before ``i``. Returns a value less than ``1`` at the beginning of the string. -.. function:: randstring([rng,] len=8) +.. function:: randstring([rng], len=8) - :: - - randstring([rng], len=8) - Create a random ASCII string of length ``len``, consisting of upper- and lower-case letters and the digits 0-9. The optional Numbers*. .. function:: charwidth(c) - :: - - charwidth(c) - Gives the number of columns needed to print a character. .. function:: strwidth(s) - :: - - strwidth(s) - Gives the number of columns needed to print a string. -.. function:: isalnum(c::Union{Char,AbstractString}) -> Bool +.. function:: isalnum(c::Union{Char, AbstractString}) -> Bool - :: - - isalnum(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is alphanumeric, or whether this is true for all elements of a string. A character is classified as alphabetic if it belongs to the Unicode general category Letter or Number, i.e. a character whose category code begins with 'L' or -.. function:: isalpha(c::Union{Char,AbstractString}) -> Bool +.. function:: isalpha(c::Union{Char, AbstractString}) -> Bool - :: - - isalpha(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is alphabetic, or whether this is true for all elements of a string. A character is classified as alphabetic if it belongs to the Unicode general category Letter, i.e. a character whose category code begins with 'L'. -.. function:: isascii(c::Union{Char,AbstractString}) -> Bool +.. function:: isascii(c::Union{Char, AbstractString}) -> Bool - :: - - isascii(c::Union{Char, AbstractString}) -> Bool - Tests whether a character belongs to the ASCII character set, or whether this is true for all elements of a string. -.. function:: iscntrl(c::Union{Char,AbstractString}) -> Bool +.. function:: iscntrl(c::Union{Char, AbstractString}) -> Bool - :: - - iscntrl(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is a control character, or whether this is true for all elements of a string. Control characters are the non-printing characters of the Latin-1 subset of Unicode. -.. function:: isdigit(c::Union{Char,AbstractString}) -> Bool +.. function:: isdigit(c::Union{Char, AbstractString}) -> Bool - :: - - isdigit(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is a numeric digit (0-9), or whether this is true for all elements of a string. -.. function:: isgraph(c::Union{Char,AbstractString}) -> Bool +.. function:: isgraph(c::Union{Char, AbstractString}) -> Bool - :: - - isgraph(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is printable, and not a space, or whether this is true for all elements of a string. Any character that would cause a printer to use ink should be classified with isgraph(c)==true. -.. function:: islower(c::Union{Char,AbstractString}) -> Bool +.. function:: islower(c::Union{Char, AbstractString}) -> Bool - :: - - islower(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is a lowercase letter, or whether this is true for all elements of a string. A character is classified as lowercase if it belongs to Unicode category Ll, Letter: Lowercase. -.. function:: isnumber(c::Union{Char,AbstractString}) -> Bool +.. function:: isnumber(c::Union{Char, AbstractString}) -> Bool - :: - - isnumber(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is numeric, or whether this is true for all elements of a string. A character is classified as numeric if it belongs to the Unicode general category Number, i.e. a character whose category code begins with 'N'. -.. function:: isprint(c::Union{Char,AbstractString}) -> Bool +.. function:: isprint(c::Union{Char, AbstractString}) -> Bool - :: - - isprint(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is printable, including spaces, but not a control character. For strings, tests whether this is true for all elements of the string. -.. function:: ispunct(c::Union{Char,AbstractString}) -> Bool +.. function:: ispunct(c::Union{Char, AbstractString}) -> Bool - :: - - ispunct(c::Union{Char, AbstractString}) -> Bool - Tests whether a character belongs to the Unicode general category Punctuation, i.e. a character whose category code begins with 'P'. For strings, tests whether this is true for all elements of the string. -.. function:: isspace(c::Union{Char,AbstractString}) -> Bool +.. function:: isspace(c::Union{Char, AbstractString}) -> Bool - :: - - isspace(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is any whitespace character. Includes ASCII characters '\t', '\n', '\v', '\f', '\r', and ' ', Latin-1 character U+0085, and characters in Unicode category Zs. For strings, tests whether this is true for all elements of the string. -.. function:: isupper(c::Union{Char,AbstractString}) -> Bool +.. function:: isupper(c::Union{Char, AbstractString}) -> Bool - :: - - isupper(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is an uppercase letter, or whether this is true for all elements of a string. A character is classified as uppercase if it belongs to Unicode category Lu, Letter: Uppercase, or Lt, Letter: Titlecase. -.. function:: isxdigit(c::Union{Char,AbstractString}) -> Bool +.. function:: isxdigit(c::Union{Char, AbstractString}) -> Bool - :: - - isxdigit(c::Union{Char, AbstractString}) -> Bool - Tests whether a character is a valid hexadecimal digit, or whether this is true for all elements of a string. .. function:: symbol(x...) -> Symbol - :: - - symbol(x...) -> Symbol - Create a ``Symbol`` by concatenating the string representations of the arguments together. .. function:: escape_string(str::AbstractString) -> AbstractString - :: - - escape_string(str::AbstractString) -> AbstractString - General escaping of traditional C and Unicode escape sequences. See .. function:: unescape_string(s::AbstractString) -> AbstractString - :: - - unescape_string(s::AbstractString) -> AbstractString - General unescaping of traditional C and Unicode escape sequences. Reverse of ``escape_string()``. See also ``print_unescaped()``. -.. function:: utf16(s) +.. function:: utf16(::Union{Ptr{UInt16}, Ptr{Int16}}[, length]) - :: - - utf16(::Union{Ptr{UInt16}, Ptr{Int16}}[, length]) - Create a string from the address of a NUL-terminated UTF-16 string. A copy is made; the pointer can be safely freed. If ``length`` is specified, the string does not have to be NUL-terminated. -.. function:: utf16(::Union{Ptr{UInt16},Ptr{Int16}} [, length]) +.. function:: utf16(::Union{Ptr{UInt16}, Ptr{Int16}}[, length]) - :: - - utf16(::Union{Ptr{UInt16}, Ptr{Int16}}[, length]) - Create a string from the address of a NUL-terminated UTF-16 string. A copy is made; the pointer can be safely freed. If ``length`` is specified, the string does not have to be NUL-terminated. -.. function:: utf32(s) +.. function:: wstring(s) - :: - - wstring(s) - This is a synonym for either ``utf32(s)`` or ``utf16(s)``, depending on whether ``Cwchar_t`` is 32 or 16 bits, respectively. The synonym ``WString`` for ``UTF32String`` or ``UTF16String`` is also provided. -.. function:: utf32(::Union{Ptr{Char},Ptr{UInt32},Ptr{Int32}} [, length]) +.. function:: wstring(s) - :: - - wstring(s) - This is a synonym for either ``utf32(s)`` or ``utf16(s)``, depending on whether ``Cwchar_t`` is 32 or 16 bits, respectively. The synonym ``WString`` for ``UTF32String`` or ``UTF16String`` is also provided. .. function:: wstring(s) - :: - - wstring(s) - This is a synonym for either ``utf32(s)`` or ``utf16(s)``, depending on whether ``Cwchar_t`` is 32 or 16 bits, respectively. The synonym ``WString`` for ``UTF32String`` or ``UTF16String`` is also provided. diff --git a/doc/stdlib/test.rst b/doc/stdlib/test.rst index e7cd69d6333a9..e4c89950d799c 100644 --- a/doc/stdlib/test.rst +++ b/doc/stdlib/test.rst @@ -12,12 +12,8 @@ binary install, you can run the test suite using ``Base.runtests()``. .. currentmodule:: Base -.. function:: runtests([tests=["all"] [, numcores=iceil(CPU_CORES/2) ]]) +.. function:: runtests([tests=["all"][, numcores=iceil(CPU_CORES/2)]]) - :: - - runtests([tests=["all"][, numcores=iceil(CPU_CORES/2)]]) - Run the Julia unit tests listed in ``tests``, which can be either a string or an array of strings, using ``numcores`` processors. (not exported) @@ -135,37 +131,21 @@ Macros .. function:: @test(ex) - :: - - @test(ex) - Test the expression ``ex`` and calls the current handler to handle the result. .. function:: @test_throws(extype, ex) - :: - - @test_throws(extype, ex) - Test that the expression ``ex`` throws an exception of type .. function:: @test_approx_eq(a, b) - :: - - @test_approx_eq(a, b) - Test two floating point numbers ``a`` and ``b`` for equality taking in account small numerical errors. .. function:: @test_approx_eq_eps(a, b, tol) - :: - - @test_approx_eq_eps(a, b, tol) - Test two floating point numbers ``a`` and ``b`` for equality taking in account a margin of tolerance given by ``tol``. @@ -174,10 +154,6 @@ Functions .. function:: with_handler(f, handler) - :: - - with_handler(f, handler) - Run the function ``f`` using the ``handler`` as the handler.