idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
149,200
public static void inner_reorder_lower ( DMatrix1Row A , DMatrix1Row B ) { final int cols = A . numCols ; B . reshape ( cols , cols ) ; Arrays . fill ( B . data , 0 ) ; for ( int i = 0 ; i < cols ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { B . data [ i * cols + j ] += A . data [ i ] * A . data [ j ] ; } for ( int k = 1 ; k < A . numRows ; k ++ ) { int indexRow = k * cols ; double valI = A . data [ i + indexRow ] ; int indexB = i * cols ; for ( int j = 0 ; j <= i ; j ++ ) { B . data [ indexB ++ ] += valI * A . data [ indexRow ++ ] ; } } } }
Computes the inner product of A times A and stores the results in B . The inner product is symmetric and this function will only store the lower triangle . The value of the upper triangular matrix is undefined .
209
42
149,201
public static void pow ( ComplexPolar_F64 a , int N , ComplexPolar_F64 result ) { result . r = Math . pow ( a . r , N ) ; result . theta = N * a . theta ; }
Computes the power of a complex number in polar notation
53
11
149,202
public static void sqrt ( Complex_F64 input , Complex_F64 root ) { double r = input . getMagnitude ( ) ; double a = input . real ; root . real = Math . sqrt ( ( r + a ) / 2.0 ) ; root . imaginary = Math . sqrt ( ( r - a ) / 2.0 ) ; if ( input . imaginary < 0 ) root . imaginary = - root . imaginary ; }
Computes the square root of the complex number .
95
10
149,203
public boolean computeDirect ( DMatrixRMaj A ) { initPower ( A ) ; boolean converged = false ; for ( int i = 0 ; i < maxIterations && ! converged ; i ++ ) { // q0.print(); CommonOps_DDRM . mult ( A , q0 , q1 ) ; double s = NormOps_DDRM . normPInf ( q1 ) ; CommonOps_DDRM . divide ( q1 , s , q2 ) ; converged = checkConverged ( A ) ; } return converged ; }
This method computes the eigen vector with the largest eigen value by using the direct power method . This technique is the easiest to implement but the slowest to converge . Works only if all the eigenvalues are real .
123
46
149,204
private boolean checkConverged ( DMatrixRMaj A ) { double worst = 0 ; double worst2 = 0 ; for ( int j = 0 ; j < A . numRows ; j ++ ) { double val = Math . abs ( q2 . data [ j ] - q0 . data [ j ] ) ; if ( val > worst ) worst = val ; val = Math . abs ( q2 . data [ j ] + q0 . data [ j ] ) ; if ( val > worst2 ) worst2 = val ; } // swap vectors DMatrixRMaj temp = q0 ; q0 = q2 ; q2 = temp ; if ( worst < tol ) return true ; else if ( worst2 < tol ) return true ; else return false ; }
Test for convergence by seeing if the element with the largest change is smaller than the tolerance . In some test cases it alternated between the + and - values of the eigen vector . When this happens it seems to have converged to a non - dominant eigen vector . At least in the case I looked at . I haven t devoted a lot of time into this issue ...
166
76
149,205
public void setup ( int numSamples , int sampleSize ) { mean = new double [ sampleSize ] ; A . reshape ( numSamples , sampleSize , false ) ; sampleIndex = 0 ; numComponents = - 1 ; }
Must be called before any other functions . Declares and sets up internal data structures .
51
17
149,206
public double [ ] getBasisVector ( int which ) { if ( which < 0 || which >= numComponents ) throw new IllegalArgumentException ( "Invalid component" ) ; DMatrixRMaj v = new DMatrixRMaj ( 1 , A . numCols ) ; CommonOps_DDRM . extract ( V_t , which , which + 1 , 0 , A . numCols , v , 0 , 0 ) ; return v . data ; }
Returns a vector from the PCA s basis .
101
10
149,207
public double [ ] sampleToEigenSpace ( double [ ] sampleData ) { if ( sampleData . length != A . getNumCols ( ) ) throw new IllegalArgumentException ( "Unexpected sample length" ) ; DMatrixRMaj mean = DMatrixRMaj . wrap ( A . getNumCols ( ) , 1 , this . mean ) ; DMatrixRMaj s = new DMatrixRMaj ( A . getNumCols ( ) , 1 , true , sampleData ) ; DMatrixRMaj r = new DMatrixRMaj ( numComponents , 1 ) ; CommonOps_DDRM . subtract ( s , mean , s ) ; CommonOps_DDRM . mult ( V_t , s , r ) ; return r . data ; }
Converts a vector from sample space into eigen space .
171
12
149,208
public double [ ] eigenToSampleSpace ( double [ ] eigenData ) { if ( eigenData . length != numComponents ) throw new IllegalArgumentException ( "Unexpected sample length" ) ; DMatrixRMaj s = new DMatrixRMaj ( A . getNumCols ( ) , 1 ) ; DMatrixRMaj r = DMatrixRMaj . wrap ( numComponents , 1 , eigenData ) ; CommonOps_DDRM . multTransA ( V_t , r , s ) ; DMatrixRMaj mean = DMatrixRMaj . wrap ( A . getNumCols ( ) , 1 , this . mean ) ; CommonOps_DDRM . add ( s , mean , s ) ; return s . data ; }
Converts a vector from eigen space into sample space .
170
12
149,209
public double response ( double [ ] sample ) { if ( sample . length != A . numCols ) throw new IllegalArgumentException ( "Expected input vector to be in sample space" ) ; DMatrixRMaj dots = new DMatrixRMaj ( numComponents , 1 ) ; DMatrixRMaj s = DMatrixRMaj . wrap ( A . numCols , 1 , sample ) ; CommonOps_DDRM . mult ( V_t , s , dots ) ; return NormOps_DDRM . normF ( dots ) ; }
Computes the dot product of each basis vector against the sample . Can be used as a measure for membership in the training sample set . High values correspond to a better fit .
122
35
149,210
public static < T extends DMatrix > boolean decomposeSafe ( DecompositionInterface < T > decomp , T M ) { if ( decomp . inputModified ( ) ) { return decomp . decompose ( M . < T > copy ( ) ) ; } else { return decomp . decompose ( M ) ; } }
A simple convinience function that decomposes the matrix but automatically checks the input ti make sure is not being modified .
68
23
149,211
public static DMatrix2 extractColumn ( DMatrix2x2 a , int column , DMatrix2 out ) { if ( out == null ) out = new DMatrix2 ( ) ; switch ( column ) { case 0 : out . a1 = a . a11 ; out . a2 = a . a21 ; break ; case 1 : out . a1 = a . a12 ; out . a2 = a . a22 ; break ; default : throw new IllegalArgumentException ( "Out of bounds column. column = " + column ) ; } return out ; }
Extracts the column from the matrix a .
125
10
149,212
public static boolean decomposeSafe ( DecompositionInterface < ZMatrixRMaj > decomposition , ZMatrixRMaj a ) { if ( decomposition . inputModified ( ) ) { a = a . copy ( ) ; } return decomposition . decompose ( a ) ; }
Decomposes the input matrix a and makes sure it isn t modified .
59
15
149,213
public static void invert ( final int blockLength , final boolean upper , final DSubmatrixD1 T , final DSubmatrixD1 T_inv , final double temp [ ] ) { if ( upper ) throw new IllegalArgumentException ( "Upper triangular matrices not supported yet" ) ; if ( temp . length < blockLength * blockLength ) throw new IllegalArgumentException ( "Temp must be at least blockLength*blockLength long." ) ; if ( T . row0 != T_inv . row0 || T . row1 != T_inv . row1 || T . col0 != T_inv . col0 || T . col1 != T_inv . col1 ) throw new IllegalArgumentException ( "T and T_inv must be at the same elements in the matrix" ) ; final int M = T . row1 - T . row0 ; final double dataT [ ] = T . original . data ; final double dataX [ ] = T_inv . original . data ; final int offsetT = T . row0 * T . original . numCols + M * T . col0 ; for ( int i = 0 ; i < M ; i += blockLength ) { int heightT = Math . min ( T . row1 - ( i + T . row0 ) , blockLength ) ; int indexII = offsetT + T . original . numCols * ( i + T . row0 ) + heightT * ( i + T . col0 ) ; for ( int j = 0 ; j < i ; j += blockLength ) { int widthX = Math . min ( T . col1 - ( j + T . col0 ) , blockLength ) ; for ( int w = 0 ; w < temp . length ; w ++ ) { temp [ w ] = 0 ; } for ( int k = j ; k < i ; k += blockLength ) { int widthT = Math . min ( T . col1 - ( k + T . col0 ) , blockLength ) ; int indexL = offsetT + T . original . numCols * ( i + T . row0 ) + heightT * ( k + T . col0 ) ; int indexX = offsetT + T . original . numCols * ( k + T . row0 ) + widthT * ( j + T . col0 ) ; blockMultMinus ( dataT , dataX , temp , indexL , indexX , 0 , heightT , widthT , widthX ) ; } int indexX = offsetT + T . original . numCols * ( i + T . row0 ) + heightT * ( j + T . col0 ) ; InnerTriangularSolver_DDRB . solveL ( dataT , temp , heightT , widthX , heightT , indexII , 0 ) ; System . arraycopy ( temp , 0 , dataX , indexX , widthX * heightT ) ; } InnerTriangularSolver_DDRB . invertLower ( dataT , dataX , heightT , indexII , indexII ) ; } }
Inverts an upper or lower triangular block submatrix .
659
12
149,214
public static DMatrixRMaj [ ] span ( int dimen , int numVectors , Random rand ) { if ( dimen < numVectors ) throw new IllegalArgumentException ( "The number of vectors must be less than or equal to the dimension" ) ; DMatrixRMaj u [ ] = new DMatrixRMaj [ numVectors ] ; u [ 0 ] = RandomMatrices_DDRM . rectangle ( dimen , 1 , - 1 , 1 , rand ) ; NormOps_DDRM . normalizeF ( u [ 0 ] ) ; for ( int i = 1 ; i < numVectors ; i ++ ) { // System.out.println(" i = "+i); DMatrixRMaj a = new DMatrixRMaj ( dimen , 1 ) ; DMatrixRMaj r = null ; for ( int j = 0 ; j < i ; j ++ ) { // System.out.println("j = "+j); if ( j == 0 ) r = RandomMatrices_DDRM . rectangle ( dimen , 1 , - 1 , 1 , rand ) ; // find a vector that is normal to vector j // u[i] = (1/2)*(r + Q[j]*r) a . set ( r ) ; VectorVectorMult_DDRM . householder ( - 2.0 , u [ j ] , r , a ) ; CommonOps_DDRM . add ( r , a , a ) ; CommonOps_DDRM . scale ( 0.5 , a ) ; // UtilEjml.print(a); DMatrixRMaj t = a ; a = r ; r = t ; // normalize it so it doesn't get too small double val = NormOps_DDRM . normF ( r ) ; if ( val == 0 || Double . isNaN ( val ) || Double . isInfinite ( val ) ) throw new RuntimeException ( "Failed sanity check" ) ; CommonOps_DDRM . divide ( r , val ) ; } u [ i ] = r ; } return u ; }
is there a faster algorithm out there? This one is a bit sluggish
458
14
149,215
public static DMatrixRMaj insideSpan ( DMatrixRMaj [ ] span , double min , double max , Random rand ) { DMatrixRMaj A = new DMatrixRMaj ( span . length , 1 ) ; DMatrixRMaj B = new DMatrixRMaj ( span [ 0 ] . getNumElements ( ) , 1 ) ; for ( int i = 0 ; i < span . length ; i ++ ) { B . set ( span [ i ] ) ; double val = rand . nextDouble ( ) * ( max - min ) + min ; CommonOps_DDRM . scale ( val , B ) ; CommonOps_DDRM . add ( A , B , A ) ; } return A ; }
Creates a random vector that is inside the specified span .
160
12
149,216
public static DMatrixRMaj diagonal ( int N , double min , double max , Random rand ) { return diagonal ( N , N , min , max , rand ) ; }
Creates a random diagonal matrix where the diagonal elements are selected from a uniform distribution that goes from min to max .
37
23
149,217
public static DMatrixRMaj diagonal ( int numRows , int numCols , double min , double max , Random rand ) { if ( max < min ) throw new IllegalArgumentException ( "The max must be >= the min" ) ; DMatrixRMaj ret = new DMatrixRMaj ( numRows , numCols ) ; int N = Math . min ( numRows , numCols ) ; double r = max - min ; for ( int i = 0 ; i < N ; i ++ ) { ret . set ( i , i , rand . nextDouble ( ) * r + min ) ; } return ret ; }
Creates a random matrix where all elements are zero but diagonal elements . Diagonal elements randomly drawn from a uniform distribution from min to max inclusive .
139
29
149,218
public static DMatrixRMaj symmetricWithEigenvalues ( int num , Random rand , double ... eigenvalues ) { DMatrixRMaj V = RandomMatrices_DDRM . orthogonal ( num , num , rand ) ; DMatrixRMaj D = CommonOps_DDRM . diag ( eigenvalues ) ; DMatrixRMaj temp = new DMatrixRMaj ( num , num ) ; CommonOps_DDRM . mult ( V , D , temp ) ; CommonOps_DDRM . multTransB ( temp , V , D ) ; return D ; }
Creates a new random symmetric matrix that will have the specified real eigenvalues .
132
18
149,219
public static BMatrixRMaj randomBinary ( int numRow , int numCol , Random rand ) { BMatrixRMaj mat = new BMatrixRMaj ( numRow , numCol ) ; setRandomB ( mat , rand ) ; return mat ; }
Returns new boolean matrix with true or false values selected with equal probability .
54
14
149,220
public static DMatrixRMaj symmetric ( int length , double min , double max , Random rand ) { DMatrixRMaj A = new DMatrixRMaj ( length , length ) ; symmetric ( A , min , max , rand ) ; return A ; }
Creates a random symmetric matrix whose values are selected from an uniform distribution from min to max inclusive .
58
21
149,221
public static void symmetric ( DMatrixRMaj A , double min , double max , Random rand ) { if ( A . numRows != A . numCols ) throw new IllegalArgumentException ( "A must be a square matrix" ) ; double range = max - min ; int length = A . numRows ; for ( int i = 0 ; i < length ; i ++ ) { for ( int j = i ; j < length ; j ++ ) { double val = rand . nextDouble ( ) * range + min ; A . set ( i , j , val ) ; A . set ( j , i , val ) ; } } }
Sets the provided square matrix to be a random symmetric matrix whose values are selected from an uniform distribution from min to max inclusive .
139
27
149,222
public static DMatrixRMaj triangularUpper ( int dimen , int hessenberg , double min , double max , Random rand ) { if ( hessenberg < 0 ) throw new RuntimeException ( "hessenberg must be more than or equal to 0" ) ; double range = max - min ; DMatrixRMaj A = new DMatrixRMaj ( dimen , dimen ) ; for ( int i = 0 ; i < dimen ; i ++ ) { int start = i <= hessenberg ? 0 : i - hessenberg ; for ( int j = start ; j < dimen ; j ++ ) { A . set ( i , j , rand . nextDouble ( ) * range + min ) ; } } return A ; }
Creates an upper triangular matrix whose values are selected from a uniform distribution . If hessenberg is greater than zero then a hessenberg matrix of the specified degree is created instead .
160
37
149,223
public double computeLikelihoodP ( ) { double ret = 1.0 ; for ( int i = 0 ; i < r . numRows ; i ++ ) { double a = r . get ( i , 0 ) ; ret *= Math . exp ( - a * a / 2.0 ) ; } return ret ; }
Computes the likelihood of the random draw
69
8
149,224
@ Override public boolean decompose ( DMatrixRMaj orig ) { if ( orig . numCols != orig . numRows ) throw new IllegalArgumentException ( "Matrix must be square." ) ; if ( orig . numCols <= 0 ) return false ; int N = orig . numRows ; // compute a similar tridiagonal matrix if ( ! decomp . decompose ( orig ) ) return false ; if ( diag == null || diag . length < N ) { diag = new double [ N ] ; off = new double [ N - 1 ] ; } decomp . getDiagonal ( diag , off ) ; // Tell the helper to work with this matrix helper . init ( diag , off , N ) ; if ( computeVectors ) { if ( computeVectorsWithValues ) { return extractTogether ( ) ; } else { return extractSeparate ( N ) ; } } else { return computeEigenValues ( ) ; } }
Decomposes the matrix using the QR algorithm . Care was taken to minimize unnecessary memory copying and cache skipping .
206
22
149,225
private boolean computeEigenValues ( ) { // make a copy of the internal tridiagonal matrix data for later use diagSaved = helper . copyDiag ( diagSaved ) ; offSaved = helper . copyOff ( offSaved ) ; vector . setQ ( null ) ; vector . setFastEigenvalues ( true ) ; // extract the eigenvalues if ( ! vector . process ( - 1 , null , null ) ) return false ; // save a copy of them since this data structure will be recycled next values = helper . copyEigenvalues ( values ) ; return true ; }
Computes eigenvalues only
128
6
149,226
protected void solveL ( double [ ] vv ) { int ii = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int ip = indx [ i ] ; double sumReal = vv [ ip * 2 ] ; double sumImg = vv [ ip * 2 + 1 ] ; vv [ ip * 2 ] = vv [ i * 2 ] ; vv [ ip * 2 + 1 ] = vv [ i * 2 + 1 ] ; if ( ii != 0 ) { // for( int j = ii-1; j < i; j++ ) // sum -= dataLU[i* n +j]*vv[j]; int index = i * stride + ( ii - 1 ) * 2 ; for ( int j = ii - 1 ; j < i ; j ++ ) { double luReal = dataLU [ index ++ ] ; double luImg = dataLU [ index ++ ] ; double vvReal = vv [ j * 2 ] ; double vvImg = vv [ j * 2 + 1 ] ; sumReal -= luReal * vvReal - luImg * vvImg ; sumImg -= luReal * vvImg + luImg * vvReal ; } } else if ( sumReal * sumReal + sumImg * sumImg != 0.0 ) { ii = i + 1 ; } vv [ i * 2 ] = sumReal ; vv [ i * 2 + 1 ] = sumImg ; } }
Solve the using the lower triangular matrix in LU . Diagonal elements are assumed to be 1
332
19
149,227
public boolean decompose ( DMatrixRMaj mat , int indexStart , int n ) { double m [ ] = mat . data ; double el_ii ; double div_el_ii = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { double sum = m [ indexStart + i * mat . numCols + j ] ; int iEl = i * n ; int jEl = j * n ; int end = iEl + i ; // k = 0:i-1 for ( ; iEl < end ; iEl ++ , jEl ++ ) { // sum -= el[i*n+k]*el[j*n+k]; sum -= el [ iEl ] * el [ jEl ] ; } if ( i == j ) { // is it positive-definate? if ( sum <= 0.0 ) return false ; el_ii = Math . sqrt ( sum ) ; el [ i * n + i ] = el_ii ; m [ indexStart + i * mat . numCols + i ] = el_ii ; div_el_ii = 1.0 / el_ii ; } else { double v = sum * div_el_ii ; el [ j * n + i ] = v ; m [ indexStart + j * mat . numCols + i ] = v ; } } } return true ; }
Decomposes a submatrix . The results are written to the submatrix and to its internal matrix L .
311
24
149,228
public static List < int [ ] > createList ( int N ) { int data [ ] = new int [ N ] ; for ( int i = 0 ; i < data . length ; i ++ ) { data [ i ] = - 1 ; } List < int [ ] > ret = new ArrayList < int [ ] > ( ) ; createList ( data , 0 , - 1 , ret ) ; return ret ; }
Creates a list of all permutations for a set with N elements .
88
15
149,229
private static void createList ( int data [ ] , int k , int level , List < int [ ] > ret ) { data [ k ] = level ; if ( level < data . length - 1 ) { for ( int i = 0 ; i < data . length ; i ++ ) { if ( data [ i ] == - 1 ) { createList ( data , i , level + 1 , ret ) ; } } } else { int [ ] copy = new int [ data . length ] ; System . arraycopy ( data , 0 , copy , 0 , data . length ) ; ret . add ( copy ) ; } data [ k ] = - 1 ; }
Internal function that uses recursion to create the list
139
10
149,230
public int [ ] next ( ) { boolean hasNewPerm = false ; escape : while ( level >= 0 ) { // boolean foundZero = false; for ( int i = iter [ level ] ; i < data . length ; i = iter [ level ] ) { iter [ level ] ++ ; if ( data [ i ] == - 1 ) { level ++ ; data [ i ] = level - 1 ; if ( level >= data . length ) { // a new permutation has been created return the results. hasNewPerm = true ; System . arraycopy ( data , 0 , ret , 0 , ret . length ) ; level = level - 1 ; data [ i ] = - 1 ; break escape ; } else { valk [ level ] = i ; } } } data [ valk [ level ] ] = - 1 ; iter [ level ] = 0 ; level = level - 1 ; } if ( hasNewPerm ) return ret ; return null ; }
Creates the next permutation in the sequence .
202
10
149,231
public static DMatrixSparseTriplet uniform ( int numRows , int numCols , int nz_total , double min , double max , Random rand ) { // Create a list of all the possible element values int N = numCols * numRows ; if ( N < 0 ) throw new IllegalArgumentException ( "matrix size is too large" ) ; nz_total = Math . min ( N , nz_total ) ; int selected [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { selected [ i ] = i ; } for ( int i = 0 ; i < nz_total ; i ++ ) { int s = rand . nextInt ( N ) ; int tmp = selected [ s ] ; selected [ s ] = selected [ i ] ; selected [ i ] = tmp ; } // Create a sparse matrix DMatrixSparseTriplet ret = new DMatrixSparseTriplet ( numRows , numCols , nz_total ) ; for ( int i = 0 ; i < nz_total ; i ++ ) { int row = selected [ i ] / numCols ; int col = selected [ i ] % numCols ; double value = rand . nextDouble ( ) * ( max - min ) + min ; ret . addItem ( row , col , value ) ; } return ret ; }
Randomly generates matrix with the specified number of matrix elements filled with values from min to max .
301
19
149,232
public static boolean decomposeQR_block_col ( final int blockLength , final DSubmatrixD1 Y , final double gamma [ ] ) { int width = Y . col1 - Y . col0 ; int height = Y . row1 - Y . row0 ; int min = Math . min ( width , height ) ; for ( int i = 0 ; i < min ; i ++ ) { // compute the householder vector if ( ! computeHouseHolderCol ( blockLength , Y , gamma , i ) ) return false ; // apply to rest of the columns in the block rank1UpdateMultR_Col ( blockLength , Y , i , gamma [ Y . col0 + i ] ) ; } return true ; }
Performs a standard QR decomposition on the specified submatrix that is one block wide .
155
19
149,233
public static void divideElementsCol ( final int blockLength , final DSubmatrixD1 Y , final int col , final double val ) { final int width = Math . min ( blockLength , Y . col1 - Y . col0 ) ; final double dataY [ ] = Y . original . data ; for ( int i = Y . row0 ; i < Y . row1 ; i += blockLength ) { int height = Math . min ( blockLength , Y . row1 - i ) ; int index = i * Y . original . numCols + height * Y . col0 + col ; if ( i == Y . row0 ) { index += width * ( col + 1 ) ; for ( int k = col + 1 ; k < height ; k ++ , index += width ) { dataY [ index ] /= val ; } } else { int endIndex = index + width * height ; //for( int k = 0; k < height; k++ for ( ; index != endIndex ; index += width ) { dataY [ index ] /= val ; } } } }
Divides the elements at the specified column by val . Takes in account leading zeros and one .
233
20
149,234
public static void multAdd_zeros ( final int blockLength , final DSubmatrixD1 Y , final DSubmatrixD1 B , final DSubmatrixD1 C ) { int widthY = Y . col1 - Y . col0 ; for ( int i = Y . row0 ; i < Y . row1 ; i += blockLength ) { int heightY = Math . min ( blockLength , Y . row1 - i ) ; for ( int j = B . col0 ; j < B . col1 ; j += blockLength ) { int widthB = Math . min ( blockLength , B . col1 - j ) ; int indexC = ( i - Y . row0 + C . row0 ) * C . original . numCols + ( j - B . col0 + C . col0 ) * heightY ; for ( int k = Y . col0 ; k < Y . col1 ; k += blockLength ) { int indexY = i * Y . original . numCols + k * heightY ; int indexB = ( k - Y . col0 + B . row0 ) * B . original . numCols + j * widthY ; if ( i == Y . row0 ) { multBlockAdd_zerosone ( Y . original . data , B . original . data , C . original . data , indexY , indexB , indexC , heightY , widthY , widthB ) ; } else { InnerMultiplication_DDRB . blockMultPlus ( Y . original . data , B . original . data , C . original . data , indexY , indexB , indexC , heightY , widthY , widthB ) ; } } } } }
Special multiplication that takes in account the zeros and one in Y which is the matrix that stores the householder vectors .
369
24
149,235
public static ManagerFunctions . InputN createMultTransA ( ) { return ( inputs , manager ) -> { if ( inputs . size ( ) != 2 ) throw new RuntimeException ( "Two inputs required" ) ; final Variable varA = inputs . get ( 0 ) ; final Variable varB = inputs . get ( 1 ) ; Operation . Info ret = new Operation . Info ( ) ; if ( varA instanceof VariableMatrix && varB instanceof VariableMatrix ) { // The output matrix or scalar variable must be created with the provided manager final VariableMatrix output = manager . createMatrix ( ) ; ret . output = output ; ret . op = new Operation ( "multTransA-mm" ) { @ Override public void process ( ) { DMatrixRMaj mA = ( ( VariableMatrix ) varA ) . matrix ; DMatrixRMaj mB = ( ( VariableMatrix ) varB ) . matrix ; CommonOps_DDRM . multTransA ( mA , mB , output . matrix ) ; } } ; } else { throw new IllegalArgumentException ( "Expected both inputs to be a matrix" ) ; } return ret ; } ; }
Create the function . Be sure to handle all possible input types and combinations correctly and provide meaningful error messages . The output matrix should be resized to fit the inputs .
248
33
149,236
public static DMatrixRMaj copyChangeRow ( int order [ ] , DMatrixRMaj src , DMatrixRMaj dst ) { if ( dst == null ) { dst = new DMatrixRMaj ( src . numRows , src . numCols ) ; } else if ( src . numRows != dst . numRows || src . numCols != dst . numCols ) { throw new IllegalArgumentException ( "src and dst must have the same dimensions." ) ; } for ( int i = 0 ; i < src . numRows ; i ++ ) { int indexDst = i * src . numCols ; int indexSrc = order [ i ] * src . numCols ; System . arraycopy ( src . data , indexSrc , dst . data , indexDst , src . numCols ) ; } return dst ; }
Creates a copy of a matrix but swaps the rows as specified by the order array .
190
18
149,237
public static DMatrixRMaj copyTriangle ( DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) { if ( dst == null ) { dst = new DMatrixRMaj ( src . numRows , src . numCols ) ; } else if ( src . numRows != dst . numRows || src . numCols != dst . numCols ) { throw new IllegalArgumentException ( "src and dst must have the same dimensions." ) ; } if ( upper ) { int N = Math . min ( src . numRows , src . numCols ) ; for ( int i = 0 ; i < N ; i ++ ) { int index = i * src . numCols + i ; System . arraycopy ( src . data , index , dst . data , index , src . numCols - i ) ; } } else { for ( int i = 0 ; i < src . numRows ; i ++ ) { int length = Math . min ( i + 1 , src . numCols ) ; int index = i * src . numCols ; System . arraycopy ( src . data , index , dst . data , index , length ) ; } } return dst ; }
Copies just the upper or lower triangular portion of a matrix .
264
13
149,238
public static DMatrixRMaj [ ] splitIntoVectors ( DMatrix1Row A , boolean column ) { int w = column ? A . numCols : A . numRows ; int M = column ? A . numRows : 1 ; int N = column ? 1 : A . numCols ; int o = Math . max ( M , N ) ; DMatrixRMaj [ ] ret = new DMatrixRMaj [ w ] ; for ( int i = 0 ; i < w ; i ++ ) { DMatrixRMaj a = new DMatrixRMaj ( M , N ) ; if ( column ) subvector ( A , 0 , i , o , false , 0 , a ) ; else subvector ( A , i , 0 , o , true , 0 , a ) ; ret [ i ] = a ; } return ret ; }
Takes a matrix and splits it into a set of row or column vectors .
188
16
149,239
public static double diagProd ( DMatrix1Row T ) { double prod = 1.0 ; int N = Math . min ( T . numRows , T . numCols ) ; for ( int i = 0 ; i < N ; i ++ ) { prod *= T . unsafe_get ( i , i ) ; } return prod ; }
Computes the product of the diagonal elements . For a diagonal or triangular matrix this is the determinant .
77
21
149,240
public static double elementSumSq ( DMatrixD1 m ) { // minimize round off error double maxAbs = CommonOps_DDRM . elementMaxAbs ( m ) ; if ( maxAbs == 0 ) return 0 ; double total = 0 ; int N = m . getNumElements ( ) ; for ( int i = 0 ; i < N ; i ++ ) { double d = m . data [ i ] / maxAbs ; total += d * d ; } return maxAbs * total * maxAbs ; }
Sums up the square of each element in the matrix . This is equivalent to the Frobenius norm squared .
111
23
149,241
public void init ( double diag [ ] , double off [ ] , int numCols ) { reset ( numCols ) ; this . diag = diag ; this . off = off ; }
Sets up and declares internal data structures .
43
9
149,242
public void reset ( int N ) { this . N = N ; this . diag = null ; this . off = null ; if ( splits . length < N ) { splits = new int [ N ] ; } numSplits = 0 ; x1 = 0 ; x2 = N - 1 ; steps = numExceptional = lastExceptional = 0 ; this . Q = null ; }
Sets the size of the matrix being decomposed declares new memory if needed and sets all helper functions to their initial value .
82
25
149,243
protected boolean isZero ( int index ) { double bottom = Math . abs ( diag [ index ] ) + Math . abs ( diag [ index + 1 ] ) ; return ( Math . abs ( off [ index ] ) <= bottom * UtilEjml . EPS ) ; }
Checks to see if the specified off diagonal element is zero using a relative metric .
60
17
149,244
protected void createBulge ( int x1 , double p , boolean byAngle ) { double a11 = diag [ x1 ] ; double a22 = diag [ x1 + 1 ] ; double a12 = off [ x1 ] ; double a23 = off [ x1 + 1 ] ; if ( byAngle ) { c = Math . cos ( p ) ; s = Math . sin ( p ) ; c2 = c * c ; s2 = s * s ; cs = c * s ; } else { computeRotation ( a11 - p , a12 ) ; } // multiply the rotator on the top left. diag [ x1 ] = c2 * a11 + 2.0 * cs * a12 + s2 * a22 ; diag [ x1 + 1 ] = c2 * a22 - 2.0 * cs * a12 + s2 * a11 ; off [ x1 ] = a12 * ( c2 - s2 ) + cs * ( a22 - a11 ) ; off [ x1 + 1 ] = c * a23 ; bulge = s * a23 ; if ( Q != null ) updateQ ( x1 , x1 + 1 , c , s ) ; }
Performs a similar transform on A - pI
266
10
149,245
protected void eigenvalue2by2 ( int x1 ) { double a = diag [ x1 ] ; double b = off [ x1 ] ; double c = diag [ x1 + 1 ] ; // normalize to reduce overflow double absA = Math . abs ( a ) ; double absB = Math . abs ( b ) ; double absC = Math . abs ( c ) ; double scale = absA > absB ? absA : absB ; if ( absC > scale ) scale = absC ; // see if it is a pathological case. the diagonal must already be zero // and the eigenvalues are all zero. so just return if ( scale == 0 ) { off [ x1 ] = 0 ; diag [ x1 ] = 0 ; diag [ x1 + 1 ] = 0 ; return ; } a /= scale ; b /= scale ; c /= scale ; eigenSmall . symm2x2_fast ( a , b , c ) ; off [ x1 ] = 0 ; diag [ x1 ] = scale * eigenSmall . value0 . real ; diag [ x1 + 1 ] = scale * eigenSmall . value1 . real ; }
Computes the eigenvalue of the 2 by 2 matrix .
257
13
149,246
@ Override public void solve ( DMatrixRMaj B , DMatrixRMaj X ) { X . reshape ( blockA . numCols , B . numCols ) ; blockB . reshape ( B . numRows , B . numCols , false ) ; blockX . reshape ( X . numRows , X . numCols , false ) ; MatrixOps_DDRB . convert ( B , blockB ) ; alg . solve ( blockB , blockX ) ; MatrixOps_DDRB . convert ( blockX , X ) ; }
Converts B and X into block matrices and calls the block matrix solve routine .
126
17
149,247
@ Override public void invert ( DMatrixRMaj A_inv ) { blockB . reshape ( A_inv . numRows , A_inv . numCols , false ) ; alg . invert ( blockB ) ; MatrixOps_DDRB . convert ( blockB , A_inv ) ; }
Creates a block matrix the same size as A_inv inverts the matrix and copies the results back onto A_inv .
71
26
149,248
public void printMinors ( int matrix [ ] , int N , PrintStream stream ) { this . N = N ; this . stream = stream ; // compute all the minors int index = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ , index ++ ) { stream . print ( " double m" + i + "" + j + " = " ) ; if ( ( i + j ) % 2 == 1 ) stream . print ( "-( " ) ; printTopMinor ( matrix , i - 1 , j - 1 , N ) ; if ( ( i + j ) % 2 == 1 ) stream . print ( ")" ) ; stream . print ( ";\n" ) ; } } stream . println ( ) ; // compute the determinant stream . print ( " double det = (a11*m11" ) ; for ( int i = 2 ; i <= N ; i ++ ) { stream . print ( " + " + a ( i - 1 ) + "*m" + 1 + "" + i ) ; } stream . println ( ")/scale;" ) ; }
Put the core auto - code algorithm here so an external class can call it
247
15
149,249
@ Override public boolean setA ( DMatrixRBlock A ) { if ( A . numRows < A . numCols ) throw new IllegalArgumentException ( "Number of rows must be more than or equal to the number of columns. " + "Can't solve an underdetermined system." ) ; if ( ! decomposer . decompose ( A ) ) return false ; this . QR = decomposer . getQR ( ) ; return true ; }
Computes the QR decomposition of A and store the results in A .
101
15
149,250
@ Override public void invert ( DMatrixRBlock A_inv ) { int M = Math . min ( QR . numRows , QR . numCols ) ; if ( A_inv . numRows != M || A_inv . numCols != M ) throw new IllegalArgumentException ( "A_inv must be square an have dimension " + M ) ; // Solve for A^-1 // Q*R*A^-1 = I // Apply householder reflectors to the identity matrix // y = Q^T*I = Q^T MatrixOps_DDRB . setIdentity ( A_inv ) ; decomposer . applyQTran ( A_inv ) ; // Solve using upper triangular R matrix // R*A^-1 = y // A^-1 = R^-1*y TriangularSolver_DDRB . solve ( QR . blockLength , true , new DSubmatrixD1 ( QR , 0 , M , 0 , M ) , new DSubmatrixD1 ( A_inv ) , false ) ; }
Invert by solving for against an identity matrix .
236
10
149,251
public void perform ( ) { for ( int i = 0 ; i < operations . size ( ) ; i ++ ) { operations . get ( i ) . process ( ) ; } }
Executes the sequence of operations
38
6
149,252
@ Override public void setExpectedMaxSize ( int numRows , int numCols ) { super . setExpectedMaxSize ( numRows , numCols ) ; // if the matrix that is being decomposed is smaller than the block we really don't // see the B matrix. if ( numRows < blockWidth ) B = new DMatrixRMaj ( 0 , 0 ) ; else B = new DMatrixRMaj ( blockWidth , maxWidth ) ; chol = new CholeskyBlockHelper_DDRM ( blockWidth ) ; }
Declares additional internal data structures .
122
7
149,253
public static DMatrixSparseCSC convert ( DMatrixSparseTriplet src , DMatrixSparseCSC dst , int hist [ ] ) { if ( dst == null ) dst = new DMatrixSparseCSC ( src . numRows , src . numCols , src . nz_length ) ; else dst . reshape ( src . numRows , src . numCols , src . nz_length ) ; if ( hist == null ) hist = new int [ src . numCols ] ; else if ( hist . length >= src . numCols ) Arrays . fill ( hist , 0 , src . numCols , 0 ) ; else throw new IllegalArgumentException ( "Length of hist must be at least numCols" ) ; // compute the number of elements in each columns for ( int i = 0 ; i < src . nz_length ; i ++ ) { hist [ src . nz_rowcol . data [ i * 2 + 1 ] ] ++ ; } // define col_idx dst . histogramToStructure ( hist ) ; System . arraycopy ( dst . col_idx , 0 , hist , 0 , dst . numCols ) ; // now write the row indexes and the values for ( int i = 0 ; i < src . nz_length ; i ++ ) { int row = src . nz_rowcol . data [ i * 2 ] ; int col = src . nz_rowcol . data [ i * 2 + 1 ] ; double value = src . nz_value . data [ i ] ; int index = hist [ col ] ++ ; dst . nz_rows [ index ] = row ; dst . nz_values [ index ] = value ; } dst . indicesSorted = false ; return dst ; }
Converts SMatrixTriplet_64 into a SMatrixCC_64 .
390
18
149,254
protected void setupPivotInfo ( ) { for ( int col = 0 ; col < numCols ; col ++ ) { pivots [ col ] = col ; double c [ ] = dataQR [ col ] ; double norm = 0 ; for ( int row = 0 ; row < numRows ; row ++ ) { double element = c [ row ] ; norm += element * element ; } normsCol [ col ] = norm ; } }
Sets the initial pivot ordering and compute the F - norm squared for each column
93
16
149,255
protected void updateNorms ( int j ) { boolean foundNegative = false ; for ( int col = j ; col < numCols ; col ++ ) { double e = dataQR [ col ] [ j - 1 ] ; double v = normsCol [ col ] -= e * e ; if ( v < 0 ) { foundNegative = true ; break ; } } // if a negative sum has been found then clearly too much precision has been lost // and it should recompute the column norms from scratch if ( foundNegative ) { for ( int col = j ; col < numCols ; col ++ ) { double u [ ] = dataQR [ col ] ; double actual = 0 ; for ( int i = j ; i < numRows ; i ++ ) { double v = u [ i ] ; actual += v * v ; } normsCol [ col ] = actual ; } } }
Performs an efficient update of each columns norm
190
9
149,256
protected void swapColumns ( int j ) { // find the column with the largest norm int largestIndex = j ; double largestNorm = normsCol [ j ] ; for ( int col = j + 1 ; col < numCols ; col ++ ) { double n = normsCol [ col ] ; if ( n > largestNorm ) { largestNorm = n ; largestIndex = col ; } } // swap the columns double [ ] tempC = dataQR [ j ] ; dataQR [ j ] = dataQR [ largestIndex ] ; dataQR [ largestIndex ] = tempC ; double tempN = normsCol [ j ] ; normsCol [ j ] = normsCol [ largestIndex ] ; normsCol [ largestIndex ] = tempN ; int tempP = pivots [ j ] ; pivots [ j ] = pivots [ largestIndex ] ; pivots [ largestIndex ] = tempP ; }
Finds the column with the largest normal and makes that the first column
192
14
149,257
public String getHiveExecutionEngine ( ) { String executionEngine = hiveConfSystemOverride . get ( HiveConf . ConfVars . HIVE_EXECUTION_ENGINE . varname ) ; return executionEngine == null ? HiveConf . ConfVars . HIVE_EXECUTION_ENGINE . getDefaultValue ( ) : executionEngine ; }
Get the configured hive . execution . engine . If not set it will default to the default value of HiveConf
76
22
149,258
public void override ( HiveRunnerConfig hiveRunnerConfig ) { config . putAll ( hiveRunnerConfig . config ) ; hiveConfSystemOverride . putAll ( hiveRunnerConfig . hiveConfSystemOverride ) ; }
Copy values from the inserted config to this config . Note that if properties has not been explicitly set the defaults will apply .
43
24
149,259
public static Optional < Field > getField ( Class < ? > type , final String fieldName ) { Optional < Field > field = Iterables . tryFind ( newArrayList ( type . getDeclaredFields ( ) ) , havingFieldName ( fieldName ) ) ; if ( ! field . isPresent ( ) && type . getSuperclass ( ) != null ) { field = getField ( type . getSuperclass ( ) , fieldName ) ; } return field ; }
Finds the first Field with given field name in the Class and in its super classes .
100
18
149,260
public void init ( Map < String , String > testConfig , Map < String , String > hiveVars ) { context . init ( ) ; HiveConf hiveConf = context . getHiveConf ( ) ; // merge test case properties with hive conf before HiveServer is started. for ( Map . Entry < String , String > property : testConfig . entrySet ( ) ) { hiveConf . set ( property . getKey ( ) , property . getValue ( ) ) ; } try { hiveServer2 = new HiveServer2 ( ) ; hiveServer2 . init ( hiveConf ) ; // Locate the ClIService in the HiveServer2 for ( Service service : hiveServer2 . getServices ( ) ) { if ( service instanceof CLIService ) { client = ( CLIService ) service ; } } Preconditions . checkNotNull ( client , "ClIService was not initialized by HiveServer2" ) ; sessionHandle = client . openSession ( "noUser" , "noPassword" , null ) ; SessionState sessionState = client . getSessionManager ( ) . getSession ( sessionHandle ) . getSessionState ( ) ; currentSessionState = sessionState ; currentSessionState . setHiveVariables ( hiveVars ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Failed to create HiveServer :" + e . getMessage ( ) , e ) ; } // Ping hive server before we do anything more with it! If validation // is switched on, this will fail if metastorage is not set up properly pingHiveServer ( ) ; }
Will start the HiveServer .
340
6
149,261
public InsertIntoTable addRowsFromDelimited ( File file , String delimiter , Object nullValue ) { builder . addRowsFromDelimited ( file , delimiter , nullValue ) ; return this ; }
Adds all rows from the TSV file specified using the provided delimiter and null value .
48
18
149,262
public InsertIntoTable addRowsFrom ( File file , FileParser fileParser ) { builder . addRowsFrom ( file , fileParser ) ; return this ; }
Adds all rows from the file specified using the provided parser .
36
12
149,263
public InsertIntoTable set ( String name , Object value ) { builder . set ( name , value ) ; return this ; }
Set the given column name to the given value .
27
10
149,264
public HiveShellContainer evaluateStatement ( List < ? extends Script > scripts , Object target , TemporaryFolder temporaryFolder , Statement base ) throws Throwable { container = null ; FileUtil . setPermission ( temporaryFolder . getRoot ( ) , FsPermission . getDirDefault ( ) ) ; try { LOGGER . info ( "Setting up {} in {}" , getName ( ) , temporaryFolder . getRoot ( ) . getAbsolutePath ( ) ) ; container = createHiveServerContainer ( scripts , target , temporaryFolder ) ; base . evaluate ( ) ; return container ; } finally { tearDown ( ) ; } }
Drives the unit test .
133
6
149,265
private HiveShellContainer createHiveServerContainer ( final List < ? extends Script > scripts , final Object testCase , TemporaryFolder baseDir ) throws IOException { HiveServerContext context = new StandaloneHiveServerContext ( baseDir , config ) ; final HiveServerContainer hiveTestHarness = new HiveServerContainer ( context ) ; HiveShellBuilder hiveShellBuilder = new HiveShellBuilder ( ) ; hiveShellBuilder . setCommandShellEmulation ( config . getCommandShellEmulator ( ) ) ; HiveShellField shellSetter = loadScriptUnderTest ( testCase , hiveShellBuilder ) ; if ( scripts != null ) { hiveShellBuilder . overrideScriptsUnderTest ( scripts ) ; } hiveShellBuilder . setHiveServerContainer ( hiveTestHarness ) ; loadAnnotatedResources ( testCase , hiveShellBuilder ) ; loadAnnotatedProperties ( testCase , hiveShellBuilder ) ; loadAnnotatedSetupScripts ( testCase , hiveShellBuilder ) ; // Build shell final HiveShellContainer shell = hiveShellBuilder . buildShell ( ) ; // Set shell shellSetter . setShell ( shell ) ; if ( shellSetter . isAutoStart ( ) ) { shell . start ( ) ; } return shell ; }
Traverses the test case annotations . Will inject a HiveShell in the test case that envelopes the HiveServer .
261
24
149,266
public static Command newInsert ( Object object , String outIdentifier ) { return getCommandFactoryProvider ( ) . newInsert ( object , outIdentifier ) ; }
Inserts a new instance but references via the outIdentifier which is returned as part of the ExecutionResults
34
21
149,267
public static Command newInsert ( Object object , String outIdentifier , boolean returnObject , String entryPoint ) { return getCommandFactoryProvider ( ) . newInsert ( object , outIdentifier , returnObject , entryPoint ) ; }
Inserts a new instance but references via the outIdentifier which is returned as part of the ExecutionResults The outIdentifier can be null . The entryPoint which can also be null specifies the entrypoint the object is inserted into .
48
47
149,268
public static Command newInsertElements ( Collection objects , String outIdentifier , boolean returnObject , String entryPoint ) { return getCommandFactoryProvider ( ) . newInsertElements ( objects , outIdentifier , returnObject , entryPoint ) ; }
Iterate and insert each of the elements of the Collection .
52
12
149,269
public static Command newSetGlobal ( String identifier , Object object ) { return getCommandFactoryProvider ( ) . newSetGlobal ( identifier , object ) ; }
Sets the global . Does not add the global to the ExecutionResults .
32
15
149,270
public static Command newGetGlobal ( String identifier , String outIdentifier ) { return getCommandFactoryProvider ( ) . newGetGlobal ( identifier , outIdentifier ) ; }
Gets the global and adds it ot the BatchExecutionresults using the alternative outIdentifier .
36
21
149,271
public static Command newStartProcess ( String processId , Map < String , Object > parameters ) { return getCommandFactoryProvider ( ) . newStartProcess ( processId , parameters ) ; }
Start a process using the given parameters .
39
8
149,272
public static Command newQuery ( String identifier , String name ) { return getCommandFactoryProvider ( ) . newQuery ( identifier , name ) ; }
Executes a query . The query results will be added to the ExecutionResults using the given identifier .
30
20
149,273
public static Command newQuery ( String identifier , String name , Object [ ] arguments ) { return getCommandFactoryProvider ( ) . newQuery ( identifier , name , arguments ) ; }
Executes a query using the given parameters . The query results will be added to the ExecutionResults using the given identifier .
37
24
149,274
public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration ( Properties properties , ClassLoader ... classLoaders ) { return FactoryServiceHolder . factoryService . newKnowledgeBuilderConfiguration ( properties , classLoaders ) ; }
Create a KnowledgeBuilderConfiguration on which properties can be set . Use the given properties file and ClassLoader - either of which can be null .
45
28
149,275
public static synchronized void unregister ( final String serviceName , final Callable < Class < ? > > factory ) { if ( serviceName == null ) { throw new IllegalArgumentException ( "serviceName cannot be null" ) ; } if ( factories != null ) { List < Callable < Class < ? > > > l = factories . get ( serviceName ) ; if ( l != null ) { l . remove ( factory ) ; } } }
Removes the given service provider factory from the set of providers for the service .
94
16
149,276
public static synchronized void register ( final String serviceName , final Callable < Class < ? > > factory ) { if ( serviceName == null ) { throw new IllegalArgumentException ( "serviceName cannot be null" ) ; } if ( factory != null ) { if ( factories == null ) { factories = new HashMap < String , List < Callable < Class < ? > > > > ( ) ; } List < Callable < Class < ? > > > l = factories . get ( serviceName ) ; if ( l == null ) { l = new ArrayList < Callable < Class < ? > > > ( ) ; factories . put ( serviceName , l ) ; } l . add ( factory ) ; } }
Adds the given service provider factory to the set of providers for the service .
152
15
149,277
public static synchronized Class < ? > locate ( final String serviceName ) { if ( serviceName == null ) { throw new IllegalArgumentException ( "serviceName cannot be null" ) ; } if ( factories != null ) { List < Callable < Class < ? > > > l = factories . get ( serviceName ) ; if ( l != null && ! l . isEmpty ( ) ) { Callable < Class < ? > > c = l . get ( l . size ( ) - 1 ) ; try { return c . call ( ) ; } catch ( Exception e ) { } } } return null ; }
Finds the preferred provider for the given service . The preferred provider is the last one added to the set of providers .
129
24
149,278
public static synchronized List < Class < ? > > locateAll ( final String serviceName ) { if ( serviceName == null ) { throw new IllegalArgumentException ( "serviceName cannot be null" ) ; } List < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; if ( factories != null ) { List < Callable < Class < ? > > > l = factories . get ( serviceName ) ; if ( l != null ) { for ( Callable < Class < ? > > c : l ) { try { classes . add ( c . call ( ) ) ; } catch ( Exception e ) { } } } } return classes ; }
Finds all providers for the given service .
143
9
149,279
public static KieRuntimeLogger newFileLogger ( KieRuntimeEventManager session , String fileName ) { return getKnowledgeRuntimeLoggerProvider ( ) . newFileLogger ( session , fileName ) ; }
Creates a file logger in the current thread . The file is in XML format suitable for interpretation by Eclipse s Drools Audit View or other tools . Note that while events are written as they happen the file will not be flushed until it is closed or the underlying file buffer is filled . If you need real time logging then use a Console Logger or a Threaded File Logger .
47
77
149,280
public static String toXml ( DeploymentDescriptor descriptor ) { try { Marshaller marshaller = getContext ( ) . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , Boolean . TRUE ) ; marshaller . setProperty ( Marshaller . JAXB_SCHEMA_LOCATION , "http://www.jboss.org/jbpm deployment-descriptor.xsd" ) ; marshaller . setSchema ( schema ) ; StringWriter stringWriter = new StringWriter ( ) ; // clone the object and cleanup transients DeploymentDescriptor clone = ( ( DeploymentDescriptorImpl ) descriptor ) . clearClone ( ) ; marshaller . marshal ( clone , stringWriter ) ; String output = stringWriter . toString ( ) ; return output ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to generate xml from deployment descriptor" , e ) ; } }
Serializes descriptor instance to XML
217
6
149,281
public static List < ObjectModelResolver > getResolvers ( ) { if ( resolvers == null ) { synchronized ( serviceLoader ) { if ( resolvers == null ) { List < ObjectModelResolver > foundResolvers = new ArrayList < ObjectModelResolver > ( ) ; for ( ObjectModelResolver resolver : serviceLoader ) { foundResolvers . add ( resolver ) ; } resolvers = foundResolvers ; } } } return resolvers ; }
Returns all found resolvers
107
6
149,282
public static ObjectModelResolver get ( String resolverId ) { List < ObjectModelResolver > resolvers = getResolvers ( ) ; for ( ObjectModelResolver resolver : resolvers ) { if ( resolver . accept ( resolverId ) ) { return resolver ; } } return null ; }
Returns first resolver that accepts the given resolverId . In case none is found null is returned .
69
21
149,283
void reset ( ) { if ( ! hasStopped ) { throw new IllegalStateException ( "cannot reset a non stopped queue poller" ) ; } hasStopped = false ; run = true ; lastLoop = null ; loop = new Semaphore ( 0 ) ; }
Will make the thread ready to run once again after it has stopped .
59
14
149,284
void releaseResources ( JobInstance ji ) { this . peremption . remove ( ji . getId ( ) ) ; this . actualNbThread . decrementAndGet ( ) ; for ( ResourceManagerBase rm : this . resourceManagers ) { rm . releaseResource ( ji ) ; } if ( ! this . strictPollingPeriod ) { // Force a new loop at once. This makes queues more fluid. loop . release ( 1 ) ; } this . engine . signalEndOfRun ( ) ; }
Called when a payload thread has ended . This also notifies the poller to poll once again .
112
21
149,285
public static JqmEngineOperations startEngine ( String name , JqmEngineHandler handler ) { JqmEngine e = new JqmEngine ( ) ; e . start ( name , handler ) ; return e ; }
Creates and start an engine representing the node named as the given parameter .
49
15
149,286
@ Override public Response toResponse ( ErrorDto e ) { // String type = headers.getContentType() == null ? MediaType.APPLICATION_JSON : headers.getContentType(); return Response . status ( e . httpStatus ) . entity ( e ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; }
private HttpServletResponse headers ;
74
8
149,287
public static JqmClient getClient ( String name , Properties p , boolean cached ) { Properties p2 = null ; if ( binder == null ) { bind ( ) ; } if ( p == null ) { p2 = props ; } else { p2 = new Properties ( props ) ; p2 . putAll ( p ) ; } return binder . getClientFactory ( ) . getClient ( name , p2 , cached ) ; }
Return a new client that may be cached or not . Given properties are always use when not cached and only used at creation time for cached clients .
94
29
149,288
public static ScheduledJob create ( String cronExpression ) { ScheduledJob res = new ScheduledJob ( ) ; res . cronExpression = cronExpression ; return res ; }
Fluent API builder .
42
5
149,289
static void export ( String path , String queueName , DbConn cnx ) throws JqmXmlException { // Argument tests if ( queueName == null ) { throw new IllegalArgumentException ( "queue name cannot be null" ) ; } if ( cnx == null ) { throw new IllegalArgumentException ( "database connection cannot be null" ) ; } Queue q = CommonXml . findQueue ( queueName , cnx ) ; if ( q == null ) { throw new IllegalArgumentException ( "there is no queue named " + queueName ) ; } List < Queue > l = new ArrayList <> ( ) ; l . add ( q ) ; export ( path , l , cnx ) ; }
Exports a single queue to an XML file .
160
10
149,290
static void createMessage ( String textMessage , JobInstance jobInstance , DbConn cnx ) { cnx . runUpdate ( "message_insert" , jobInstance . getId ( ) , textMessage ) ; }
Create a text message that will be stored in the database . Must be called inside a transaction .
48
19
149,291
static int createDeliverable ( String path , String originalFileName , String fileFamily , Integer jobId , DbConn cnx ) { QueryResult qr = cnx . runUpdate ( "deliverable_insert" , fileFamily , path , jobId , originalFileName , UUID . randomUUID ( ) . toString ( ) ) ; return qr . getGeneratedId ( ) ; }
Create a Deliverable inside the database that will track a file created by a JobInstance Must be called from inside a transaction
90
24
149,292
static void initSingleParam ( String key , String initValue , DbConn cnx ) { try { cnx . runSelectSingle ( "globalprm_select_by_key" , 2 , String . class , key ) ; return ; } catch ( NoResultException e ) { GlobalParameter . create ( cnx , key , initValue ) ; } catch ( NonUniqueResultException e ) { // It exists! Nothing to do... } }
Checks if a parameter exists . If it exists it is left untouched . If it doesn t it is created . Only works for parameters which key is unique . Must be called from within an open transaction .
98
41
149,293
static void setSingleParam ( String key , String value , DbConn cnx ) { QueryResult r = cnx . runUpdate ( "globalprm_update_value_by_key" , value , key ) ; if ( r . nbUpdated == 0 ) { cnx . runUpdate ( "globalprm_insert" , key , value ) ; } cnx . commit ( ) ; }
Checks if a parameter exists . If it exists it is updated . If it doesn t it is created . Only works for parameters which key is unique . Will create a transaction on the given entity manager .
91
41
149,294
public void close ( ) { if ( transac_open ) { try { this . _cnx . rollback ( ) ; } catch ( Exception e ) { // Ignore. } } for ( Statement s : toClose ) { closeQuietly ( s ) ; } toClose . clear ( ) ; closeQuietly ( _cnx ) ; _cnx = null ; }
Close all JDBC objects related to this connection .
81
10
149,295
void killAll ( ) { for ( RjiRegistration reg : this . instancesById . values ( ) . toArray ( new RjiRegistration [ ] { } ) ) { reg . rji . handleInstruction ( Instruction . KILL ) ; } }
Send a kill signal to all running instances and return as soon as the signal is sent .
52
18
149,296
@ Override public void setJobQueue ( int jobId , Queue queue ) { JqmClientFactory . getClient ( ) . setJobQueue ( jobId , queue ) ; }
No need to expose . Client side work .
40
9
149,297
@ Override public List < JobInstance > getJobs ( Query query ) { return JqmClientFactory . getClient ( ) . getJobs ( query ) ; }
Not exposed directly - the Query object passed as parameter actually contains results ...
37
14
149,298
@ Override public void stop ( ) { synchronized ( killHook ) { jqmlogger . info ( "JQM engine " + this . node . getName ( ) + " has received a stop order" ) ; // Kill hook should be removed try { if ( ! Runtime . getRuntime ( ) . removeShutdownHook ( killHook ) ) { jqmlogger . error ( "The engine could not unregister its shutdown hook" ) ; } } catch ( IllegalStateException e ) { // This happens if the stop sequence is initiated by the shutdown hook itself. jqmlogger . info ( "Stop order is due to an admin operation (KILL/INT)" ) ; } } // Stop pollers int pollerCount = pollers . size ( ) ; for ( QueuePoller p : pollers . values ( ) ) { p . stop ( ) ; } // Scheduler this . scheduler . stop ( ) ; // Jetty is closed automatically when all pollers are down // Wait for the end of the world if ( pollerCount > 0 ) { try { this . ended . acquire ( ) ; } catch ( InterruptedException e ) { jqmlogger . error ( "interrupted" , e ) ; } } // Send a KILL signal to remaining job instances, and wait some more. if ( this . getCurrentlyRunningJobCount ( ) > 0 ) { this . runningJobInstanceManager . killAll ( ) ; try { Thread . sleep ( 10000 ) ; } catch ( InterruptedException e ) { jqmlogger . error ( "interrupted" , e ) ; } } jqmlogger . debug ( "Stop order was correctly handled. Engine for node " + this . node . getName ( ) + " has stopped." ) ; }
Gracefully stop the engine
381
6
149,299
private void purgeDeadJobInstances ( DbConn cnx , Node node ) { for ( JobInstance ji : JobInstance . select ( cnx , "ji_select_by_node" , node . getId ( ) ) ) { try { cnx . runSelectSingle ( "history_select_state_by_id" , String . class , ji . getId ( ) ) ; } catch ( NoResultException e ) { History . create ( cnx , ji , State . CRASHED , Calendar . getInstance ( ) ) ; Message . create ( cnx , "Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash" , ji . getId ( ) ) ; } cnx . runUpdate ( "ji_delete_by_id" , ji . getId ( ) ) ; } cnx . commit ( ) ; }
To be called at node startup - it purges all job instances associated to this node .
204
18