idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
19,000
public static List < Filter > toFilters ( List < DimFilter > dimFilters ) { return ImmutableList . copyOf ( FunctionalIterable . create ( dimFilters ) . transform ( new Function < DimFilter , Filter > ( ) { public Filter apply ( DimFilter input ) { return input . toFilter ( ) ; } } ) ) ; }
Convert a list of DimFilters to a list of Filters .
19,001
static Iterable < ImmutableBitmap > bitmapsFromIndexes ( final IntIterable indexes , final BitmapIndex bitmapIndex ) { return new Iterable < ImmutableBitmap > ( ) { public Iterator < ImmutableBitmap > iterator ( ) { final IntIterator iterator = indexes . iterator ( ) ; return new Iterator < ImmutableBitmap > ( ) { public boolean hasNext ( ) { return iterator . hasNext ( ) ; } public ImmutableBitmap next ( ) { return bitmapIndex . getBitmap ( iterator . nextInt ( ) ) ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } } ; }
Transform an iterable of indexes of bitmaps to an iterable of bitmaps
19,002
public static < T > T matchPredicate ( final String dimension , final BitmapIndexSelector selector , BitmapResultFactory < T > bitmapResultFactory , final Predicate < String > predicate ) { return bitmapResultFactory . unionDimensionValueBitmaps ( matchPredicateNoUnion ( dimension , selector , predicate ) ) ; }
Return the union of bitmaps for all values matching a particular predicate .
19,003
public static double estimateSelectivity ( final String dimension , final BitmapIndexSelector indexSelector , final Predicate < String > predicate ) { Preconditions . checkNotNull ( dimension , "dimension" ) ; Preconditions . checkNotNull ( indexSelector , "selector" ) ; Preconditions . checkNotNull ( predicate , "predicate" ) ; try ( final CloseableIndexed < String > dimValues = indexSelector . getDimensionValues ( dimension ) ) { if ( dimValues == null || dimValues . size ( ) == 0 ) { return predicate . apply ( null ) ? 1. : 0. ; } final BitmapIndex bitmapIndex = indexSelector . getBitmapIndex ( dimension ) ; return estimateSelectivity ( bitmapIndex , IntIteratorUtils . toIntList ( makePredicateQualifyingIndexIterable ( bitmapIndex , predicate , dimValues ) . iterator ( ) ) , indexSelector . getNumRows ( ) ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } }
Return an estimated selectivity for bitmaps of all values matching the given predicate .
19,004
public static double estimateSelectivity ( final BitmapIndex bitmapIndex , final IntList bitmaps , final long totalNumRows ) { long numMatchedRows = 0 ; for ( int i = 0 ; i < bitmaps . size ( ) ; i ++ ) { final ImmutableBitmap bitmap = bitmapIndex . getBitmap ( bitmaps . getInt ( i ) ) ; numMatchedRows += bitmap . size ( ) ; } return Math . min ( 1. , ( double ) numMatchedRows / totalNumRows ) ; }
Return an estimated selectivity for bitmaps for the dimension values given by dimValueIndexes .
19,005
public static double estimateSelectivity ( final Iterator < ImmutableBitmap > bitmaps , final long totalNumRows ) { long numMatchedRows = 0 ; while ( bitmaps . hasNext ( ) ) { final ImmutableBitmap bitmap = bitmaps . next ( ) ; numMatchedRows += bitmap . size ( ) ; } return Math . min ( 1. , ( double ) numMatchedRows / totalNumRows ) ; }
Return an estimated selectivity for bitmaps given by an iterator .
19,006
public < T extends LogicalSegment > List < T > filterSegments ( QueryType query , List < T > segments ) { return segments ; }
This method is called to allow the query to prune segments that it does not believe need to actually be queried . It can use whatever criteria it wants in order to do the pruning it just needs to return the list of Segments it actually wants to see queried .
19,007
private Set < DataSegment > refreshSegmentsForDataSource ( final String dataSource , final Set < DataSegment > segments ) throws IOException { log . debug ( "Refreshing metadata for dataSource[%s]." , dataSource ) ; final long startTime = System . currentTimeMillis ( ) ; final Map < String , DataSegment > segmentMap = Maps . uniqueIndex ( segments , segment -> segment . getId ( ) . toString ( ) ) ; final Set < DataSegment > retVal = new HashSet < > ( ) ; final Sequence < SegmentAnalysis > sequence = runSegmentMetadataQuery ( queryLifecycleFactory , Iterables . limit ( segments , MAX_SEGMENTS_PER_QUERY ) , escalator . createEscalatedAuthenticationResult ( ) ) ; Yielder < SegmentAnalysis > yielder = Yielders . each ( sequence ) ; try { while ( ! yielder . isDone ( ) ) { final SegmentAnalysis analysis = yielder . get ( ) ; final DataSegment segment = segmentMap . get ( analysis . getId ( ) ) ; if ( segment == null ) { log . warn ( "Got analysis for segment[%s] we didn't ask for, ignoring." , analysis . getId ( ) ) ; } else { synchronized ( lock ) { final RowSignature rowSignature = analysisToRowSignature ( analysis ) ; log . debug ( "Segment[%s] has signature[%s]." , segment . getId ( ) , rowSignature ) ; final Map < DataSegment , AvailableSegmentMetadata > dataSourceSegments = segmentMetadataInfo . get ( segment . getDataSource ( ) ) ; if ( dataSourceSegments == null ) { log . warn ( "No segment map found with datasource[%s], skipping refresh" , segment . getDataSource ( ) ) ; } else { final AvailableSegmentMetadata segmentMetadata = dataSourceSegments . get ( segment ) ; if ( segmentMetadata == null ) { log . warn ( "No segment[%s] found, skipping refresh" , segment . getId ( ) ) ; } else { final AvailableSegmentMetadata updatedSegmentMetadata = AvailableSegmentMetadata . from ( segmentMetadata ) . withRowSignature ( rowSignature ) . withNumRows ( analysis . getNumRows ( ) ) . build ( ) ; dataSourceSegments . put ( segment , updatedSegmentMetadata ) ; setAvailableSegmentMetadata ( segment , updatedSegmentMetadata ) ; retVal . add ( segment ) ; } } } } yielder = yielder . next ( null ) ; } } finally { yielder . close ( ) ; } log . info ( "Refreshed metadata for dataSource[%s] in %,d ms (%d segments queried, %d segments left)." , dataSource , System . currentTimeMillis ( ) - startTime , retVal . size ( ) , segments . size ( ) - retVal . size ( ) ) ; return retVal ; }
Attempt to refresh segmentSignatures for a set of segments for a particular dataSource . Returns the set of segments actually refreshed which may be a subset of the asked - for set .
19,008
public DruidQuerySignature asAggregateSignature ( RowSignature sourceSignature ) { return new DruidQuerySignature ( sourceSignature , virtualColumnPrefix , virtualColumnsByExpression , virtualColumnsByName , true ) ; }
Create as an immutable aggregate signature for a grouping so that post aggregations and having filters can not define new virtual columns
19,009
public static final TracerFactory instance ( ) { if ( INSTANCE == null ) throw new IllegalStateException ( String . format ( "%s not initialized" , TracerFactory . class . getSimpleName ( ) ) ) ; return INSTANCE ; }
Returns the singleton TracerFactory
19,010
private void onAcquire ( final PooledConnection conn , String httpMethod , String uriStr , int attemptNum , CurrentPassport passport ) { passport . setOnChannel ( conn . getChannel ( ) ) ; removeIdleStateHandler ( conn ) ; conn . setInUse ( ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "PooledConnection acquired: " + conn . toString ( ) ) ; }
function to run when a connection is acquired before returning it to caller .
19,011
public void addProxyProtocol ( ChannelPipeline pipeline ) { pipeline . addLast ( NAME , this ) ; if ( withProxyProtocol ) { pipeline . addBefore ( NAME , OptionalHAProxyMessageDecoder . NAME , new OptionalHAProxyMessageDecoder ( ) ) ; } }
Setup the required handlers on pipeline using this method .
19,012
public ZuulFilter getFilter ( String sCode , String sName ) throws Exception { if ( filterCheck . get ( sName ) == null ) { filterCheck . putIfAbsent ( sName , sName ) ; if ( ! sCode . equals ( filterClassCode . get ( sName ) ) ) { LOG . info ( "reloading code " + sName ) ; filterRegistry . remove ( sName ) ; } } ZuulFilter filter = filterRegistry . get ( sName ) ; if ( filter == null ) { Class clazz = compiler . compile ( sCode , sName ) ; if ( ! Modifier . isAbstract ( clazz . getModifiers ( ) ) ) { filter = filterFactory . newInstance ( clazz ) ; } } return filter ; }
Given source and name will compile and store the filter if it detects that the filter code has changed or the filter doesn t exist . Otherwise it will return an instance of the requested ZuulFilter
19,013
public boolean putFilter ( File file ) throws Exception { try { String sName = file . getAbsolutePath ( ) ; if ( filterClassLastModified . get ( sName ) != null && ( file . lastModified ( ) != filterClassLastModified . get ( sName ) ) ) { LOG . debug ( "reloading filter " + sName ) ; filterRegistry . remove ( sName ) ; } ZuulFilter filter = filterRegistry . get ( sName ) ; if ( filter == null ) { Class clazz = compiler . compile ( file ) ; if ( ! Modifier . isAbstract ( clazz . getModifiers ( ) ) ) { filter = filterFactory . newInstance ( clazz ) ; putFilter ( sName , filter , file . lastModified ( ) ) ; return true ; } } } catch ( Exception e ) { LOG . error ( "Error loading filter! Continuing. file=" + String . valueOf ( file ) , e ) ; return false ; } return false ; }
From a file this will read the ZuulFilter source code compile it and add it to the list of current filters a true response means that it was successful .
19,014
public List < ZuulFilter > putFiltersForClasses ( String [ ] classNames ) throws Exception { List < ZuulFilter > newFilters = new ArrayList < > ( ) ; for ( String className : classNames ) { newFilters . add ( putFilterForClassName ( className ) ) ; } return newFilters ; }
Load and cache filters by className
19,015
public List < ZuulFilter > getFiltersByType ( FilterType filterType ) { List < ZuulFilter > list = hashFiltersByType . get ( filterType ) ; if ( list != null ) return list ; list = new ArrayList < ZuulFilter > ( ) ; Collection < ZuulFilter > filters = filterRegistry . getAllFilters ( ) ; for ( Iterator < ZuulFilter > iterator = filters . iterator ( ) ; iterator . hasNext ( ) ; ) { ZuulFilter filter = iterator . next ( ) ; if ( filter . filterType ( ) . equals ( filterType ) ) { list . add ( filter ) ; } } Collections . sort ( list , new Comparator < ZuulFilter > ( ) { public int compare ( ZuulFilter o1 , ZuulFilter o2 ) { return o1 . filterOrder ( ) - o2 . filterOrder ( ) ; } } ) ; hashFiltersByType . putIfAbsent ( filterType , list ) ; return list ; }
Returns a list of filters by the filterType specified
19,016
public static String getClientIP ( HttpRequestInfo request ) { final String xForwardedFor = request . getHeaders ( ) . getFirst ( HttpHeaderNames . X_FORWARDED_FOR ) ; String clientIP ; if ( xForwardedFor == null ) { clientIP = request . getClientIp ( ) ; } else { clientIP = extractClientIpFromXForwardedFor ( xForwardedFor ) ; } return clientIP ; }
Get the IP address of client making the request .
19,017
public static String extractClientIpFromXForwardedFor ( String xForwardedFor ) { if ( xForwardedFor == null ) { return null ; } xForwardedFor = xForwardedFor . trim ( ) ; String tokenized [ ] = xForwardedFor . split ( "," ) ; if ( tokenized . length == 0 ) { return null ; } else { return tokenized [ 0 ] . trim ( ) ; } }
Extract the client IP address from an x - forwarded - for header . Returns null if there is no x - forwarded - for header
19,018
public static String stripMaliciousHeaderChars ( String input ) { for ( char c : MALICIOUS_HEADER_CHARS ) { input = StringUtils . remove ( input , c ) ; } return input ; }
Ensure decoded new lines are not propagated in headers in order to prevent XSS
19,019
public String getFirst ( String name , String defaultValue ) { String value = getFirst ( name ) ; if ( value == null ) { value = defaultValue ; } return value ; }
Get the first value found for this key even if there are multiple . If none then return the specified defaultValue .
19,020
public Class compile ( String sCode , String sName ) { GroovyClassLoader loader = getGroovyClassLoader ( ) ; LOG . warn ( "Compiling filter: " + sName ) ; Class groovyClass = loader . parseClass ( sCode , sName ) ; return groovyClass ; }
Compiles Groovy code and returns the Class of the compiles code .
19,021
public Class compile ( File file ) throws IOException { GroovyClassLoader loader = getGroovyClassLoader ( ) ; Class groovyClass = loader . parseClass ( file ) ; return groovyClass ; }
Compiles groovy class from a file
19,022
private Channel unlinkFromOrigin ( ) { if ( originResponseReceiver != null ) { originResponseReceiver . unlinkFromClientRequest ( ) ; originResponseReceiver = null ; } if ( concurrentReqCount > 0 ) { origin . recordProxyRequestEnd ( ) ; concurrentReqCount -- ; } Channel origCh = null ; if ( originConn != null ) { origCh = originConn . getChannel ( ) ; originConn = null ; } return origCh ; }
Unlink OriginResponseReceiver from origin channel pipeline so that we no longer receive events
19,023
protected RequestStat createRequestStat ( ) { BasicRequestStat basicRequestStat = new BasicRequestStat ( origin . getName ( ) ) ; RequestStat . putInSessionContext ( basicRequestStat , context ) ; return basicRequestStat ; }
Override to track your own request stats
19,024
public static void addLast ( ChannelPipeline pipeline , long timeout , TimeUnit unit , BasicCounter httpRequestReadTimeoutCounter ) { HttpRequestReadTimeoutHandler handler = new HttpRequestReadTimeoutHandler ( timeout , unit , httpRequestReadTimeoutCounter ) ; pipeline . addLast ( HANDLER_NAME , handler ) ; }
Factory which ensures that this handler is added to the pipeline using the correct name .
19,025
public void putStats ( String route , String cause ) { if ( route == null ) route = "UNKNOWN_ROUTE" ; route = route . replace ( "/" , "_" ) ; ConcurrentHashMap < String , ErrorStatsData > statsMap = routeMap . get ( route ) ; if ( statsMap == null ) { statsMap = new ConcurrentHashMap < String , ErrorStatsData > ( ) ; routeMap . putIfAbsent ( route , statsMap ) ; } ErrorStatsData sd = statsMap . get ( cause ) ; if ( sd == null ) { sd = new ErrorStatsData ( route , cause ) ; ErrorStatsData sd1 = statsMap . putIfAbsent ( cause , sd ) ; if ( sd1 != null ) { sd = sd1 ; } else { MonitorRegistry . getInstance ( ) . registerObject ( sd ) ; } } sd . update ( ) ; }
updates count for the given route and error cause
19,026
protected void registerClient ( ChannelHandlerContext ctx , PushUserAuth authEvent , PushConnection conn , PushConnectionRegistry registry ) { registry . put ( authEvent . getClientIdentity ( ) , conn ) ; ctx . executor ( ) . schedule ( this :: requestClientToCloseConnection , ditheredReconnectDeadline ( ) , TimeUnit . SECONDS ) ; if ( KEEP_ALIVE_ENABLED . get ( ) ) { keepAliveTask = ctx . executor ( ) . scheduleWithFixedDelay ( this :: keepAlive , KEEP_ALIVE_INTERVAL . get ( ) , KEEP_ALIVE_INTERVAL . get ( ) , TimeUnit . SECONDS ) ; } }
Register authenticated client - represented by PushAuthEvent - with PushConnectionRegistry of this instance .
19,027
protected void incrementNamedCountingMonitor ( String name , ConcurrentMap < String , NamedCountingMonitor > map ) { NamedCountingMonitor monitor = map . get ( name ) ; if ( monitor == null ) { monitor = new NamedCountingMonitor ( name ) ; NamedCountingMonitor conflict = map . putIfAbsent ( name , monitor ) ; if ( conflict != null ) monitor = conflict ; else MonitorRegistry . getInstance ( ) . registerObject ( monitor ) ; } monitor . increment ( ) ; }
helper method to create new monitor place into map and register wtih Epic if necessary
19,028
public String getOriginalHost ( ) { String host = getHeaders ( ) . getFirst ( HttpHeaderNames . X_FORWARDED_HOST ) ; if ( host == null ) { host = getHeaders ( ) . getFirst ( HttpHeaderNames . HOST ) ; if ( host != null ) { host = PTN_COLON . split ( host ) [ 0 ] ; } if ( host == null ) { host = getServerName ( ) ; } } return host ; }
The originally request host . This will NOT include port .
19,029
public String reconstructURI ( ) { if ( immutable ) { if ( reconstructedUri == null ) { reconstructedUri = _reconstructURI ( ) ; } return reconstructedUri ; } else { return _reconstructURI ( ) ; } }
Attempt to reconstruct the full URI that the client used .
19,030
public void gracefullyShutdownClientChannels ( ) { LOG . warn ( "Gracefully shutting down all client channels" ) ; try { List < ChannelFuture > futures = new ArrayList < > ( ) ; channels . forEach ( channel -> { ConnectionCloseType . setForChannel ( channel , ConnectionCloseType . DELAYED_GRACEFUL ) ; ChannelFuture f = channel . pipeline ( ) . close ( ) ; futures . add ( f ) ; } ) ; LOG . warn ( "Waiting for " + futures . size ( ) + " client channels to be closed." ) ; for ( ChannelFuture f : futures ) { f . await ( ) ; } LOG . warn ( futures . size ( ) + " client channels closed." ) ; } catch ( InterruptedException ie ) { LOG . warn ( "Interrupted while shutting down client channels" ) ; } }
Note this blocks until all the channels have finished closing .
19,031
public static void addRequestDebug ( SessionContext ctx , String line ) { List < String > rd = getRequestDebug ( ctx ) ; rd . add ( line ) ; }
Adds a line to the Request debug messages
19,032
public static void compareContextState ( String filterName , SessionContext context , SessionContext copy ) { Iterator < String > it = context . keySet ( ) . iterator ( ) ; String key = it . next ( ) ; while ( key != null ) { if ( ( ! key . equals ( "routingDebug" ) && ! key . equals ( "requestDebug" ) ) ) { Object newValue = context . get ( key ) ; Object oldValue = copy . get ( key ) ; if ( oldValue == null && newValue != null ) { addRoutingDebug ( context , "{" + filterName + "} added " + key + "=" + newValue . toString ( ) ) ; } else if ( oldValue != null && newValue != null ) { if ( ! ( oldValue . equals ( newValue ) ) ) { addRoutingDebug ( context , "{" + filterName + "} changed " + key + "=" + newValue . toString ( ) ) ; } } } if ( it . hasNext ( ) ) { key = it . next ( ) ; } else { key = null ; } } }
Adds debug details about changes that a given filter made to the request context .
19,033
protected ZuulFilter < HttpRequestMessage , HttpResponseMessage > newProxyEndpoint ( HttpRequestMessage zuulRequest ) { return new ProxyEndpoint ( zuulRequest , getChannelHandlerContext ( zuulRequest ) , getNextStage ( ) , MethodBinding . NO_OP_BINDING ) ; }
Override to inject your own proxy endpoint implementation
19,034
public static String buildFilterID ( String application_name , FilterType filter_type , String filter_name ) { return application_name + ":" + filter_name + ":" + filter_type . toString ( ) ; }
builds the unique filter_id key
19,035
public void init ( ) throws Exception { long startTime = System . currentTimeMillis ( ) ; filterLoader . putFiltersForClasses ( config . getClassNames ( ) ) ; manageFiles ( ) ; startPoller ( ) ; LOG . warn ( "Finished loading all zuul filters. Duration = " + ( System . currentTimeMillis ( ) - startTime ) + " ms." ) ; }
Initialized the GroovyFileManager .
19,036
public File getDirectory ( String sPath ) { File directory = new File ( sPath ) ; if ( ! directory . isDirectory ( ) ) { URL resource = FilterFileManager . class . getClassLoader ( ) . getResource ( sPath ) ; try { directory = new File ( resource . toURI ( ) ) ; } catch ( Exception e ) { LOG . error ( "Error accessing directory in classloader. path=" + sPath , e ) ; } if ( ! directory . isDirectory ( ) ) { throw new RuntimeException ( directory . getAbsolutePath ( ) + " is not a valid directory" ) ; } } return directory ; }
Returns the directory File for a path . A Runtime Exception is thrown if the directory is in valid
19,037
void processGroovyFiles ( List < File > aFiles ) throws Exception { List < Callable < Boolean > > tasks = new ArrayList < > ( ) ; for ( File file : aFiles ) { tasks . add ( ( ) -> { try { return filterLoader . putFilter ( file ) ; } catch ( Exception e ) { LOG . error ( "Error loading groovy filter from disk! file = " + String . valueOf ( file ) , e ) ; return false ; } } ) ; } processFilesService . invokeAll ( tasks , FILE_PROCESSOR_TASKS_TIMEOUT_SECS . get ( ) , TimeUnit . SECONDS ) ; }
puts files into the FilterLoader . The FilterLoader will only add new or changed filters
19,038
private boolean startsWithAFilteredPAttern ( String string ) { Iterator < String > iterator = filteredFrames . iterator ( ) ; while ( iterator . hasNext ( ) ) { if ( string . trim ( ) . startsWith ( iterator . next ( ) ) ) { return true ; } } return false ; }
Check if the given string starts with any of the filtered patterns .
19,039
public static final CounterFactory instance ( ) { if ( INSTANCE == null ) throw new IllegalStateException ( String . format ( "%s not initialized" , CounterFactory . class . getSimpleName ( ) ) ) ; return INSTANCE ; }
return the singleton CounterFactory instance .
19,040
public void waitForEachEventLoop ( ) throws InterruptedException , ExecutionException { for ( EventExecutor exec : serverGroup . clientToProxyWorkerPool ) { exec . submit ( ( ) -> { } ) . get ( ) ; } }
This is just for use in unit - testing .
19,041
public ZuulFilter newInstance ( Class clazz ) throws InstantiationException , IllegalAccessException { return ( ZuulFilter ) clazz . newInstance ( ) ; }
Returns a new implementation of ZuulFilter as specified by the provided Class . The Class is instantiated using its nullary constructor .
19,042
public boolean getBoolean ( String key , boolean defaultResponse ) { Boolean b = ( Boolean ) get ( key ) ; if ( b != null ) { return b . booleanValue ( ) ; } return defaultResponse ; }
Convenience method to return a boolean value for a given key
19,043
public void set ( String key , Object value ) { if ( value != null ) put ( key , value ) ; else remove ( key ) ; }
puts the key value into the map . a null value will remove the key from the map
19,044
public SessionContext copy ( ) { SessionContext copy = new SessionContext ( ) ; copy . brownoutMode = brownoutMode ; copy . cancelled = cancelled ; copy . shouldStopFilterProcessing = shouldStopFilterProcessing ; copy . shouldSendErrorResponse = shouldSendErrorResponse ; copy . errorResponseSent = errorResponseSent ; copy . debugRouting = debugRouting ; copy . debugRequest = debugRequest ; copy . debugRequestHeadersOnly = debugRequestHeadersOnly ; copy . timings = timings ; Iterator < String > it = keySet ( ) . iterator ( ) ; String key = it . next ( ) ; while ( key != null ) { Object orig = get ( key ) ; try { Object copyValue = DeepCopy . copy ( orig ) ; if ( copyValue != null ) { copy . set ( key , copyValue ) ; } else { copy . set ( key , orig ) ; } } catch ( NotSerializableException e ) { copy . set ( key , orig ) ; } if ( it . hasNext ( ) ) { key = it . next ( ) ; } else { key = null ; } } return copy ; }
Makes a copy of the SessionContext . This is used for debugging .
19,045
public void addFilterExecutionSummary ( String name , String status , long time ) { StringBuilder sb = getFilterExecutionSummary ( ) ; if ( sb . length ( ) > 0 ) sb . append ( ", " ) ; sb . append ( name ) . append ( '[' ) . append ( status ) . append ( ']' ) . append ( '[' ) . append ( time ) . append ( "ms]" ) ; }
appends filter name and status to the filter execution history for the current request
19,046
public FilterInfo verifyFilter ( String sFilterCode ) throws org . codehaus . groovy . control . CompilationFailedException , IllegalAccessException , InstantiationException { Class groovyClass = compileGroovy ( sFilterCode ) ; Object instance = instanciateClass ( groovyClass ) ; checkZuulFilterInstance ( instance ) ; BaseFilter filter = ( BaseFilter ) instance ; String filter_id = FilterInfo . buildFilterID ( ZuulApplicationInfo . getApplicationName ( ) , filter . filterType ( ) , groovyClass . getSimpleName ( ) ) ; return new FilterInfo ( filter_id , sFilterCode , filter . filterType ( ) , groovyClass . getSimpleName ( ) , filter . disablePropertyName ( ) , "" + filter . filterOrder ( ) , ZuulApplicationInfo . getApplicationName ( ) ) ; }
verifies compilation instanciation and that it is a ZuulFilter
19,047
public Class compileGroovy ( String sFilterCode ) throws org . codehaus . groovy . control . CompilationFailedException { GroovyClassLoader loader = new GroovyClassLoader ( ) ; return loader . parseClass ( sFilterCode ) ; }
compiles the Groovy source code
19,048
public static String selectAllColumns ( Class < ? > entityClass ) { StringBuilder sql = new StringBuilder ( ) ; sql . append ( "SELECT " ) ; sql . append ( getAllColumns ( entityClass ) ) ; sql . append ( " " ) ; return sql . toString ( ) ; }
select xxx xxx ...
19,049
public static < T > Flux < T > toFlux ( EventPublisher < T > eventPublisher ) { DirectProcessor < T > directProcessor = DirectProcessor . create ( ) ; eventPublisher . onEvent ( directProcessor :: onNext ) ; return directProcessor ; }
Converts the EventPublisher into a Flux .
19,050
@ ConditionalOnMissingBean ( value = BulkheadEvent . class , parameterizedContainer = EventConsumerRegistry . class ) public EventConsumerRegistry < BulkheadEvent > bulkheadEventConsumerRegistry ( ) { return bulkheadConfiguration . bulkheadEventConsumerRegistry ( ) ; }
The EventConsumerRegistry is used to manage EventConsumer instances . The EventConsumerRegistry is used by the BulkheadHealthIndicator to show the latest Bulkhead events for each Bulkhead instance .
19,051
@ ConditionalOnMissingBean ( value = RetryEvent . class , parameterizedContainer = EventConsumerRegistry . class ) public EventConsumerRegistry < RetryEvent > retryEventConsumerRegistry ( ) { return retryConfiguration . retryEventConsumerRegistry ( ) ; }
The EventConsumerRegistry is used to manage EventConsumer instances . The EventConsumerRegistry is used by the Retry events monitor to show the latest RetryEvent events for each Retry instance .
19,052
public static < T , R > Supplier < R > andThen ( Supplier < T > supplier , Function < T , R > resultHandler ) { return ( ) -> resultHandler . apply ( supplier . get ( ) ) ; }
Returns a composed function that first applies the Supplier and then applies the resultHandler .
19,053
public static < T > Supplier < T > recover ( Supplier < T > supplier , Function < Exception , T > exceptionHandler ) { return ( ) -> { try { return supplier . get ( ) ; } catch ( Exception exception ) { return exceptionHandler . apply ( exception ) ; } } ; }
Returns a composed function that first executes the Supplier and optionally recovers from an exception .
19,054
public static < T , R > Supplier < R > andThen ( Supplier < T > supplier , Function < T , R > resultHandler , Function < Exception , R > exceptionHandler ) { return ( ) -> { try { T result = supplier . get ( ) ; return resultHandler . apply ( result ) ; } catch ( Exception exception ) { return exceptionHandler . apply ( exception ) ; } } ; }
Returns a composed function that first applies the Supplier and then applies either the resultHandler or exceptionHandler .
19,055
private Object handleJoinPointCompletableFuture ( ProceedingJoinPoint proceedingJoinPoint , io . github . resilience4j . circuitbreaker . CircuitBreaker circuitBreaker ) { return circuitBreaker . executeCompletionStage ( ( ) -> { try { return ( CompletionStage < ? > ) proceedingJoinPoint . proceed ( ) ; } catch ( Throwable throwable ) { throw new CompletionException ( throwable ) ; } } ) ; }
handle the CompletionStage return types AOP based into configured circuit - breaker
19,056
private Object defaultHandling ( ProceedingJoinPoint proceedingJoinPoint , io . github . resilience4j . circuitbreaker . CircuitBreaker circuitBreaker ) throws Throwable { return circuitBreaker . executeCheckedSupplier ( proceedingJoinPoint :: proceed ) ; }
the default Java types handling for the circuit breaker AOP
19,057
public static < T , R > Callable < R > andThen ( Callable < T > callable , Function < T , R > resultHandler ) { return ( ) -> resultHandler . apply ( callable . call ( ) ) ; }
Returns a composed function that first applies the Callable and then applies the resultHandler .
19,058
public static < T , R > Callable < R > andThen ( Callable < T > callable , Function < T , R > resultHandler , Function < Exception , R > exceptionHandler ) { return ( ) -> { try { T result = callable . call ( ) ; return resultHandler . apply ( result ) ; } catch ( Exception exception ) { return exceptionHandler . apply ( exception ) ; } } ; }
Returns a composed function that first applies the Callable and then applies either the resultHandler or exceptionHandler .
19,059
public static < T > Callable < T > recover ( Callable < T > callable , Function < Exception , T > exceptionHandler ) { return ( ) -> { try { return callable . call ( ) ; } catch ( Exception exception ) { return exceptionHandler . apply ( exception ) ; } } ; }
Returns a composed function that first executes the Callable and optionally recovers from an exception .
19,060
public static < T extends Annotation > T extract ( Class < ? > targetClass , Class < T > annotationClass ) { T annotation = null ; if ( targetClass . isAnnotationPresent ( annotationClass ) ) { annotation = targetClass . getAnnotation ( annotationClass ) ; if ( annotation == null && logger . isDebugEnabled ( ) ) { logger . debug ( "TargetClass has no annotation '{}'" , annotationClass . getSimpleName ( ) ) ; annotation = targetClass . getDeclaredAnnotation ( annotationClass ) ; if ( annotation == null && logger . isDebugEnabled ( ) ) { logger . debug ( "TargetClass has no declared annotation '{}'" , annotationClass . getSimpleName ( ) ) ; } } } return annotation ; }
extract annotation from target class
19,061
public static CircuitBreakerCallAdapter of ( final CircuitBreaker circuitBreaker , final Predicate < Response > successResponse ) { return new CircuitBreakerCallAdapter ( circuitBreaker , successResponse ) ; }
Create a circuit - breaking call adapter that decorates retrofit calls
19,062
int set ( int bitIndex , boolean value ) { int wordIndex = wordIndex ( bitIndex ) ; long bitMask = 1L << bitIndex ; int previous = ( words [ wordIndex ] & bitMask ) != 0 ? 1 : 0 ; if ( value ) { words [ wordIndex ] |= bitMask ; } else { words [ wordIndex ] &= ~ bitMask ; } return previous ; }
Sets the bit at the specified index to value .
19,063
boolean get ( int bitIndex ) { int wordIndex = wordIndex ( bitIndex ) ; long bitMask = 1L << bitIndex ; return ( words [ wordIndex ] & bitMask ) != 0 ; }
Gets the bit at the specified index .
19,064
public CircuitBreakerRegistry createCircuitBreakerRegistry ( CircuitBreakerConfigurationProperties circuitBreakerProperties ) { Map < String , CircuitBreakerConfig > configs = circuitBreakerProperties . getConfigs ( ) . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( Map . Entry :: getKey , entry -> circuitBreakerProperties . createCircuitBreakerConfig ( entry . getValue ( ) ) ) ) ; return CircuitBreakerRegistry . of ( configs ) ; }
Initializes a circuitBreaker registry .
19,065
public void initCircuitBreakerRegistry ( CircuitBreakerRegistry circuitBreakerRegistry ) { circuitBreakerProperties . getBackends ( ) . forEach ( ( name , properties ) -> circuitBreakerRegistry . circuitBreaker ( name , circuitBreakerProperties . createCircuitBreakerConfig ( properties ) ) ) ; }
Initializes the CircuitBreaker registry .
19,066
public void registerEventConsumer ( CircuitBreakerRegistry circuitBreakerRegistry , EventConsumerRegistry < CircuitBreakerEvent > eventConsumerRegistry ) { circuitBreakerRegistry . getEventPublisher ( ) . onEntryAdded ( event -> registerEventConsumer ( eventConsumerRegistry , event . getAddedEntry ( ) ) ) ; }
Registers the post creation consumer function that registers the consumer events to the circuit breakers .
19,067
public synchronized int setNextBit ( boolean value ) { increaseLength ( ) ; index = ( index + 1 ) % size ; int previous = bitSet . set ( index , value ) ; int current = value ? 1 : 0 ; cardinality = cardinality - previous + current ; return cardinality ; }
Sets the bit at the next index to the specified value .
19,068
public static < T > Flowable < T > toFlowable ( EventPublisher < T > eventPublisher ) { PublishProcessor < T > publishProcessor = PublishProcessor . create ( ) ; FlowableProcessor < T > flowableProcessor = publishProcessor . toSerialized ( ) ; eventPublisher . onEvent ( flowableProcessor :: onNext ) ; return flowableProcessor ; }
Converts the EventPublisher into a Flowable .
19,069
public static < T > Observable < T > toObservable ( EventPublisher < T > eventPublisher ) { PublishSubject < T > publishSubject = PublishSubject . create ( ) ; Subject < T > serializedSubject = publishSubject . toSerialized ( ) ; eventPublisher . onEvent ( serializedSubject :: onNext ) ; return serializedSubject ; }
Converts the EventPublisher into an Observable .
19,070
private void configureRetryIntervalFunction ( BackendProperties properties , RetryConfig . Builder < Object > builder ) { if ( properties . getWaitDuration ( ) != 0 ) { long waitDuration = properties . getWaitDuration ( ) ; if ( properties . getEnableExponentialBackoff ( ) ) { if ( properties . getExponentialBackoffMultiplier ( ) != 0 ) { builder . intervalFunction ( IntervalFunction . ofExponentialBackoff ( waitDuration , properties . getExponentialBackoffMultiplier ( ) ) ) ; } else { builder . intervalFunction ( IntervalFunction . ofExponentialBackoff ( properties . getWaitDuration ( ) ) ) ; } } else if ( properties . getEnableRandomizedWait ( ) ) { if ( properties . getRandomizedWaitFactor ( ) != 0 ) { builder . intervalFunction ( IntervalFunction . ofRandomized ( waitDuration , properties . getRandomizedWaitFactor ( ) ) ) ; } else { builder . intervalFunction ( IntervalFunction . ofRandomized ( waitDuration ) ) ; } } else { builder . waitDuration ( Duration . ofMillis ( properties . getWaitDuration ( ) ) ) ; } } }
decide which retry delay polciy will be configured based into the configured properties
19,071
private static < T > Consumer < T > throwingConsumerWrapper ( ThrowingConsumer < T , Exception > throwingConsumer ) { return i -> { try { throwingConsumer . accept ( i ) ; } catch ( Exception ex ) { throw new RetryExceptionWrapper ( ex ) ; } } ; }
to handle checked exception handling in reactor Function java 8 doOnNext
19,072
public List < UserDictionaryMatch > findUserDictionaryMatches ( String text ) { List < UserDictionaryMatch > matchInfos = new ArrayList < > ( ) ; int startIndex = 0 ; while ( startIndex < text . length ( ) ) { int matchLength = 0 ; while ( startIndex + matchLength < text . length ( ) && entries . containsKeyPrefix ( text . substring ( startIndex , startIndex + matchLength + 1 ) ) ) { matchLength ++ ; } if ( matchLength > 0 ) { String match = text . substring ( startIndex , startIndex + matchLength ) ; int [ ] details = entries . get ( match ) ; if ( details != null ) { matchInfos . addAll ( makeMatchDetails ( startIndex , details ) ) ; } } startIndex ++ ; } return matchInfos ; }
Lookup words in text
19,073
public void setStateViewArray ( INDArray viewArray ) { if ( this . updaterStateViewArray == null ) { if ( viewArray == null ) return ; else { throw new IllegalStateException ( "Attempting to set updater state view array with null value" ) ; } } if ( this . updaterStateViewArray . length ( ) != viewArray . length ( ) ) throw new IllegalStateException ( "Invalid input: view arrays differ in length. " + "Expected length " + this . updaterStateViewArray . length ( ) + ", got length " + viewArray . length ( ) ) ; this . updaterStateViewArray . assign ( viewArray ) ; }
Set the view array . Note that this does an assign operation - the provided array is not stored internally .
19,074
public INDArray getCorruptedInput ( INDArray x , double corruptionLevel ) { INDArray corrupted = Nd4j . getDistributions ( ) . createBinomial ( 1 , 1 - corruptionLevel ) . sample ( x . ulike ( ) ) ; corrupted . muli ( x . castTo ( corrupted . dataType ( ) ) ) ; return corrupted ; }
Corrupts the given input by doing a binomial sampling given the corruption level
19,075
public boolean containsPoint ( INDArray point ) { double first = point . getDouble ( 0 ) , second = point . getDouble ( 1 ) ; return x - hw <= first && x + hw >= first && y - hh <= second && y + hh >= second ; }
Whether the given point is contained within this cell
19,076
public synchronized void shutdown ( ) { if ( zoo == null ) return ; for ( int e = 0 ; e < zoo . length ; e ++ ) { if ( zoo [ e ] == null ) continue ; zoo [ e ] . interrupt ( ) ; zoo [ e ] . shutdown ( ) ; zoo [ e ] = null ; } zoo = null ; System . gc ( ) ; }
This method gracefully shuts down ParallelInference instance
19,077
public static boolean checkGradients ( MultiLayerNetwork mln , double epsilon , double maxRelError , double minAbsoluteError , boolean print , boolean exitOnFirstError , INDArray input , INDArray labels ) { return checkGradients ( mln , epsilon , maxRelError , minAbsoluteError , print , exitOnFirstError , input , labels , null , null ) ; }
Check backprop gradients for a MultiLayerNetwork .
19,078
public static boolean checkGradients ( ComputationGraph graph , double epsilon , double maxRelError , double minAbsoluteError , boolean print , boolean exitOnFirstError , INDArray [ ] inputs , INDArray [ ] labels ) { return checkGradients ( graph , epsilon , maxRelError , minAbsoluteError , print , exitOnFirstError , inputs , labels , null , null , null ) ; }
Check backprop gradients for a ComputationGraph
19,079
public static Window windowForWordInPosition ( int windowSize , int wordPos , List < String > sentence ) { List < String > window = new ArrayList < > ( ) ; List < String > onlyTokens = new ArrayList < > ( ) ; int contextSize = ( int ) Math . floor ( ( windowSize - 1 ) / 2 ) ; for ( int i = wordPos - contextSize ; i <= wordPos + contextSize ; i ++ ) { if ( i < 0 ) window . add ( "<s>" ) ; else if ( i >= sentence . size ( ) ) window . add ( "</s>" ) ; else { onlyTokens . add ( sentence . get ( i ) ) ; window . add ( sentence . get ( i ) ) ; } } String wholeSentence = StringUtils . join ( sentence ) ; String window2 = StringUtils . join ( onlyTokens ) ; int begin = wholeSentence . indexOf ( window2 ) ; int end = begin + window2 . length ( ) ; return new Window ( window , begin , end ) ; }
Creates a sliding window from text
19,080
public static List < Window > windows ( List < String > words , int windowSize ) { List < Window > ret = new ArrayList < > ( ) ; for ( int i = 0 ; i < words . size ( ) ; i ++ ) ret . add ( windowForWordInPosition ( windowSize , i , words ) ) ; return ret ; }
Constructs a list of window of size windowSize
19,081
public static BatchCSVRecord fromWritables ( List < List < Writable > > batch ) { List < SingleCSVRecord > records = new ArrayList < > ( batch . size ( ) ) ; for ( List < Writable > list : batch ) { List < String > add = new ArrayList < > ( list . size ( ) ) ; for ( Writable writable : list ) { add . add ( writable . toString ( ) ) ; } records . add ( new SingleCSVRecord ( add ) ) ; } return BatchCSVRecord . builder ( ) . records ( records ) . build ( ) ; }
Create a batch csv record from a list of writables .
19,082
public void setCurrentIndex ( long curr ) { try { if ( curr < 0 || curr > count ) { throw new RuntimeException ( curr + " is not in the range 0 to " + count ) ; } seek ( getHeaderSize ( ) + curr * getEntryLength ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Set the required current entry index .
19,083
public void processBlasCall ( String blasOpName ) { String key = "BLAS" ; invocationsCount . incrementAndGet ( ) ; opCounter . incrementCount ( blasOpName ) ; classCounter . incrementCount ( key ) ; updatePairs ( blasOpName , key ) ; prevOpMatching = "" ; lastZ = 0 ; }
This method tracks blasCalls
19,084
public void processStackCall ( Op op , long timeStart ) { long timeSpent = ( System . nanoTime ( ) - timeStart ) / 1000 ; methodsAggregator . incrementCount ( timeSpent ) ; }
This method builds
19,085
public PenaltyCause [ ] processOperands ( INDArray ... operands ) { if ( operands == null ) return new PenaltyCause [ ] { NONE } ; List < PenaltyCause > causes = new ArrayList < > ( ) ; for ( int e = 0 ; e < operands . length - 1 ; e ++ ) { if ( operands [ e ] == null && operands [ e + 1 ] == null ) continue ; PenaltyCause lc [ ] = processOperands ( operands [ e ] , operands [ e + 1 ] ) ; for ( PenaltyCause cause : lc ) { if ( cause != NONE && ! causes . contains ( cause ) ) causes . add ( cause ) ; } } if ( causes . isEmpty ( ) ) causes . add ( NONE ) ; return causes . toArray ( new PenaltyCause [ 0 ] ) ; }
This method checks for something somewhere
19,086
public Object getValue ( Field property ) { try { return property . get ( this ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } return null ; }
Get the value for a given property for this function
19,087
public SDVariable arg ( int num ) { SDVariable [ ] args = args ( ) ; Preconditions . checkNotNull ( args , "Arguments are null for function %s" , this . getOwnName ( ) ) ; Preconditions . checkArgument ( num >= 0 && num < args . length , "Invalid index: must be 0 to numArgs (0 <= idx < %s)" , args . length ) ; return args [ num ] ; }
Return the specified argument for this function
19,088
public void resolvePropertiesFromSameDiffBeforeExecution ( ) { val properties = sameDiff . propertiesToResolveForFunction ( this ) ; val fields = DifferentialFunctionClassHolder . getInstance ( ) . getFieldsForFunction ( this ) ; val currentFields = this . propertiesForFunction ( ) ; for ( val property : properties ) { if ( ! fields . containsKey ( property ) ) continue ; val var = sameDiff . getVarNameForFieldAndFunction ( this , property ) ; val fieldType = fields . get ( property ) ; val varArr = sameDiff . getArrForVarName ( var ) ; if ( currentFields . containsKey ( property ) ) { continue ; } if ( varArr == null ) { throw new ND4JIllegalStateException ( "Unable to set null array!" ) ; } if ( fieldType . getType ( ) . equals ( int [ ] . class ) ) { setValueFor ( fieldType , varArr . data ( ) . asInt ( ) ) ; } else if ( fieldType . equals ( double [ ] . class ) ) { setValueFor ( fieldType , varArr . data ( ) . asDouble ( ) ) ; } else if ( fieldType . equals ( int . class ) ) { setValueFor ( fieldType , varArr . getInt ( 0 ) ) ; } else if ( fieldType . equals ( double . class ) ) { setValueFor ( fieldType , varArr . getDouble ( 0 ) ) ; } } }
Resolve properties and arguments right before execution of this operation .
19,089
public List < SDVariable > diff ( List < SDVariable > i_v1 ) { List < SDVariable > vals = doDiff ( i_v1 ) ; if ( vals == null ) { throw new IllegalStateException ( "Error executing diff operation: doDiff returned null for op: " + this . opName ( ) ) ; } val outputVars = args ( ) ; boolean copied = false ; for ( int i = 0 ; i < vals . size ( ) ; i ++ ) { SDVariable var = outputVars [ i ] ; SDVariable grad = var . hasGradient ( ) ? var . getGradient ( ) : null ; if ( grad != null ) { if ( ! copied ) { vals = new ArrayList < > ( vals ) ; copied = true ; } SDVariable gradVar = f ( ) . add ( grad , vals . get ( i ) ) ; vals . set ( i , gradVar ) ; sameDiff . setGradientForVariableName ( var . getVarName ( ) , gradVar ) ; } else { SDVariable gradVar = vals . get ( i ) ; sameDiff . updateVariableNameAndReference ( gradVar , var . getVarName ( ) + "-grad" ) ; sameDiff . setGradientForVariableName ( var . getVarName ( ) , gradVar ) ; sameDiff . setForwardVariableForVarName ( gradVar . getVarName ( ) , var ) ; } } return vals ; }
Perform automatic differentiation wrt the input variables
19,090
public SDVariable larg ( ) { val args = args ( ) ; if ( args == null || args . length == 0 ) throw new ND4JIllegalStateException ( "No arguments found." ) ; return args ( ) [ 0 ] ; }
The left argument for this function
19,091
public void cumSumWithinPartition ( ) { final Accumulator < Counter < Integer > > maxPerPartitionAcc = sc . accumulator ( new Counter < Integer > ( ) , new MaxPerPartitionAccumulator ( ) ) ; foldWithinPartitionRDD = sentenceCountRDD . mapPartitionsWithIndex ( new FoldWithinPartitionFunction ( maxPerPartitionAcc ) , true ) . cache ( ) ; actionForMapPartition ( foldWithinPartitionRDD ) ; broadcastedMaxPerPartitionCounter = sc . broadcast ( maxPerPartitionAcc . value ( ) ) ; }
Do cum sum within the partition
19,092
private Object readResolve ( ) throws java . io . ObjectStreamException { return Nd4j . create ( data , arrayShape , Nd4j . getStrides ( arrayShape , arrayOrdering ) , 0 , arrayOrdering ) ; }
READ DONE HERE - return an NDArray using the available backend
19,093
protected void read ( ObjectInputStream s ) throws IOException , ClassNotFoundException { val header = BaseDataBuffer . readHeader ( s ) ; data = Nd4j . createBuffer ( header . getRight ( ) , length , false ) ; data . read ( s , header . getLeft ( ) , header . getMiddle ( ) , header . getRight ( ) ) ; }
Custom deserialization for Java serialization
19,094
public synchronized void add ( T actual , T predicted , int count ) { if ( matrix . containsKey ( actual ) ) { matrix . get ( actual ) . add ( predicted , count ) ; } else { Multiset < T > counts = HashMultiset . create ( ) ; counts . add ( predicted , count ) ; matrix . put ( actual , counts ) ; } }
Increments the entry specified by actual and predicted by count .
19,095
public synchronized void add ( ConfusionMatrix < T > other ) { for ( T actual : other . matrix . keySet ( ) ) { Multiset < T > counts = other . matrix . get ( actual ) ; for ( T predicted : counts . elementSet ( ) ) { int count = counts . count ( predicted ) ; this . add ( actual , predicted , count ) ; } } }
Adds the entries from another confusion matrix to this one .
19,096
public synchronized int getCount ( T actual , T predicted ) { if ( ! matrix . containsKey ( actual ) ) { return 0 ; } else { return matrix . get ( actual ) . count ( predicted ) ; } }
Gives the count of the number of times the predicted class was predicted for the actual class .
19,097
public synchronized int getPredictedTotal ( T predicted ) { int total = 0 ; for ( T actual : classes ) { total += getCount ( actual , predicted ) ; } return total ; }
Computes the total number of times the class was predicted by the classifier .
19,098
public synchronized int getActualTotal ( T actual ) { if ( ! matrix . containsKey ( actual ) ) { return 0 ; } else { int total = 0 ; for ( T elem : matrix . get ( actual ) . elementSet ( ) ) { total += matrix . get ( actual ) . count ( elem ) ; } return total ; } }
Computes the total number of times the class actually appeared in the data .
19,099
public String toCSV ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( ",,Predicted Class,\n" ) ; builder . append ( ",," ) ; for ( T predicted : classes ) { builder . append ( String . format ( "%s," , predicted ) ) ; } builder . append ( "Total\n" ) ; String firstColumnLabel = "Actual Class," ; for ( T actual : classes ) { builder . append ( firstColumnLabel ) ; firstColumnLabel = "," ; builder . append ( String . format ( "%s," , actual ) ) ; for ( T predicted : classes ) { builder . append ( getCount ( actual , predicted ) ) ; builder . append ( "," ) ; } builder . append ( getActualTotal ( actual ) ) ; builder . append ( "\n" ) ; } builder . append ( ",Total," ) ; for ( T predicted : classes ) { builder . append ( getPredictedTotal ( predicted ) ) ; builder . append ( "," ) ; } builder . append ( "\n" ) ; return builder . toString ( ) ; }
Outputs the ConfusionMatrix as comma - separated values for easy import into spreadsheets