idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
5,000
public List < NaaccrValidationError > getAllValidationErrors ( ) { List < NaaccrValidationError > results = new ArrayList < > ( getValidationErrors ( ) ) ; results . addAll ( getItems ( ) . stream ( ) . filter ( item -> item . getValidationError ( ) != null ) . map ( Item :: getValidationError ) . collect ( Collectors . toList ( ) ) ) ; for ( Tumor tumor : getTumors ( ) ) results . addAll ( tumor . getAllValidationErrors ( ) ) ; return results ; }
This methods returns all the validation errors on the patient any of its items and any of its tumors .
5,001
public static String computeId ( String recordType , NaaccrDictionary baseDictionary , Collection < NaaccrDictionary > userDictionaries ) { if ( baseDictionary == null ) return recordType ; StringBuilder buf = new StringBuilder ( recordType ) ; buf . append ( ";" ) . append ( baseDictionary . getDictionaryUri ( ) ) ; if ( userDictionaries != null ) for ( NaaccrDictionary userDictionary : userDictionaries ) if ( userDictionary != null ) buf . append ( ";" ) . append ( userDictionary . getDictionaryUri ( ) ) ; return buf . toString ( ) ; }
Helper method to compute an ID for a runtime dictionary based on the URI of its base and user dictionaries .
5,002
public String getItemValue ( String id ) { Item item = getItem ( id ) ; if ( item != null ) return item . getValue ( ) ; return null ; }
Returns the value of the item with the requested ID .
5,003
public static long sum ( long [ ] array ) { if ( array == null ) { return 0L ; } long sum = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) { sum += array [ i ] ; } return sum ; }
Return the sum of values in the array
5,004
protected NaaccrIOException convertSyntaxException ( ConversionException ex ) { String msg = ex . get ( "message" ) ; if ( msg == null ) msg = ex . getMessage ( ) ; NaaccrIOException e = new NaaccrIOException ( msg , ex ) ; if ( ex . get ( "line number" ) != null ) e . setLineNumber ( Integer . valueOf ( ex . get ( "line number" ) ) ) ; e . setPath ( ex . get ( "path" ) ) ; return e ; }
We don t want to expose the conversion exceptions so let s translate them into our own exceptions ...
5,005
private NaaccrIOException convertSyntaxException ( ConversionException ex ) { String msg = ex . get ( "message" ) ; if ( CannotResolveClassException . class . getName ( ) . equals ( ex . get ( "cause-exception" ) ) ) msg = "invalid tag: " + ex . get ( "cause-message" ) ; else if ( StreamException . class . getName ( ) . equals ( ex . get ( "cause-exception" ) ) ) msg = "invalid XML syntax" ; if ( msg == null ) msg = ex . getMessage ( ) ; NaaccrIOException e = new NaaccrIOException ( msg , ex ) ; if ( ex . get ( "line number" ) != null ) e . setLineNumber ( Integer . valueOf ( ex . get ( "line number" ) ) ) ; e . setPath ( ex . get ( "path" ) ) ; return e ; }
We don t want to expose the conversion exceptions so let s translate them into our own exception ...
5,006
public static boolean isFullLengthRequiredForType ( String type ) { boolean result = NAACCR_DATA_TYPE_ALPHA . equals ( type ) ; result |= NAACCR_DATA_TYPE_DIGITS . equals ( type ) ; result |= NAACCR_DATA_TYPE_MIXED . equals ( type ) ; return result ; }
Returns whether values for a given data type need to have the same length as their definition
5,007
public static String extractVersionFromUri ( String uri ) { if ( uri == null ) return null ; Matcher matcher = BASE_DICTIONARY_URI_PATTERN . matcher ( uri ) ; if ( matcher . matches ( ) ) return matcher . group ( 1 ) ; else { matcher = DEFAULT_USER_DICTIONARY_URI_PATTERN . matcher ( uri ) ; if ( matcher . matches ( ) ) return matcher . group ( 1 ) ; } return null ; }
Extracts the NAACCR version from an internal dictionary URI .
5,008
public static NaaccrDictionary getBaseDictionaryByUri ( String uri ) { if ( uri == null ) throw new RuntimeException ( "URI is required for getting the base dictionary." ) ; return getBaseDictionaryByVersion ( extractVersionFromUri ( uri ) ) ; }
Returns the base dictionary for the requested URI .
5,009
public static NaaccrDictionary getDefaultUserDictionaryByUri ( String uri ) { if ( uri == null ) throw new RuntimeException ( "URI is required for getting the default user dictionary." ) ; return getDefaultUserDictionaryByVersion ( extractVersionFromUri ( uri ) ) ; }
Returns the default user dictionary for the requested URI .
5,010
@ SuppressWarnings ( "ConstantConditions" ) public static NaaccrDictionary getDefaultUserDictionaryByVersion ( String naaccrVersion ) { if ( naaccrVersion == null ) throw new RuntimeException ( "Version is required for getting the default user dictionary." ) ; if ( ! NaaccrFormat . isVersionSupported ( naaccrVersion ) ) throw new RuntimeException ( "Unsupported default user dictionary version: " + naaccrVersion ) ; NaaccrDictionary result = _INTERNAL_DICTIONARIES . get ( "user_" + naaccrVersion ) ; if ( result == null ) { String resName = "user-defined-naaccr-dictionary-" + naaccrVersion + ".xml" ; try ( Reader reader = new InputStreamReader ( Thread . currentThread ( ) . getContextClassLoader ( ) . getResource ( resName ) . openStream ( ) , StandardCharsets . UTF_8 ) ) { result = readDictionary ( reader ) ; _INTERNAL_DICTIONARIES . put ( "user_" + naaccrVersion , result ) ; } catch ( IOException e ) { throw new RuntimeException ( "Unable to get base dictionary for version " + naaccrVersion , e ) ; } } return result ; }
Returns the default user dictionary for the requested NAACCR version .
5,011
public static NaaccrDictionary readDictionary ( File file ) throws IOException { if ( file == null ) throw new IOException ( "File is required to load dictionary." ) ; if ( ! file . exists ( ) ) throw new IOException ( "File must exist to load dictionary." ) ; try ( Reader reader = new InputStreamReader ( new FileInputStream ( file ) , StandardCharsets . UTF_8 ) ) { return readDictionary ( reader ) ; } }
Reads a dictionary from the provided file .
5,012
public static NaaccrDictionary readDictionary ( Reader reader ) throws IOException { try { NaaccrDictionary dictionary = ( NaaccrDictionary ) instanciateXStream ( ) . fromXML ( reader ) ; if ( dictionary . getSpecificationVersion ( ) == null ) dictionary . setSpecificationVersion ( SpecificationVersion . SPEC_1_0 ) ; if ( dictionary . getItems ( ) != null ) for ( NaaccrDictionaryItem item : dictionary . getItems ( ) ) if ( item . getRecordTypes ( ) == null ) item . setRecordTypes ( NaaccrFormat . ALL_RECORD_TYPES ) ; String uri = dictionary . getDictionaryUri ( ) ; if ( uri == null || uri . trim ( ) . isEmpty ( ) ) throw new IOException ( "'dictionaryUri' attribute is required" ) ; else if ( ! BASE_DICTIONARY_URI_PATTERN . matcher ( uri ) . matches ( ) && ! DEFAULT_USER_DICTIONARY_URI_PATTERN . matcher ( uri ) . matches ( ) ) { List < String > errors = validateUserDictionary ( dictionary ) ; if ( ! errors . isEmpty ( ) ) throw new IOException ( errors . get ( 0 ) ) ; } return dictionary ; } catch ( XStreamException ex ) { throw new IOException ( "Unable to read dictionary" , ex ) ; } }
Reads a dictionary from the provided reader .
5,013
public static void writeDictionary ( NaaccrDictionary dictionary , File file ) throws IOException { try ( Writer writer = new OutputStreamWriter ( new FileOutputStream ( file ) , StandardCharsets . UTF_8 ) ) { writeDictionary ( dictionary , writer ) ; } }
Writes the given dictionary to the provided file .
5,014
public static void writeDictionary ( NaaccrDictionary dictionary , Writer writer ) throws IOException { try { instanciateXStream ( ) . marshal ( dictionary , new NaaccrPrettyPrintWriter ( dictionary , writer ) ) ; } catch ( XStreamException ex ) { throw new IOException ( "Unable to write dictionary" , ex ) ; } }
Writes the given dictionary to the provided writer .
5,015
public static List < String > validateUserDictionary ( NaaccrDictionary dictionary , String naaccrVersion ) { return validateDictionary ( dictionary , false , naaccrVersion ) ; }
Validates the provided user dictionary .
5,016
public static void flatToXml ( File flatFile , File xmlFile , NaaccrOptions options , List < NaaccrDictionary > userDictionaries , NaaccrObserver observer ) throws NaaccrIOException { if ( flatFile == null ) throw new NaaccrIOException ( "Source flat file is required" ) ; if ( ! flatFile . exists ( ) ) throw new NaaccrIOException ( "Source flat file must exist" ) ; if ( ! xmlFile . getParentFile ( ) . exists ( ) ) throw new NaaccrIOException ( "Target folder must exist" ) ; try ( PatientFlatReader reader = new PatientFlatReader ( createReader ( flatFile ) , options , userDictionaries ) ) { try ( PatientXmlWriter writer = new PatientXmlWriter ( createWriter ( xmlFile ) , reader . getRootData ( ) , options , userDictionaries ) ) { Patient patient = reader . readPatient ( ) ; while ( patient != null && ! Thread . currentThread ( ) . isInterrupted ( ) ) { if ( observer != null ) observer . patientRead ( patient ) ; writer . writePatient ( patient ) ; if ( observer != null ) observer . patientWritten ( patient ) ; patient = reader . readPatient ( ) ; } } } }
Translates a flat data file into an XML data file .
5,017
public static String getFormatFromFlatFile ( File flatFile ) { if ( flatFile == null || ! flatFile . exists ( ) ) return null ; try ( BufferedReader reader = new BufferedReader ( createReader ( flatFile ) ) ) { return getFormatFromFlatFileLine ( reader . readLine ( ) ) ; } catch ( IOException e ) { return null ; } }
Returns the NAACCR format of the given flat file based on it s first data line .
5,018
public static String getFormatFromXmlFile ( File xmlFile ) { if ( xmlFile == null || ! xmlFile . exists ( ) ) return null ; try ( Reader reader = createReader ( xmlFile ) ) { return getFormatFromXmlReader ( reader ) ; } catch ( IOException | RuntimeException e ) { return null ; } }
Returns the NAACCR format of the given XML file .
5,019
public static String getFormatFromXmlReader ( Reader xmlReader ) { Map < String , String > attributes = getAttributesFromXmlReader ( xmlReader ) ; String baseDictUri = attributes . get ( NAACCR_XML_ROOT_ATT_BASE_DICT ) ; String recordType = attributes . get ( NAACCR_XML_ROOT_ATT_REC_TYPE ) ; if ( baseDictUri != null && recordType != null ) { String version = NaaccrXmlDictionaryUtils . extractVersionFromUri ( baseDictUri ) ; if ( NaaccrFormat . isVersionSupported ( version ) && NaaccrFormat . isRecordTypeSupported ( recordType ) ) return NaaccrFormat . getInstance ( version , recordType ) . toString ( ) ; } return null ; }
Returns the NAACCR format of the given XML reader .
5,020
public static Map < String , String > getAttributesFromXmlFile ( File xmlFile ) { if ( xmlFile == null || ! xmlFile . exists ( ) ) return Collections . emptyMap ( ) ; try ( Reader reader = createReader ( xmlFile ) ) { return getAttributesFromXmlReader ( reader ) ; } catch ( IOException | RuntimeException e ) { return Collections . emptyMap ( ) ; } }
Returns all the available attributes from the given XML file .
5,021
public static Reader createReader ( File file ) throws NaaccrIOException { InputStream is = null ; try { is = new FileInputStream ( file ) ; if ( file . getName ( ) . endsWith ( ".gz" ) ) is = new GZIPInputStream ( is ) ; return new InputStreamReader ( is , StandardCharsets . UTF_8 ) ; } catch ( IOException e ) { if ( is != null ) { try { is . close ( ) ; } catch ( IOException e1 ) { } } throw new NaaccrIOException ( e . getMessage ( ) ) ; } }
Returns a generic reader for the provided file taking care of the optional GZ compression .
5,022
public static Writer createWriter ( File file ) throws NaaccrIOException { OutputStream os = null ; try { os = new FileOutputStream ( file ) ; if ( file . getName ( ) . endsWith ( ".gz" ) ) os = new GZIPOutputStream ( os ) ; return new OutputStreamWriter ( os , StandardCharsets . UTF_8 ) ; } catch ( IOException e ) { if ( os != null ) { try { os . close ( ) ; } catch ( IOException e1 ) { } } throw new NaaccrIOException ( e . getMessage ( ) ) ; } }
Returns a generic writer for the provided file taking care of the optional GZ compression .
5,023
protected final int getMeq ( ) { if ( meq < 0 ) { meq = ( this . request . getA ( ) == null ) ? 0 : this . request . getA ( ) . rows ( ) ; } return meq ; }
Number of equalities .
5,024
protected boolean isInDomainF0 ( DoubleMatrix1D X ) { double F0X = request . getF0 ( ) . value ( X . toArray ( ) ) ; return ! Double . isInfinite ( F0X ) && ! Double . isNaN ( F0X ) ; }
Objective function domain .
5,025
protected DoubleMatrix1D getGradF0 ( DoubleMatrix1D X ) { return F1 . make ( request . getF0 ( ) . gradient ( X . toArray ( ) ) ) ; }
Objective function gradient at X .
5,026
protected DoubleMatrix2D getHessF0 ( DoubleMatrix1D X ) { double [ ] [ ] hess = request . getF0 ( ) . hessian ( X . toArray ( ) ) ; if ( hess == FunctionsUtils . ZEROES_2D_ARRAY_PLACEHOLDER ) { return F2 . make ( X . size ( ) , X . size ( ) ) ; } else { return F2 . make ( hess ) ; } }
Objective function hessian at X .
5,027
protected DoubleMatrix1D getFi ( DoubleMatrix1D X ) { final ConvexMultivariateRealFunction [ ] fis = request . getFi ( ) ; if ( fis == null ) { return null ; } final double [ ] ret = new double [ fis . length ] ; final double [ ] x = X . toArray ( ) ; for ( int i = 0 ; i < fis . length ; i ++ ) { final ConvexMultivariateRealFunction fi = fis [ i ] ; final double fix = fi . value ( x ) ; ret [ i ] = fix ; } return F1 . make ( ret ) ; }
Inequality functions values at X .
5,028
protected DoubleMatrix2D getGradFi ( DoubleMatrix1D X ) { DoubleMatrix2D ret = F2 . make ( request . getFi ( ) . length , X . size ( ) ) ; double [ ] x = X . toArray ( ) ; for ( int i = 0 ; i < request . getFi ( ) . length ; i ++ ) { ret . viewRow ( i ) . assign ( request . getFi ( ) [ i ] . gradient ( x ) ) ; } return ret ; }
Inequality functions gradients values at X .
5,029
protected DoubleMatrix2D [ ] getHessFi ( DoubleMatrix1D X ) { DoubleMatrix2D [ ] ret = new DoubleMatrix2D [ request . getFi ( ) . length ] ; double [ ] x = X . toArray ( ) ; for ( int i = 0 ; i < request . getFi ( ) . length ; i ++ ) { double [ ] [ ] hess = request . getFi ( ) [ i ] . hessian ( x ) ; if ( hess == FunctionsUtils . ZEROES_2D_ARRAY_PLACEHOLDER ) { ret [ i ] = FunctionsUtils . ZEROES_MATRIX_PLACEHOLDER ; } else { ret [ i ] = F2 . make ( hess ) ; } } return ret ; }
Inequality functions hessians values at X .
5,030
public double [ ] presolve ( double [ ] x ) { if ( x . length != originalN ) { throw new IllegalArgumentException ( "wrong array dimension: " + x . length ) ; } double [ ] presolvedX = Arrays . copyOf ( x , x . length ) ; for ( int i = 0 ; i < presolvingStack . size ( ) ; i ++ ) { presolvingStack . get ( i ) . preSolve ( presolvedX ) ; } double [ ] ret = new double [ presolvedN ] ; int cntPosition = 0 ; for ( int i = 0 ; i < presolvedX . length ; i ++ ) { if ( indipendentVariables [ i ] ) { ret [ cntPosition ] = presolvedX [ i ] ; cntPosition ++ ; } } if ( this . T != null ) { for ( int i = 0 ; i < ret . length ; i ++ ) { ret [ i ] = ret [ i ] / T . getQuick ( i ) ; } } return ret ; }
From the full x gives back its presolved elements .
5,031
public double [ ] postConvert ( double [ ] X ) { if ( X . length != standardN ) { throw new IllegalArgumentException ( "wrong array dimension: " + X . length ) ; } double [ ] ret = new double [ originalN ] ; int cntSplitted = 0 ; for ( int i = standardS ; i < standardN ; i ++ ) { if ( splittedVariablesList . contains ( i - standardS ) ) { ret [ i - standardS ] = X [ i ] - X [ standardN + cntSplitted ] ; cntSplitted ++ ; } else { ret [ i - standardS ] = X [ i ] ; } } return ret ; }
Get back the vector in the original components .
5,032
public double [ ] getStandardComponents ( double [ ] x ) { if ( x . length != originalN ) { throw new IllegalArgumentException ( "wrong array dimension: " + x . length ) ; } double [ ] ret = new double [ standardN ] ; for ( int i = 0 ; i < x . length ; i ++ ) { if ( splittedVariablesList . contains ( i ) ) { if ( x [ i ] >= 0 ) { ret [ standardS + i ] = x [ i ] ; } else { int pos = - 1 ; for ( int k = 0 ; k < splittedVariablesList . size ( ) ; k ++ ) { if ( splittedVariablesList . get ( k ) == i ) { pos = k ; break ; } } ret [ standardS + x . length + pos ] = - x [ i ] ; } } else { ret [ standardS + i ] = x [ i ] ; } } if ( standardS > 0 ) { DoubleMatrix1D residuals = ColtUtils . zMult ( standardA , F1 . make ( ret ) , standardB , - 1 ) ; for ( int i = 0 ; i < standardS ; i ++ ) { ret [ i ] = - residuals . get ( i ) + ret [ i ] ; } } return ret ; }
Express a vector in the original variables in the final standard variable form
5,033
public DoubleMatrix1D getMatrixScalingFactorsSymm ( DoubleMatrix2D A ) { int n = A . rows ( ) ; final double log10_b = Math . log10 ( base ) ; final int [ ] x = new int [ n ] ; final double [ ] cHolder = new double [ 1 ] ; final double [ ] tHolder = new double [ 1 ] ; final int [ ] currentColumnIndexHolder = new int [ ] { - 1 } ; IntIntDoubleFunction myFunct = new IntIntDoubleFunction ( ) { public double apply ( int i , int j , double pij ) { int currentColumnIndex = currentColumnIndexHolder [ 0 ] ; if ( i == currentColumnIndex ) { tHolder [ 0 ] = tHolder [ 0 ] - 0.5 * ( Math . log10 ( Math . abs ( pij ) ) / log10_b + 0.5 ) ; cHolder [ 0 ] = cHolder [ 0 ] + 1 ; } else if ( i > currentColumnIndex ) { tHolder [ 0 ] = tHolder [ 0 ] - 2 * ( Math . log10 ( Math . abs ( pij ) ) / log10_b + 0.5 ) - 2 * x [ i ] ; cHolder [ 0 ] = cHolder [ 0 ] + 2 ; } return pij ; } } ; for ( int currentColumnIndex = n - 1 ; currentColumnIndex >= 0 ; currentColumnIndex -- ) { cHolder [ 0 ] = 0 ; tHolder [ 0 ] = 0 ; currentColumnIndexHolder [ 0 ] = currentColumnIndex ; DoubleMatrix2D P = A . viewPart ( 0 , currentColumnIndex , n , 1 ) ; P . forEachNonZero ( myFunct ) ; if ( cHolder [ 0 ] > 0 ) { x [ currentColumnIndex ] = ( int ) Math . round ( tHolder [ 0 ] / cHolder [ 0 ] ) ; } } DoubleMatrix1D u = new DenseDoubleMatrix1D ( n ) ; for ( int k = 0 ; k < n ; k ++ ) { u . setQuick ( k , Math . pow ( base , x [ k ] ) ) ; } return u ; }
Symmetry preserving scale factors
5,034
public boolean checkScaling ( final DoubleMatrix2D A , final DoubleMatrix1D U , final DoubleMatrix1D V ) { final double log10_2 = Math . log10 ( base ) ; final double [ ] originalOFValue = { 0 } ; final double [ ] scaledOFValue = { 0 } ; final double [ ] x = new double [ A . rows ( ) ] ; final double [ ] y = new double [ A . columns ( ) ] ; A . forEachNonZero ( new IntIntDoubleFunction ( ) { public double apply ( int i , int j , double aij ) { double v = Math . log10 ( Math . abs ( aij ) ) / log10_2 + 0.5 ; originalOFValue [ 0 ] = originalOFValue [ 0 ] + Math . pow ( v , 2 ) ; double xi = Math . log10 ( U . getQuick ( i ) ) / log10_2 ; double yj = Math . log10 ( V . getQuick ( j ) ) / log10_2 ; scaledOFValue [ 0 ] = scaledOFValue [ 0 ] + Math . pow ( xi + yj + v , 2 ) ; x [ i ] = xi ; y [ j ] = yj ; return aij ; } } ) ; originalOFValue [ 0 ] = 0.5 * originalOFValue [ 0 ] ; scaledOFValue [ 0 ] = 0.5 * scaledOFValue [ 0 ] ; logger . debug ( "x: " + ArrayUtils . toString ( x ) ) ; logger . debug ( "y: " + ArrayUtils . toString ( y ) ) ; logger . debug ( "originalOFValue: " + originalOFValue [ 0 ] ) ; logger . debug ( "scaledOFValue : " + scaledOFValue [ 0 ] ) ; return ! ( originalOFValue [ 0 ] < scaledOFValue [ 0 ] ) ; }
Check if the scaling algorithm returned proper results . Note that the scaling algorithm is for minimizing a given objective function of the original matrix elements and the check will be done on the value of this objective function .
5,035
public DoubleMatrix1D solve ( DoubleMatrix1D b ) { if ( b . size ( ) != dim ) { log . error ( "wrong dimension of vector b: expected " + dim + ", actual " + b . size ( ) ) ; throw new RuntimeException ( "wrong dimension of vector b: expected " + dim + ", actual " + b . size ( ) ) ; } if ( this . rescaler != null ) { b = ColtUtils . diagonalMatrixMult ( this . U , b ) ; } final double [ ] y = new double [ dim ] ; for ( int i = 0 ; i < diagonalLength ; i ++ ) { double LII = LData [ 0 ] [ i ] ; y [ i ] = b . getQuick ( i ) / LII ; } for ( int i = diagonalLength ; i < dim ; i ++ ) { double [ ] LI = LData [ i - diagonalLength + 1 ] ; double LII = LI [ i ] ; double sum = 0 ; for ( int j = 0 ; j < i ; j ++ ) { sum += LI [ j ] * y [ j ] ; } y [ i ] = ( b . getQuick ( i ) - sum ) / LII ; } final DoubleMatrix1D x = F1 . make ( dim ) ; for ( int i = dim - 1 ; i > diagonalLength - 1 ; i -- ) { double sum = 0 ; for ( int j = dim - 1 ; j > i ; j -- ) { sum += LData [ j - diagonalLength + 1 ] [ i ] * x . getQuick ( j ) ; } x . setQuick ( i , ( y [ i ] - sum ) / LData [ i - diagonalLength + 1 ] [ i ] ) ; } for ( int i = diagonalLength - 1 ; i > - 1 ; i -- ) { double sum = 0 ; for ( int j = dim - 1 ; j > diagonalLength - 1 ; j -- ) { sum += LData [ j - diagonalLength + 1 ] [ i ] * x . getQuick ( j ) ; } x . setQuick ( i , ( y [ i ] - sum ) / LData [ 0 ] [ i ] ) ; } if ( this . rescaler != null ) { return ColtUtils . diagonalMatrixMult ( this . U , x ) ; } else { return x ; } }
Solve Q . x = b
5,036
private DoubleMatrix1D calculateNewtonStep ( DoubleMatrix2D hessX , DoubleMatrix1D gradX ) throws Exception { final KKTSolver kktSolver = new BasicKKTSolver ( ) ; if ( isCheckKKTSolutionAccuracy ( ) ) { kktSolver . setCheckKKTSolutionAccuracy ( isCheckKKTSolutionAccuracy ( ) ) ; kktSolver . setToleranceKKT ( getToleranceKKT ( ) ) ; } kktSolver . setHMatrix ( hessX ) ; kktSolver . setGVector ( gradX ) ; DoubleMatrix1D [ ] sol = kktSolver . solve ( ) ; DoubleMatrix1D step = sol [ 0 ] ; return step ; }
Hess . step = - Grad
5,037
private PagedSearchResult postImageSearch ( UploadSearchParams uploadSearchParams , String endpointMethod ) { ViSearchHttpResponse response = getPostImageSearchHttpResponse ( uploadSearchParams , endpointMethod ) ; return getPagedResult ( response ) ; }
Perform upload search by image
5,038
public static int getMaxIndex ( DoubleMatrix1D v ) { int maxIndex = - 1 ; double maxValue = - Double . MAX_VALUE ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v . getQuick ( i ) > maxValue ) { maxIndex = i ; maxValue = v . getQuick ( i ) ; } } return maxIndex ; }
Get the index of the maximum entry .
5,039
public static int getMinIndex ( DoubleMatrix1D v ) { int minIndex = - 1 ; double minValue = Double . MAX_VALUE ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v . getQuick ( i ) < minValue ) { minIndex = i ; minValue = v . getQuick ( i ) ; } } return minIndex ; }
Get the index of the minimum entry .
5,040
public static final double calculateDeterminant ( double [ ] [ ] ai , int dim ) { double det = 0 ; if ( dim == 1 ) { det = ai [ 0 ] [ 0 ] ; } else if ( dim == 2 ) { det = ai [ 0 ] [ 0 ] * ai [ 1 ] [ 1 ] - ai [ 0 ] [ 1 ] * ai [ 1 ] [ 0 ] ; } else { double ai1 [ ] [ ] = new double [ dim - 1 ] [ dim - 1 ] ; for ( int k = 0 ; k < dim ; k ++ ) { for ( int i1 = 1 ; i1 < dim ; i1 ++ ) { int j = 0 ; for ( int j1 = 0 ; j1 < dim ; j1 ++ ) { if ( j1 != k ) { ai1 [ i1 - 1 ] [ j ] = ai [ i1 ] [ j1 ] ; j ++ ; } } } if ( k % 2 == 0 ) { det += ai [ 0 ] [ k ] * calculateDeterminant ( ai1 , dim - 1 ) ; } else { det -= ai [ 0 ] [ k ] * calculateDeterminant ( ai1 , dim - 1 ) ; } } } return det ; }
Brute - force determinant calculation .
5,041
private DoubleMatrix1D findOneRoot ( DoubleMatrix2D A , DoubleMatrix1D b ) throws Exception { return originalProblem . findEqFeasiblePoint ( A , b ) ; }
Just looking for one out of all the possible solutions .
5,042
public static final DoubleMatrix1D diagonalMatrixMult ( DoubleMatrix1D diagonalM , DoubleMatrix1D vector ) { int n = diagonalM . size ( ) ; DoubleMatrix1D ret = DoubleFactory1D . dense . make ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { ret . setQuick ( i , diagonalM . getQuick ( i ) * vector . getQuick ( i ) ) ; } return ret ; }
Matrix - vector multiplication with diagonal matrix .
5,043
public static final DoubleMatrix2D diagonalMatrixMult ( final DoubleMatrix1D diagonalU , DoubleMatrix2D A , final DoubleMatrix1D diagonalV ) { int r = A . rows ( ) ; int c = A . columns ( ) ; final DoubleMatrix2D ret ; if ( A instanceof SparseDoubleMatrix2D ) { ret = DoubleFactory2D . sparse . make ( r , c ) ; A . forEachNonZero ( new IntIntDoubleFunction ( ) { public double apply ( int i , int j , double aij ) { ret . setQuick ( i , j , aij * diagonalU . getQuick ( i ) * diagonalV . getQuick ( j ) ) ; return aij ; } } ) ; } else { ret = DoubleFactory2D . dense . make ( r , c ) ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { ret . setQuick ( i , j , A . getQuick ( i , j ) * diagonalU . getQuick ( i ) * diagonalV . getQuick ( j ) ) ; } } } return ret ; }
Return diagonalU . A . diagonalV with diagonalU and diagonalV diagonal .
5,044
public static final DoubleMatrix2D fillSubdiagonalSymmetricMatrix ( DoubleMatrix2D S ) { if ( S . rows ( ) != S . columns ( ) ) { throw new IllegalArgumentException ( "Not square matrix" ) ; } boolean isSparse = S instanceof SparseDoubleMatrix2D ; DoubleFactory2D F2D = ( isSparse ) ? DoubleFactory2D . sparse : DoubleFactory2D . dense ; final DoubleMatrix2D SFull = F2D . make ( S . rows ( ) , S . rows ( ) ) ; if ( isSparse ) { S . forEachNonZero ( new IntIntDoubleFunction ( ) { public double apply ( int i , int j , double hij ) { SFull . setQuick ( i , j , hij ) ; SFull . setQuick ( j , i , hij ) ; return hij ; } } ) ; } else { for ( int i = 0 ; i < S . rows ( ) ; i ++ ) { for ( int j = 0 ; j < i + 1 ; j ++ ) { double sij = S . getQuick ( i , j ) ; SFull . setQuick ( i , j , sij ) ; SFull . setQuick ( j , i , sij ) ; } } } return SFull ; }
Given a symm matrix S that stores just its subdiagonal elements reconstructs the full symmetric matrix .
5,045
public void factorize ( ) throws Exception { m = A . rows ( ) ; n = A . columns ( ) ; if ( this . rescaler != null ) { double [ ] cn_00_original = null ; double [ ] cn_2_original = null ; double [ ] cn_00_scaled = null ; double [ ] cn_2_scaled = null ; if ( log . isDebugEnabled ( ) ) { cn_00_original = ColtUtils . getConditionNumberRange ( new Array2DRowRealMatrix ( A . toArray ( ) ) , Integer . MAX_VALUE ) ; log . debug ( "cn_00_original Q before scaling: " + ArrayUtils . toString ( cn_00_original ) ) ; cn_2_original = ColtUtils . getConditionNumberRange ( new Array2DRowRealMatrix ( A . toArray ( ) ) , 2 ) ; log . debug ( "cn_2_original Q before scaling : " + ArrayUtils . toString ( cn_2_original ) ) ; } DoubleMatrix1D [ ] UV = rescaler . getMatrixScalingFactors ( A ) ; this . U = UV [ 0 ] ; this . V = UV [ 1 ] ; if ( log . isDebugEnabled ( ) ) { boolean checkOK = rescaler . checkScaling ( A , U , V ) ; if ( ! checkOK ) { log . warn ( "Scaling failed (checkScaling = false)" ) ; } } this . A = ( SparseDoubleMatrix2D ) ColtUtils . diagonalMatrixMult ( U , A , V ) ; if ( log . isDebugEnabled ( ) ) { cn_00_scaled = ColtUtils . getConditionNumberRange ( new Array2DRowRealMatrix ( A . toArray ( ) ) , Integer . MAX_VALUE ) ; log . debug ( "cn_00_scaled Q after scaling : " + ArrayUtils . toString ( cn_00_scaled ) ) ; cn_2_scaled = ColtUtils . getConditionNumberRange ( new Array2DRowRealMatrix ( A . toArray ( ) ) , 2 ) ; log . debug ( "cn_2_scaled Q after scaling : " + ArrayUtils . toString ( cn_2_scaled ) ) ; if ( cn_00_original [ 0 ] < cn_00_scaled [ 0 ] || cn_2_original [ 0 ] < cn_2_scaled [ 0 ] ) { log . warn ( "Problematic scaling" ) ; } } } Dcs dcs ; if ( m >= n ) { dcs = ColtUtils . matrixToDcs ( A ) ; } else { dcs = ColtUtils . matrixToDcs ( ( SparseDoubleMatrix2D ) ALG . transpose ( A ) ) ; } S = Dcs_sqr . cs_sqr ( order , dcs , true ) ; if ( S == null ) { throw new IllegalArgumentException ( "Exception occured in cs_sqr()" ) ; } N = Dcs_qr . cs_qr ( dcs , S ) ; if ( N == null ) { throw new IllegalArgumentException ( "Exception occured in cs_qr()" ) ; } }
Constructs and returns a new QR decomposition object ; computed by Householder reflections ; If m < n then then the QR of A is computed . The decomposed matrices can be retrieved via instance methods of the returned decomposition object .
5,046
public DoubleMatrix2D solve ( DoubleMatrix2D B ) { if ( B . rows ( ) != dim ) { log . error ( "wrong dimension of vector b: expected " + dim + ", actual " + B . rows ( ) ) ; throw new RuntimeException ( "wrong dimension of vector b: expected " + dim + ", actual " + B . rows ( ) ) ; } if ( this . rescaler != null ) { B = ColtUtils . diagonalMatrixMult ( this . U , B ) ; } int nOfColumns = B . columns ( ) ; final double [ ] [ ] Y = B . copy ( ) . toArray ( ) ; for ( int j = 0 ; j < dim ; j ++ ) { final double [ ] LTJ = LcolumnsValues [ j ] ; for ( int col = 0 ; col < nOfColumns ; col ++ ) { Y [ j ] [ col ] /= LTJ [ 0 ] ; final double YJCol = Y [ j ] [ col ] ; if ( Double . compare ( YJCol , 0. ) != 0 ) { for ( int i = j + 1 ; i < dim ; i ++ ) { Y [ i ] [ col ] -= YJCol * LTJ [ i - j ] ; } } } } final DoubleMatrix2D X = F2 . make ( dim , nOfColumns ) ; for ( int i = dim - 1 ; i > - 1 ; i -- ) { final double [ ] LTI = LcolumnsValues [ i ] ; double [ ] sum = new double [ nOfColumns ] ; for ( int col = 0 ; col < nOfColumns ; col ++ ) { for ( int j = dim - 1 ; j > i ; j -- ) { sum [ col ] += LTI [ j - i ] * X . getQuick ( j , col ) ; } X . setQuick ( i , col , ( Y [ i ] [ col ] - sum [ col ] ) / LTI [ 0 ] ) ; } } if ( this . rescaler != null ) { return ColtUtils . diagonalMatrixMult ( this . U , X ) ; } else { return X ; } }
Solves Q . X = B
5,047
protected boolean checkKKTSolutionAccuracy ( DoubleMatrix1D v , DoubleMatrix1D w ) { DoubleMatrix2D KKT = null ; DoubleMatrix1D x = null ; DoubleMatrix1D b = null ; if ( this . A != null ) { if ( this . AT == null ) { this . AT = ALG . transpose ( A ) ; } if ( h != null ) { DoubleMatrix2D [ ] [ ] parts = { { this . H , this . AT } , { this . A , null } } ; if ( H instanceof SparseDoubleMatrix2D && A instanceof SparseDoubleMatrix2D ) { KKT = DoubleFactory2D . sparse . compose ( parts ) ; } else { KKT = DoubleFactory2D . dense . compose ( parts ) ; } x = F1 . append ( v , w ) ; b = F1 . append ( g , h ) . assign ( Mult . mult ( - 1 ) ) ; } else { DoubleMatrix2D [ ] [ ] parts = { { this . H , this . AT } } ; if ( H instanceof SparseDoubleMatrix2D && A instanceof SparseDoubleMatrix2D ) { KKT = DoubleFactory2D . sparse . compose ( parts ) ; } else { KKT = DoubleFactory2D . dense . compose ( parts ) ; } x = F1 . append ( v , w ) ; b = ColtUtils . scalarMult ( g , - 1 ) ; } } else { KKT = this . H ; x = v ; b = ColtUtils . scalarMult ( g , - 1 ) ; } double scaledResidual = Utils . calculateScaledResidual ( KKT , x , b ) ; return scaledResidual < toleranceKKT ; }
Check the solution of the system
5,048
protected DoubleMatrix2D createFullDataMatrix ( DoubleMatrix2D SubDiagonalSymmMatrix ) { int c = SubDiagonalSymmMatrix . columns ( ) ; DoubleMatrix2D ret = F2 . make ( c , c ) ; for ( int i = 0 ; i < c ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { ret . setQuick ( i , j , SubDiagonalSymmMatrix . getQuick ( i , j ) ) ; ret . setQuick ( j , i , SubDiagonalSymmMatrix . getQuick ( i , j ) ) ; } } return ret ; }
Create a full data matrix starting form a symmetric matrix filled only in its subdiagonal elements .
5,049
public DoubleMatrix1D [ ] getMatrixScalingFactors ( DoubleMatrix2D A ) { DoubleFactory1D F1 = DoubleFactory1D . dense ; Algebra ALG = Algebra . DEFAULT ; int r = A . rows ( ) ; int c = A . columns ( ) ; DoubleMatrix1D D1 = F1 . make ( r , 1 ) ; DoubleMatrix1D D2 = F1 . make ( c , 1 ) ; DoubleMatrix2D AK = A . copy ( ) ; DoubleMatrix1D DR = F1 . make ( r , 1 ) ; DoubleMatrix1D DC = F1 . make ( c , 1 ) ; DoubleMatrix1D DRInv = F1 . make ( r ) ; DoubleMatrix1D DCInv = F1 . make ( c ) ; log . debug ( "eps : " + eps ) ; int maxIteration = 50 ; for ( int k = 0 ; k <= maxIteration ; k ++ ) { double normR = - Double . MAX_VALUE ; double normC = - Double . MAX_VALUE ; for ( int i = 0 ; i < r ; i ++ ) { double dri = ALG . normInfinity ( AK . viewRow ( i ) ) ; DR . setQuick ( i , Math . sqrt ( dri ) ) ; DRInv . setQuick ( i , 1. / Math . sqrt ( dri ) ) ; normR = Math . max ( normR , Math . abs ( 1 - dri ) ) ; } for ( int j = 0 ; j < c ; j ++ ) { double dci = ALG . normInfinity ( AK . viewColumn ( j ) ) ; DC . setQuick ( j , Math . sqrt ( dci ) ) ; DCInv . setQuick ( j , 1. / Math . sqrt ( dci ) ) ; normC = Math . max ( normC , Math . abs ( 1 - dci ) ) ; } log . debug ( "normR: " + normR ) ; log . debug ( "normC: " + normC ) ; if ( normR < eps && normC < eps ) { break ; } for ( int i = 0 ; i < r ; i ++ ) { double prevD1I = D1 . getQuick ( i ) ; double newD1I = prevD1I * DRInv . getQuick ( i ) ; D1 . setQuick ( i , newD1I ) ; } for ( int j = 0 ; j < c ; j ++ ) { double prevD2J = D2 . getQuick ( j ) ; double newD2J = prevD2J * DCInv . getQuick ( j ) ; D2 . setQuick ( j , newD2J ) ; } if ( k == maxIteration ) { log . warn ( "max iteration reached" ) ; } AK = ColtUtils . diagonalMatrixMult ( DRInv , AK , DCInv ) ; } return new DoubleMatrix1D [ ] { D1 , D2 } ; }
Scaling factors for not singular matrices .
5,050
public boolean checkScaling ( final DoubleMatrix2D AOriginal , final DoubleMatrix1D U , final DoubleMatrix1D V ) { int c = AOriginal . columns ( ) ; int r = AOriginal . rows ( ) ; final double [ ] maxValueHolder = new double [ ] { - Double . MAX_VALUE } ; IntIntDoubleFunction myFunct = new IntIntDoubleFunction ( ) { public double apply ( int i , int j , double pij ) { maxValueHolder [ 0 ] = Math . max ( maxValueHolder [ 0 ] , Math . abs ( pij ) ) ; return pij ; } } ; DoubleMatrix2D AScaled = ColtUtils . diagonalMatrixMult ( U , AOriginal , V ) ; boolean isOk = true ; for ( int i = 0 ; isOk && i < r ; i ++ ) { maxValueHolder [ 0 ] = - Double . MAX_VALUE ; DoubleMatrix2D P = AScaled . viewPart ( i , 0 , 1 , c ) ; P . forEachNonZero ( myFunct ) ; isOk = Math . abs ( 1. - maxValueHolder [ 0 ] ) < eps ; } for ( int j = 0 ; isOk && j < c ; j ++ ) { maxValueHolder [ 0 ] = - Double . MAX_VALUE ; DoubleMatrix2D P = AScaled . viewPart ( 0 , j , r , 1 ) ; P . forEachNonZero ( myFunct ) ; isOk = Math . abs ( 1. - maxValueHolder [ 0 ] ) < eps ; } return isOk ; }
Check if the scaling algorithm returned proper results . Note that AOriginal cannot be only subdiagonal filled because this check is for both symm and bath notsymm matrices .
5,051
public String getReqId ( ) { if ( this . headers != null && this . headers . containsKey ( ViSearchHttpConstants . X_LOG_ID ) ) { return headers . get ( ViSearchHttpConstants . X_LOG_ID ) ; } return ViSearchHttpConstants . X_LOG_ID_EMPTY ; }
Get the request id to identify this request .
5,052
public InsertStatus insertStatus ( String transId , Integer errorPage , Integer errorLimit ) { return dataOperations . insertStatus ( transId , errorPage , errorLimit ) ; }
Get insert status by insert trans id and get errors page .
5,053
public PagedSearchResult search ( SearchParams searchParams ) { PagedSearchResult result = searchOperations . search ( searchParams ) ; if ( result != null && enableAutoSolutionActionTrack ) { String reqId = result . getReqId ( ) ; this . sendSolutionActions ( "search" , reqId ) ; } return result ; }
Search for similar images from the ViSearch App given an existing image in the App .
5,054
public PagedSearchResult recommendation ( SearchParams searchParams ) { PagedSearchResult result = searchOperations . recommendation ( searchParams ) ; if ( result != null && enableAutoSolutionActionTrack ) { String reqId = result . getReqId ( ) ; this . sendSolutionActions ( "recommendation" , reqId ) ; } return result ; }
Recommendation for similar images from the ViSearch App given an existing image in the App .
5,055
public PagedSearchResult colorSearch ( ColorSearchParams colorSearchParams ) { PagedSearchResult result = searchOperations . colorSearch ( colorSearchParams ) ; if ( result != null && enableAutoSolutionActionTrack ) { String reqId = result . getReqId ( ) ; this . sendSolutionActions ( "colorsearch" , reqId ) ; } return result ; }
Search for similar images from the ViSearch App given a hex color .
5,056
public PagedSearchResult uploadSearch ( UploadSearchParams uploadSearchParams ) { PagedSearchResult result = searchOperations . uploadSearch ( uploadSearchParams ) ; if ( result != null && enableAutoSolutionActionTrack ) { String reqId = result . getReqId ( ) ; this . sendSolutionActions ( "uploadsearch" , reqId ) ; } return result ; }
Search for similar images from the ViSearch App given an image file or url .
5,057
private void sendSolutionActions ( String action , String reqId ) { if ( reqId != null && ! reqId . equals ( "" ) ) { Map < String , String > map = Maps . newHashMap ( ) ; map . put ( "action" , action ) ; map . put ( "reqid" , reqId ) ; this . sendEvent ( map ) ; } }
send search actions after finishing search
5,058
public void factorize ( boolean checkSymmetry ) throws Exception { if ( checkSymmetry && ! Property . TWELVE . isSymmetric ( Q ) ) { throw new Exception ( "Matrix is not symmetric" ) ; } double threshold = Utils . getDoubleMachineEpsilon ( ) ; this . LData = new double [ ( dim + 1 ) * dim / 2 ] ; for ( int i = 0 ; i < dim ; i ++ ) { int iShift = ( i + 1 ) * i / 2 ; for ( int j = 0 ; j < i + 1 ; j ++ ) { int jShift = ( j + 1 ) * j / 2 ; double sum = 0.0 ; for ( int k = 0 ; k < j ; k ++ ) { sum += LData [ jShift + k ] * LData [ iShift + k ] ; } if ( i == j ) { double d = Q . getQuick ( i , i ) - sum ; if ( ! ( d > threshold ) ) { throw new Exception ( "not positive definite matrix" ) ; } LData [ iShift + i ] = Math . sqrt ( d ) ; } else { LData [ iShift + j ] = 1.0 / LData [ jShift + j ] * ( Q . getQuick ( i , j ) - sum ) ; } } } }
Cholesky factorization L of psd matrix Q = L . LT
5,059
public void bind ( InetSocketAddress socketBindAddress ) { try { localConnector . stop ( ) ; LOG . info ( "Binding server socket to {}:{}" , socketBindAddress . getHostString ( ) , socketBindAddress . getPort ( ) ) ; localConnector . setHost ( socketBindAddress . getHostString ( ) ) ; localConnector . setPort ( socketBindAddress . getPort ( ) ) ; localConnector . start ( ) ; } catch ( Exception e ) { throw new ServerLifecycleException ( "Failed to restart socket." , e ) ; } }
Reconfigures the server socket to listen on the specified bindAddr and port .
5,060
public synchronized void start ( ) throws ServerLifecycleException { if ( executorService . isShutdown ( ) ) { throw new IllegalStateException ( "Server has already been terminated." ) ; } try { server . start ( ) ; LOG . info ( "WebDavServer started." ) ; } catch ( Exception e ) { throw new ServerLifecycleException ( "Server couldn't be started" , e ) ; } }
Starts the WebDAV server .
5,061
public synchronized void stop ( ) throws ServerLifecycleException { try { server . stop ( ) ; LOG . info ( "WebDavServer stopped." ) ; } catch ( Exception e ) { throw new ServerLifecycleException ( "Server couldn't be stopped" , e ) ; } }
Stops the WebDAV server .
5,062
public static void assertExitValue ( Process proc , int expectedExitValue ) throws CommandFailedException { int actualExitValue = proc . exitValue ( ) ; if ( actualExitValue != expectedExitValue ) { try { String error = toString ( proc . getErrorStream ( ) , StandardCharsets . UTF_8 ) ; throw new CommandFailedException ( "Command failed with exit code " + actualExitValue + ". Expected " + expectedExitValue + ". Stderr: " + error ) ; } catch ( IOException e ) { throw new CommandFailedException ( "Command failed with exit code " + actualExitValue + ". Expected " + expectedExitValue + "." ) ; } } }
Fails with a CommandFailedException if the process did not finish with the expected exit code .
5,063
public static void waitFor ( Process proc , long timeout , TimeUnit unit ) throws CommandTimeoutException { try { boolean finishedInTime = proc . waitFor ( timeout , unit ) ; if ( ! finishedInTime ) { proc . destroyForcibly ( ) ; throw new CommandTimeoutException ( ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } }
Waits for the process to terminate or throws an exception if it fails to do so within the given timeout .
5,064
public void start ( ) throws ServerLifecycleException { try { contextHandlerCollection . addHandler ( contextHandler ) ; contextHandlerCollection . mapContexts ( ) ; contextHandler . start ( ) ; LOG . info ( "WebDavServlet started: " + contextPath ) ; } catch ( Exception e ) { throw new ServerLifecycleException ( "Servlet couldn't be started" , e ) ; } }
Convenience function to start this servlet .
5,065
public void stop ( ) throws ServerLifecycleException { try { contextHandler . stop ( ) ; contextHandlerCollection . removeHandler ( contextHandler ) ; contextHandlerCollection . mapContexts ( ) ; LOG . info ( "WebDavServlet stopped: " + contextPath ) ; } catch ( Exception e ) { throw new ServerLifecycleException ( "Servlet couldn't be stopped" , e ) ; } }
Convenience function to stop this servlet .
5,066
public Mount mount ( MountParams mountParams ) throws CommandFailedException { if ( ! contextHandler . isStarted ( ) ) { throw new IllegalStateException ( "Mounting only possible for running servlets." ) ; } URI uri = getServletRootUri ( mountParams . getOrDefault ( MountParam . WEBDAV_HOSTNAME , connector . getHost ( ) ) ) ; LOG . info ( "Mounting {} using {}" , uri , mounter . getClass ( ) . getName ( ) ) ; return mounter . mount ( uri , mountParams ) ; }
Tries to mount the resource served by this servlet as a WebDAV drive on the local machine .
5,067
private void processInitialization ( ) { ExecutorService executorService = Executors . newFixedThreadPool ( this . maxThread ) ; this . postInitializingMethods . entrySet ( ) . stream ( ) . sorted ( Comparator . comparing ( Map . Entry :: getKey ) ) . forEach ( entry -> { log . debug ( "Found {} beans with max threads {} and order {}" , entry . getValue ( ) . size ( ) , this . maxThread , entry . getKey ( ) ) ; try { executorService . invokeAll ( entry . getValue ( ) ) ; } catch ( InterruptedException e ) { log . warn ( "Failed to invoke {} method(s) on executorService {}" , entry . getValue ( ) . size ( ) , executorService ) ; } } ) ; executorService . shutdown ( ) ; }
Launch the initialization of eligible beans
5,068
public boolean unsubscribe ( ) { CachingWeakRefSubscriber < T > subscriber = manager . get ( tag ) ; if ( subscriber != null ) { subscriber . unsubscribe ( ) ; return true ; } return false ; }
Cancels the task .
5,069
public synchronized Tuner getTuner ( int i ) { checkReleased ( ) ; for ( Tuner t : tuners ) if ( t . getIndex ( ) == i ) return t ; throw new ArrayIndexOutOfBoundsException ( "No tuner with such index" ) ; }
This method returns a tuner given its index .
5,070
public void sendRequest ( ) throws IOException { URL url = new URL ( CleverBotQuery . formatRequest ( CleverBotQuery . URL_STRING , this . key , this . phrase , this . conversationID ) ) ; URLConnection urlConnection = url . openConnection ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( urlConnection . getInputStream ( ) ) ) ; String inputLine = in . readLine ( ) ; JsonObject jsonObject = new JsonParser ( ) . parse ( inputLine ) . getAsJsonObject ( ) ; this . setConversationID ( jsonObject . get ( "cs" ) . getAsString ( ) ) ; this . setResponse ( jsonObject . get ( "output" ) . getAsString ( ) ) ; this . setRandomNumber ( Integer . parseInt ( jsonObject . get ( "random_number" ) . getAsString ( ) ) ) ; in . close ( ) ; }
Sends request to CleverBot servers . API key and phrase should be set prior to this call
5,071
private static String formatRequest ( String url , String key , String phrase , String conversationID ) { String formattedPhrase = phrase . replaceAll ( "\\s+" , "+" ) ; return String . format ( "%s%s&input=%s&wrapper=Headline22JavaAPI%s" , url , key , formattedPhrase , ( ( conversationID . equals ( "" ) ) ? "" : ( "&cs=" + conversationID ) ) ) ; }
URL request formater
5,072
private void moveNativeFirst ( List < ImageFormat > v ) { int index = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) if ( ! formats . contains ( v . get ( index ) ) ) { v . add ( v . remove ( index ) ) ; } else index ++ ; }
This method moves the native formats in the given vector to the beginning of the vector .
5,073
private ImageFormat getFormat ( List < ImageFormat > l , String n ) { for ( ImageFormat f : l ) if ( f . getName ( ) . equals ( n ) ) return f ; return null ; }
this method returns a format in a list given its name
5,074
private ImageFormat getFormat ( List < ImageFormat > l , int i ) { for ( ImageFormat f : l ) if ( f . getIndex ( ) == i ) return f ; return null ; }
this method returns a format in a list given its index
5,075
public static void loadLibraryFromJar ( String jarpath , String [ ] libs ) throws IOException { File libspath = File . createTempFile ( "libs" , "" ) ; if ( ! libspath . delete ( ) ) { throw new IOException ( "Cannot clean " + libspath ) ; } if ( ! libspath . exists ( ) ) { if ( ! libspath . mkdirs ( ) ) { throw new IOException ( "Cannot create directory " + libspath ) ; } } libspath . deleteOnExit ( ) ; try { addLibraryPath ( libspath . getAbsolutePath ( ) ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } for ( String lib : libs ) { String libfile = "lib" + lib + ".so" ; String path = jarpath + "/" + libfile ; if ( ! path . startsWith ( "/" ) ) { throw new IllegalArgumentException ( "The path to be absolute (start with '/')." ) ; } File file = new File ( libspath , libfile ) ; file . createNewFile ( ) ; file . deleteOnExit ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int readBytes ; InputStream is = NativeUtils . class . getResourceAsStream ( path ) ; if ( is == null ) { throw new FileNotFoundException ( "File " + path + " was not found inside JAR." ) ; } OutputStream os = new FileOutputStream ( file ) ; try { while ( ( readBytes = is . read ( buffer ) ) != - 1 ) { os . write ( buffer , 0 , readBytes ) ; } } finally { os . close ( ) ; is . close ( ) ; } } for ( String lib : libs ) { System . loadLibrary ( lib ) ; } }
Loads library from current JAR archive
5,076
public static void addLibraryPath ( String pathToAdd ) throws Exception { Field usrPathsField = ClassLoader . class . getDeclaredField ( "usr_paths" ) ; usrPathsField . setAccessible ( true ) ; final String [ ] paths = ( String [ ] ) usrPathsField . get ( null ) ; for ( String path : paths ) { if ( path . equals ( pathToAdd ) ) { return ; } } final String [ ] newPaths = Arrays . copyOf ( paths , paths . length + 1 ) ; newPaths [ newPaths . length - 1 ] = pathToAdd ; usrPathsField . set ( null , newPaths ) ; }
Adds the specified path to the java library path
5,077
public JSONObject getAccountInfo ( String idToken ) throws GitkitClientException , GitkitServerException { try { JSONObject params = new JSONObject ( ) . put ( "idToken" , idToken ) ; return invokeGoogle2LegOauthApi ( "getAccountInfo" , params ) ; } catch ( JSONException e ) { throw new GitkitServerException ( "OAuth API failed" ) ; } }
Uses idToken to retrieve the user account information from GITkit service .
5,078
public static void copyZipWithoutEmptyDirectories ( final File inputFile , final File outputFile ) throws IOException { final byte [ ] buf = new byte [ 0x2000 ] ; final ZipFile inputZip = new ZipFile ( inputFile ) ; final ZipOutputStream outputStream = new ZipOutputStream ( new FileOutputStream ( outputFile ) ) ; try { final Enumeration < ? extends ZipEntry > e = inputZip . entries ( ) ; final ArrayList < ZipEntry > sortedList = new ArrayList < ZipEntry > ( ) ; while ( e . hasMoreElements ( ) ) { final ZipEntry entry = e . nextElement ( ) ; sortedList . add ( entry ) ; } Collections . sort ( sortedList , new Comparator < ZipEntry > ( ) { public int compare ( ZipEntry o1 , ZipEntry o2 ) { String n1 = o1 . getName ( ) , n2 = o2 . getName ( ) ; if ( metaOverride ( n1 , n2 ) ) { return - 1 ; } if ( metaOverride ( n2 , n1 ) ) { return 1 ; } return n1 . compareTo ( n2 ) ; } private boolean metaOverride ( String n1 , String n2 ) { return ( n1 . startsWith ( "META-INF/" ) && ! n2 . startsWith ( "META-INF/" ) ) || ( n1 . equals ( "META-INF/MANIFEST.MF" ) && ! n2 . equals ( n1 ) && ! n2 . equals ( "META-INF/" ) ) || ( n1 . equals ( "META-INF/" ) && ! n2 . equals ( n1 ) ) ; } } ) ; for ( int i = sortedList . size ( ) - 1 ; i >= 0 ; i -- ) { final ZipEntry inputEntry = sortedList . get ( i ) ; final String name = inputEntry . getName ( ) ; final boolean isEmptyDirectory ; if ( inputEntry . isDirectory ( ) ) { if ( i == sortedList . size ( ) - 1 ) { isEmptyDirectory = true ; } else { final String nextName = sortedList . get ( i + 1 ) . getName ( ) ; isEmptyDirectory = ! nextName . startsWith ( name ) ; } } else { isEmptyDirectory = false ; } if ( isEmptyDirectory ) { sortedList . remove ( i ) ; } } for ( int i = 0 ; i < sortedList . size ( ) ; i ++ ) { final ZipEntry inputEntry = sortedList . get ( i ) ; final ZipEntry outputEntry = new ZipEntry ( inputEntry ) ; outputStream . putNextEntry ( outputEntry ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final InputStream is = inputZip . getInputStream ( inputEntry ) ; IoUtil . pipe ( is , baos , buf ) ; is . close ( ) ; outputStream . write ( baos . toByteArray ( ) ) ; } } finally { outputStream . close ( ) ; inputZip . close ( ) ; } }
Create a copy of an zip file without its empty directories .
5,079
public GitkitUser validateTokenInRequest ( HttpServletRequest request ) throws GitkitClientException { Cookie [ ] cookies = request . getCookies ( ) ; if ( cookieName == null || cookies == null ) { return null ; } for ( Cookie cookie : cookies ) { if ( cookieName . equals ( cookie . getName ( ) ) ) { return validateToken ( cookie . getValue ( ) ) ; } } return null ; }
Verifies Gitkit token in http request .
5,080
public GitkitUser getUserByToken ( String token ) throws GitkitClientException , GitkitServerException { GitkitUser gitkitUser = validateToken ( token ) ; if ( gitkitUser == null ) { throw new GitkitClientException ( "invalid gitkit token" ) ; } try { JSONObject result = rpcHelper . getAccountInfo ( token ) ; JSONObject jsonUser = result . getJSONArray ( "users" ) . getJSONObject ( 0 ) ; return jsonToUser ( jsonUser ) . setCurrentProvider ( gitkitUser . getCurrentProvider ( ) ) ; } catch ( JSONException e ) { throw new GitkitServerException ( e ) ; } }
Gets user info from GITkit service using Gitkit token . Can be used to verify a Gitkit token remotely .
5,081
public GitkitUser getUserByEmail ( String email ) throws GitkitClientException , GitkitServerException { Preconditions . checkNotNull ( email ) ; try { JSONObject result = rpcHelper . getAccountInfoByEmail ( email ) ; return jsonToUser ( result . getJSONArray ( "users" ) . getJSONObject ( 0 ) ) ; } catch ( JSONException e ) { throw new GitkitServerException ( e ) ; } }
Gets user info given an email .
5,082
public GitkitUser getUserByLocalId ( String localId ) throws GitkitClientException , GitkitServerException { Preconditions . checkNotNull ( localId ) ; try { JSONObject result = rpcHelper . getAccountInfoById ( localId ) ; return jsonToUser ( result . getJSONArray ( "users" ) . getJSONObject ( 0 ) ) ; } catch ( JSONException e ) { throw new GitkitServerException ( e ) ; } }
Gets user info given a user id .
5,083
public Iterator < GitkitUser > getAllUsers ( final Integer resultsPerRequest ) { return new DownloadIterator < GitkitUser > ( ) { private String nextPageToken = null ; protected Iterator < GitkitUser > getNextResults ( ) { try { JSONObject response = rpcHelper . downloadAccount ( nextPageToken , resultsPerRequest ) ; nextPageToken = response . has ( "nextPageToken" ) ? response . getString ( "nextPageToken" ) : null ; if ( response . has ( "users" ) ) { return jsonToList ( response . getJSONArray ( "users" ) ) . iterator ( ) ; } } catch ( JSONException e ) { logger . warning ( e . getMessage ( ) ) ; } catch ( GitkitServerException e ) { logger . warning ( e . getMessage ( ) ) ; } catch ( GitkitClientException e ) { logger . warning ( e . getMessage ( ) ) ; } return ImmutableSet . < GitkitUser > of ( ) . iterator ( ) ; } } ; }
Gets all user info of this web site . Underlying requests are paginated and send on demand with given size .
5,084
public GitkitUser updateUser ( GitkitUser user ) throws GitkitClientException , GitkitServerException { try { return jsonToUser ( rpcHelper . updateAccount ( user ) ) ; } catch ( JSONException e ) { throw new GitkitServerException ( e ) ; } }
Updates a user info at Gitkit server .
5,085
final void recycleVideoBuffer ( BaseVideoFrame frame ) { if ( state . isStarted ( ) ) { enqueueBuffer ( object , frame . getBufferInex ( ) ) ; synchronized ( availableVideoFrames ) { availableVideoFrames . add ( frame ) ; availableVideoFrames . notify ( ) ; } } }
This method is called by a video frame when it is being recycled .
5,086
final void release ( ) { try { stopCapture ( ) ; } catch ( StateException se ) { } state . release ( ) ; doRelease ( object ) ; state . commit ( ) ; }
This method releases resources used by the FrameCapture object .
5,087
public String getStringValue ( ) throws ControlException { String v ; if ( type != V4L4JConstants . CTRL_TYPE_STRING ) throw new UnsupportedMethod ( "This control is not a string control" ) ; state . get ( ) ; try { v = doGetStringValue ( v4l4jObject , id ) ; } finally { state . put ( ) ; } return v ; }
This method retrieves the current string value of this control . Some controls may be write - only and getting their value does not make sense . Invoking this method on this kind of controls will trigger a ControlException .
5,088
public String setStringValue ( String value ) throws ControlException { String v = null ; if ( type != V4L4JConstants . CTRL_TYPE_STRING ) throw new UnsupportedMethod ( "This control is not a string control" ) ; if ( value . length ( ) > max ) throw new ControlException ( "The new string value for this control exceeds the maximum length" ) ; if ( value . length ( ) < min ) throw new ControlException ( "The new string value for this control is below the minimum length" ) ; state . get ( ) ; try { doSetStringValue ( v4l4jObject , id , value ) ; v = doGetStringValue ( v4l4jObject , id ) ; } finally { state . put ( ) ; } return v ; }
This method sets a new string value for this control . The returned value is the new value of the control .
5,089
public long getLongValue ( ) throws ControlException { long v ; if ( type != V4L4JConstants . CTRL_TYPE_LONG ) throw new UnsupportedMethod ( "This control is not a long control" ) ; state . get ( ) ; try { v = doGetLongValue ( v4l4jObject , id ) ; } finally { state . put ( ) ; } return v ; }
This method retrieves the current long value of this control . Some controls may be write - only and getting their value does not make sense . Invoking this method on this kind of controls will trigger a ControlException .
5,090
public long setLongValue ( long value ) throws ControlException { long v = 0 ; if ( type != V4L4JConstants . CTRL_TYPE_LONG ) throw new UnsupportedMethod ( "This control is not a long control" ) ; state . get ( ) ; try { doSetLongValue ( v4l4jObject , id , value ) ; v = doGetLongValue ( v4l4jObject , id ) ; } finally { state . put ( ) ; } return v ; }
This method sets a new long value for this control . The returned value is the new value of the control .
5,091
public int getMaxValue ( ) { if ( type == V4L4JConstants . CTRL_TYPE_LONG ) throw new UnsupportedMethod ( "This control is a long control and does not support calls to getMaxValue()" ) ; synchronized ( state ) { if ( state . isNotReleased ( ) ) return max ; else throw new StateException ( "This control has been released and must not be used" ) ; } }
This method retrieves the maximum value this control will accept . If this control is a string control this method returns the maximum string size that can be set on this control .
5,092
public int getMinValue ( ) { if ( type == V4L4JConstants . CTRL_TYPE_LONG ) throw new UnsupportedMethod ( "This control is a long control and does not support calls to getMinValue()" ) ; synchronized ( state ) { if ( state . isNotReleased ( ) ) return min ; else throw new StateException ( "This control has been released and must not be used" ) ; } }
This method retrieves the minimum value this control will accept . If this control is a string control this method returns the minimum string size that can be set on this control .
5,093
public int getDefaultValue ( ) { if ( type == V4L4JConstants . CTRL_TYPE_STRING ) throw new UnsupportedMethod ( "This control is a string control and does not support calls to getDefaultValue()" ) ; if ( type == V4L4JConstants . CTRL_TYPE_LONG ) throw new UnsupportedMethod ( "This control is a long control and does not support calls to getDefaultValue()" ) ; synchronized ( state ) { if ( state . isNotReleased ( ) ) return defaultValue ; else throw new StateException ( "This control has been released and must not be used" ) ; } }
This method returns the default value for this control
5,094
public void addAll ( T ... fragments ) { for ( T fragment : fragments ) { mItems . add ( fragment ) ; } notifyDataSetChanged ( ) ; }
Adds the specified fragments at the end of the array .
5,095
public void setJPGQuality ( int q ) { state . checkReleased ( ) ; if ( q < V4L4JConstants . MIN_JPEG_QUALITY ) q = V4L4JConstants . MIN_JPEG_QUALITY ; if ( q > V4L4JConstants . MAX_JPEG_QUALITY ) q = V4L4JConstants . MAX_JPEG_QUALITY ; setQuality ( object , q ) ; quality = q ; }
This method sets the desired JPEG quality .
5,096
private static String removeSlashes ( String path ) { String retString = path ; String slash = System . getProperty ( "file.separator" ) ; retString = retString . replace ( slash , "/" ) ; retString = retString . replaceFirst ( "^/" , "" ) ; retString = retString . replaceFirst ( "/$" , "" ) ; return retString ; }
Removes leading or trailing slashes from a string .
5,097
private void initializeFragmentSwitcher ( ) { mFragmentSwitcher = ( FragmentSwitcher ) findViewById ( R . id . fragment_switcher ) ; mFragmentAdapter = new FragmentStateArrayPagerAdapter ( getSupportFragmentManager ( ) ) ; mFragmentSwitcher . setAdapter ( mFragmentAdapter ) ; }
Initializes the fragment switcher . It works just like a viewpager .
5,098
private void initializeDrawer ( ) { mDrawerLayout = ( DrawerLayout ) findViewById ( R . id . drawer_layout ) ; mDrawerToggle = new ActionBarDrawerToggle ( this , mDrawerLayout , R . drawable . ic_drawer , R . string . show , R . string . hide ) ; mDrawerLayout . setDrawerListener ( mDrawerToggle ) ; getActionBar ( ) . setDisplayHomeAsUpEnabled ( true ) ; mDrawerToggle . syncState ( ) ; }
Sets up the UI for the navigation drawer .
5,099
private void initializeList ( ) { mListView = ( ListView ) findViewById ( R . id . drawer_list ) ; mListAdapter = new ArrayAdapter < String > ( this , android . R . layout . simple_list_item_1 ) ; mListView . setAdapter ( mListAdapter ) ; mListView . setOnItemClickListener ( new AdapterView . OnItemClickListener ( ) { public void onItemClick ( AdapterView < ? > adapterView , View view , int position , long id ) { mFragmentSwitcher . setCurrentItem ( position ) ; mDrawerLayout . closeDrawer ( Gravity . START ) ; } } ) ; }
Initializes the list that controls which fragment will be shown .