idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
122,400
public static ServiceAdapter < BlockingService > forBlockingService ( ) { return new SimpleServiceAdapter < BlockingService > ( ) { protected void start ( BlockingService instance ) throws Exception { instance . start ( ) ; } protected void stop ( BlockingService instance ) throws Exception { instance . stop ( ) ; } } ...
Returns factory which transforms blocking Service to asynchronous non - blocking ConcurrentService . It runs blocking operations from other thread from executor .
122,401
public static ServiceAdapter < Timer > forTimer ( ) { return new SimpleServiceAdapter < Timer > ( false , false ) { protected void start ( Timer instance ) { } protected void stop ( Timer instance ) { instance . cancel ( ) ; } } ; }
Returns factory which transforms Timer to ConcurrentService . On starting it doing nothing on stop it cancel timer .
122,402
public static ServiceAdapter < ExecutorService > forExecutorService ( ) { return new SimpleServiceAdapter < ExecutorService > ( false , true ) { protected void start ( ExecutorService instance ) { } protected void stop ( ExecutorService instance ) throws Exception { List < Runnable > runnables = instance . shutdownNow ...
Returns factory which transforms ExecutorService to ConcurrentService . On starting it doing nothing on stopping it shuts down ExecutorService .
122,403
public static ServiceAdapter < Closeable > forCloseable ( ) { return new SimpleServiceAdapter < Closeable > ( false , true ) { protected void start ( Closeable instance ) { } protected void stop ( Closeable instance ) throws Exception { instance . close ( ) ; } } ; }
Returns factory which transforms Closeable object to ConcurrentService . On starting it doing nothing on stopping it close Closeable .
122,404
public static ServiceAdapter < DataSource > forDataSource ( ) { return new SimpleServiceAdapter < DataSource > ( true , false ) { protected void start ( DataSource instance ) throws Exception { Connection connection = instance . getConnection ( ) ; connection . close ( ) ; } protected void stop ( DataSource instance ) ...
Returns factory which transforms DataSource object to ConcurrentService . On starting it checks connecting on stopping it close DataSource .
122,405
public static String renderQueryString ( Map < String , String > q , String enc ) { StringBuilder sb = new StringBuilder ( ) ; for ( Map . Entry < String , String > e : q . entrySet ( ) ) { String name = urlEncode ( e . getKey ( ) , enc ) ; sb . append ( name ) ; if ( e . getValue ( ) != null ) { sb . append ( '=' ) ; ...
Method which creates string with parameters and its value in format URL
122,406
@ Contract ( pure = true ) public ByteBuf peekBuf ( ) { return hasRemaining ( ) ? bufs [ first ] : null ; }
Returns the first ByteBuf of this queue if the queue is not empty . Otherwise returns null .
122,407
@ Contract ( pure = true ) public int remainingBufs ( ) { return last >= first ? last - first : bufs . length + ( last - first ) ; }
Returns the number of ByteBufs in this queue .
122,408
@ Contract ( pure = true ) public int remainingBytes ( ) { int result = 0 ; for ( int i = first ; i != last ; i = next ( i ) ) { result += bufs [ i ] . readRemaining ( ) ; } return result ; }
Returns the number of bytes in this queue .
122,409
@ Contract ( pure = true ) public byte peekByte ( ) { assert hasRemaining ( ) ; ByteBuf buf = bufs [ first ] ; return buf . peek ( ) ; }
Returns the first byte from this queue without any recycling .
122,410
@ SuppressWarnings ( "PointlessArithmeticExpression" ) protected void onStartLine ( byte [ ] line , int limit ) throws ParseException { switchPool ( server . poolReadWrite ) ; HttpMethod method = getHttpMethod ( line ) ; if ( method == null ) { throw new UnknownFormatException ( HttpServerConnection . class , "Unknown ...
This method is called after received line of header .
122,411
protected void onHeader ( HttpHeader header , byte [ ] array , int off , int len ) throws ParseException { if ( header == HttpHeaders . EXPECT ) { if ( equalsLowerCaseAscii ( EXPECT_100_CONTINUE , array , off , len ) ) { socket . write ( ByteBuf . wrapForReading ( EXPECT_RESPONSE_CONTINUE ) ) ; } } if ( request . heade...
This method is called after receiving header . It sets its value to request .
122,412
public static < K , T > StreamMerger < K , T > create ( Function < T , K > keyFunction , Comparator < K > keyComparator , boolean distinct ) { return new StreamMerger < > ( keyFunction , keyComparator , distinct ) ; }
Returns new instance of StreamMerger
122,413
public static < K , I , O , A > StreamReducerSimple < K , I , O , A > create ( Function < I , K > keyFunction , Comparator < K > keyComparator , Reducer < K , I , O , A > reducer ) { return new StreamReducerSimple < > ( keyFunction , keyComparator , reducer ) ; }
Creates a new instance of StreamReducerSimple
122,414
public static Aggregation create ( Eventloop eventloop , Executor executor , DefiningClassLoader classLoader , AggregationChunkStorage aggregationChunkStorage , AggregationStructure structure ) { checkArgument ( structure != null , "Cannot create Aggregation with AggregationStructure that is null" ) ; return new Aggreg...
Instantiates an aggregation with the specified structure that runs in a given event loop uses the specified class loader for creating dynamic classes saves data and metadata to given storages . Maximum size of chunk is 1 000 000 bytes . No more than 1 000 000 records stay in memory while sorting . Maximum duration of c...
122,415
public static < K , O , A > StreamReducer < K , O , A > create ( Comparator < K > keyComparator ) { return new StreamReducer < > ( keyComparator ) ; }
Creates a new instance of StreamReducer
122,416
public < I > StreamConsumer < I > newInput ( Function < I , K > keyFunction , Reducer < K , I , O , A > reducer ) { return super . newInput ( keyFunction , reducer ) ; }
Creates a new input stream for this reducer
122,417
public static < K , L , R , V > StreamJoin < K , L , R , V > create ( Comparator < K > keyComparator , Function < L , K > leftKeyFunction , Function < R , K > rightKeyFunction , Joiner < K , L , R , V > joiner ) { return new StreamJoin < > ( keyComparator , leftKeyFunction , rightKeyFunction , joiner ) ; }
Creates a new instance of StreamJoin
122,418
public static ByteBuf createDnsQueryPayload ( DnsTransaction transaction ) { ByteBuf byteBuf = ByteBufPool . allocate ( MAX_SIZE ) ; byteBuf . writeShort ( transaction . getId ( ) ) ; byteBuf . write ( STANDARD_QUERY_HEADER ) ; byte componentSize = 0 ; DnsQuery query = transaction . getQuery ( ) ; byte [ ] domainBytes ...
Creates a bytebuf with a DNS query payload
122,419
public int read ( ) throws IOException { if ( pos >= limit ) return - 1 ; try { int c = buf [ pos ] & 0xff ; if ( c < 0x80 ) { pos ++ ; } else if ( c < 0xE0 ) { c = ( char ) ( ( c & 0x1F ) << 6 | buf [ pos + 1 ] & 0x3F ) ; pos += 2 ; } else { c = ( char ) ( ( c & 0x0F ) << 12 | ( buf [ pos + 1 ] & 0x3F ) << 6 | ( buf [...
Reads a single character
122,420
private void skipHeaders ( int flag ) { if ( ( flag & FEXTRA ) != 0 ) { skipExtra ( flag ) ; } else if ( ( flag & FNAME ) != 0 ) { skipTerminatorByte ( flag , FNAME ) ; } else if ( ( flag & FCOMMENT ) != 0 ) { skipTerminatorByte ( flag , FCOMMENT ) ; } else if ( ( flag & FHCRC ) != 0 ) { skipCRC16 ( flag ) ; } }
region skip header fields
122,421
public RemoteFsClusterClient withPartition ( Object id , FsClient client ) { clients . put ( id , client ) ; aliveClients . put ( id , client ) ; return this ; }
Adds given client with given partition id to this cluster
122,422
public RemoteFsClusterClient withReplicationCount ( int replicationCount ) { checkArgument ( 1 <= replicationCount && replicationCount <= clients . size ( ) , "Replication count cannot be less than one or more than number of clients" ) ; this . replicationCount = replicationCount ; return this ; }
Sets the replication count that determines how many copies of the file should persist over the cluster .
122,423
private static < T , U > Promise < T > ofFailure ( String message , List < Try < U > > failed ) { StacklessException exception = new StacklessException ( RemoteFsClusterClient . class , message ) ; failed . stream ( ) . map ( Try :: getExceptionOrNull ) . filter ( Objects :: nonNull ) . forEach ( exception :: addSuppre...
shortcut for creating single Exception from list of possibly failed tries
122,424
public static Expression cast ( Expression expression , Class < ? > type ) { return cast ( expression , getType ( type ) ) ; }
Casts expression to the type
122,425
public static PredicateDef cmpEq ( Expression left , Expression right ) { return cmp ( CompareOperation . EQ , left , right ) ; }
Verifies that the arguments are equal
122,426
public static Expression asEquals ( List < String > properties ) { PredicateDefAnd predicate = PredicateDefAnd . create ( ) ; for ( String property : properties ) { predicate . add ( cmpEq ( property ( self ( ) , property ) , property ( cast ( arg ( 0 ) , ExpressionCast . THIS_TYPE ) , property ) ) ) ; } return predica...
Verifies that the properties are equal
122,427
public static Expression asString ( List < String > properties ) { ExpressionToString toString = new ExpressionToString ( ) ; for ( String property : properties ) { toString . withArgument ( property + "=" , property ( self ( ) , property ) ) ; } return toString ; }
Returns the string which was constructed from properties
122,428
public static ExpressionHash hashCodeOfThis ( List < String > properties ) { List < Expression > arguments = new ArrayList < > ( ) ; for ( String property : properties ) { arguments . add ( property ( new VarThis ( ) , property ) ) ; } return new ExpressionHash ( arguments ) ; }
Returns hash of the properties
122,429
public static ExpressionArithmeticOp add ( Expression left , Expression right ) { return new ExpressionArithmeticOp ( ArithmeticOperation . ADD , left , right ) ; }
Returns sum of arguments
122,430
public static ExpressionConstructor constructor ( Class < ? > type , Expression ... fields ) { return new ExpressionConstructor ( type , asList ( fields ) ) ; }
Returns new instance of class
122,431
public static VarLocal newLocal ( Context ctx , Type type ) { int local = ctx . getGeneratorAdapter ( ) . newLocal ( type ) ; return new VarLocal ( local ) ; }
Returns a new local variable from a given context
122,432
public DnsQueryCacheResult tryToResolve ( DnsQuery query ) { CachedDnsQueryResult cachedResult = cache . get ( query ) ; if ( cachedResult == null ) { logger . trace ( "{} cache miss" , query ) ; return null ; } DnsResponse result = cachedResult . response ; assert result != null ; if ( result . isSuccessful ( ) ) { lo...
Tries to get status of the entry for some query from the cache .
122,433
public void add ( DnsQuery query , DnsResponse response ) { assert eventloop . inEventloopThread ( ) : "Concurrent cache adds are not allowed" ; long expirationTime = now . currentTimeMillis ( ) ; if ( response . isSuccessful ( ) ) { assert response . getRecord ( ) != null ; long minTtl = response . getRecord ( ) . get...
Adds DnsResponse to this cache
122,434
@ SuppressWarnings ( "unchecked" ) public DatagraphEnvironment with ( Object key , Object value ) { ( ( Map < Object , Object > ) instances ) . put ( key , value ) ; return this ; }
Sets the given value for the specified key .
122,435
public static int encodeUtf8 ( byte [ ] array , int pos , String string ) { int p = pos ; for ( int i = 0 ; i < string . length ( ) ; i ++ ) { p += encodeUtf8 ( array , p , string . charAt ( i ) ) ; } return p - pos ; }
UTF - 8
122,436
public static Object fetchAnnotationElementValue ( Annotation annotation , Method element ) throws ReflectiveOperationException { Object value = element . invoke ( annotation ) ; if ( value == null ) { String errorMsg = "@" + annotation . annotationType ( ) . getName ( ) + "." + element . getName ( ) + "() returned nul...
Returns values if it is not null otherwise throws exception
122,437
public ClassBuilder < T > withField ( String field , Class < ? > fieldClass ) { fields . put ( field , fieldClass ) ; return this ; }
Creates a new field for a dynamic class
122,438
public ClassBuilder < T > withMethod ( String methodName , Expression expression ) { if ( methodName . contains ( "(" ) ) { Method method = Method . getMethod ( methodName ) ; return withMethod ( method , expression ) ; } Method foundMethod = null ; List < List < java . lang . reflect . Method > > listOfMethods = new A...
CCreates a new method for a dynamic class
122,439
public final void setConsumer ( StreamConsumer < T > consumer ) { checkNotNull ( consumer ) ; checkState ( this . consumer == null , "Consumer has already been set" ) ; checkState ( getCapabilities ( ) . contains ( LATE_BINDING ) || eventloop . tick ( ) == createTick , LATE_BINDING_ERROR_MESSAGE , this ) ; this . consu...
Sets consumer for this supplier . At the moment of calling this method supplier shouldn t have consumer as well as consumer shouldn t have supplier otherwise there will be error
122,440
public void execute ( ) { Map < Partition , List < Node > > map = getNodesByPartition ( ) ; for ( Partition partition : map . keySet ( ) ) { List < Node > nodes = map . get ( partition ) ; partition . execute ( nodes ) ; } }
Executes the defined operations on all partitions .
122,441
public DynamicMBean createFor ( List < ? > monitorables , MBeanSettings setting , boolean enableRefresh ) { checkNotNull ( monitorables ) ; checkArgument ( monitorables . size ( ) > 0 , "Size of list of monitorables should be greater than 0" ) ; checkArgument ( monitorables . stream ( ) . noneMatch ( Objects :: isNull ...
Creates Jmx MBean for monitorables with operations and attributes .
122,442
private void handleJmxRefreshables ( List < MBeanWrapper > mbeanWrappers , AttributeNodeForPojo rootNode ) { for ( MBeanWrapper mbeanWrapper : mbeanWrappers ) { Eventloop eventloop = mbeanWrapper . getEventloop ( ) ; List < JmxRefreshable > currentRefreshables = rootNode . getAllRefreshables ( mbeanWrapper . getMBean (...
region refreshing jmx
122,443
private AttributeNodeForPojo createAttributesTree ( Class < ? > clazz , Map < Type , JmxCustomTypeAdapter < ? > > customTypes ) { List < AttributeNode > subNodes = createNodesFor ( clazz , clazz , new String [ 0 ] , null , customTypes ) ; return new AttributeNodeForPojo ( "" , null , true , new ValueFetcherDirect ( ) ,...
Creates attribute tree of Jmx attributes for clazz .
122,444
private static MBeanInfo createMBeanInfo ( AttributeNodeForPojo rootNode , Class < ? > monitorableClass ) { String monitorableName = "" ; String monitorableDescription = "" ; MBeanAttributeInfo [ ] attributes = rootNode != null ? fetchAttributesInfo ( rootNode ) : new MBeanAttributeInfo [ 0 ] ; MBeanOperationInfo [ ] o...
region creating jmx metadata - MBeanInfo
122,445
private static Map < OperationKey , Method > fetchOpkeyToMethod ( Class < ? > mbeanClass ) { Map < OperationKey , Method > opkeyToMethod = new HashMap < > ( ) ; Method [ ] methods = mbeanClass . getMethods ( ) ; for ( Method method : methods ) { if ( method . isAnnotationPresent ( JmxOperation . class ) ) { JmxOperatio...
region jmx operations fetching
122,446
public Promise < HttpResponse > send ( HttpRequest request ) { SettablePromise < HttpResponse > promise = new SettablePromise < > ( ) ; this . promise = promise ; assert pool == null ; ( pool = client . poolReadWrite ) . addLastNode ( this ) ; poolTimestamp = eventloop . currentTimeMillis ( ) ; HttpHeaderValue connecti...
Sends the request recycles it and closes connection in case of timeout
122,447
protected void onClosed ( ) { assert promise == null ; if ( pool == client . poolKeepAlive ) { AddressLinkedList addresses = client . addresses . get ( remoteAddress ) ; addresses . removeNode ( this ) ; if ( addresses . isEmpty ( ) ) { client . addresses . remove ( remoteAddress ) ; } } pool . removeNode ( this ) ; po...
After closing this connection it removes it from its connections cache and recycles Http response .
122,448
public Promise < HttpResponse > request ( HttpRequest request ) { assert eventloop . inEventloopThread ( ) ; if ( inspector != null ) inspector . onRequest ( request ) ; String host = request . getUrl ( ) . getHost ( ) ; assert host != null ; return asyncDnsClient . resolve4 ( host ) . thenEx ( ( dnsResponse , e ) -> {...
Sends the request to server waits the result timeout and handles result with callback
122,449
public static void clear ( ) { for ( int i = 0 ; i < ByteBufPool . NUMBER_OF_SLABS ; i ++ ) { slabs [ i ] . clear ( ) ; created [ i ] . set ( 0 ) ; reused [ i ] . set ( 0 ) ; } synchronized ( registry ) { registry . clear ( ) ; } }
Clears all of the slabs and stats .
122,450
private void ensureCapacity ( ) { if ( size < selectionKeys . length ) { return ; } SelectionKey [ ] newArray = new SelectionKey [ selectionKeys . length * 2 ] ; System . arraycopy ( selectionKeys , 0 , newArray , 0 , size ) ; selectionKeys = newArray ; }
Multiply the size of array twice
122,451
public static < K , T > StreamSorter < K , T > create ( StreamSorterStorage < T > storage , Function < T , K > keyFunction , Comparator < K > keyComparator , boolean distinct , int itemsInMemorySize ) { return new StreamSorter < > ( storage , keyFunction , keyComparator , distinct , itemsInMemorySize ) ; }
Creates a new instance of StreamSorter
122,452
public static void update ( DMatrixRMaj H , DMatrixRMaj s , DMatrixRMaj y , DMatrixRMaj tempV0 , DMatrixRMaj tempV1 ) { double p = VectorVectorMult_DDRM . innerProd ( y , s ) ; if ( p == 0 ) return ; p = 1.0 / p ; double sBs = VectorVectorMult_DDRM . innerProdA ( s , H , s ) ; if ( sBs == 0 ) return ; CommonOps_DDRM . ...
DFP Hessian update equation . See class description for equations
122,453
public static void inverseUpdate ( DMatrixRMaj H , DMatrixRMaj s , DMatrixRMaj y , DMatrixRMaj tempV0 , DMatrixRMaj tempV1 ) { double alpha = VectorVectorMult_DDRM . innerProdA ( y , H , y ) ; double p = 1.0 / VectorVectorMult_DDRM . innerProd ( s , y ) ; CommonOps_DDRM . mult ( H , y , tempV0 ) ; CommonOps_DDRM . mult...
BFGS inverse hessian update equation that orders the multiplications to minimize the number of operations .
122,454
public static boolean process ( IterativeOptimization search , int maxSteps ) { for ( int i = 0 ; i < maxSteps ; i ++ ) { boolean converged = step ( search ) ; if ( converged ) { return search . isConverged ( ) ; } } return true ; }
Iterate until the line search converges or the maximum number of iterations has been exceeded .
122,455
public static boolean step ( IterativeOptimization search ) { for ( int i = 0 ; i < 10000 ; i ++ ) { boolean converged = search . iterate ( ) ; if ( converged || ! search . isUpdated ( ) ) { return converged ; } } throw new RuntimeException ( "After 10,000 iterations it failed to take a step! Probably a bug." ) ; }
Performs a single step by iterating until the parameters are updated .
122,456
public KdTree . Node requestNode ( ) { if ( unusedNodes . isEmpty ( ) ) return new KdTree . Node ( ) ; return unusedNodes . remove ( unusedNodes . size ( ) - 1 ) ; }
Returns a new node . All object references can be assumed to be null .
122,457
public KdTree . Node requestNode ( P point , int index ) { KdTree . Node n = requestNode ( ) ; n . point = point ; n . index = index ; n . split = - 1 ; return n ; }
Request a leaf node be returned . All data parameters will be automatically assigned appropriate values for a leaf .
122,458
public static Polynomial multiply ( Polynomial a , Polynomial b , Polynomial result ) { int N = Math . max ( 0 , a . size ( ) + b . size ( ) - 1 ) ; if ( result == null ) { result = new Polynomial ( N ) ; } else { if ( result . size < N ) throw new IllegalArgumentException ( "Unexpected length of 'result'" ) ; result ....
Multiplies the two polynomials together .
122,459
public static Polynomial add ( Polynomial a , Polynomial b , Polynomial results ) { int N = Math . max ( a . size , b . size ) ; if ( results == null ) { results = new Polynomial ( N ) ; } else if ( results . size < N ) { throw new IllegalArgumentException ( "storage for results must be at least as large as the the lar...
Adds two polynomials together . The lengths of the polynomials do not need to be the zero but the missing coefficients are assumed to be zero .
122,460
public static PolynomialRoots createRootFinder ( int maxCoefficients , RootFinderType which ) { switch ( which ) { case STURM : FindRealRootsSturm sturm = new FindRealRootsSturm ( maxCoefficients , - 1 , 1e-10 , 200 , 200 ) ; return new WrapRealRootsSturm ( sturm ) ; case EVD : return new RootFinderCompanion ( ) ; defa...
Creates different polynomial root finders .
122,461
public static boolean gradient ( FunctionNtoS func , FunctionNtoN gradient , double param [ ] , double tol ) { return gradient ( func , gradient , param , tol , Math . sqrt ( UtilEjml . EPS ) ) ; }
Compares the passed in gradient function to a numerical calculation . Comparison is done using an absolute value .
122,462
protected boolean bracket ( ) { function . setInput ( stp ) ; if ( mode != 0 ) { fp = function . computeFunction ( ) ; gp = Double . NaN ; } else { mode = 1 ; } if ( fp > valueZero + ftol * stp * derivZero ) { setModeToSection ( stprev , fprev , stp ) ; return false ; } if ( fp >= fprev ) { setModeToSection ( stprev , ...
Searches for an upper bound .
122,463
protected boolean section ( ) { double temp = stp ; stp = interpolate ( pLow + t2 * ( pHi - pLow ) , pHi - t3 * ( pHi - pLow ) ) ; updated = true ; if ( ! Double . isNaN ( gp ) ) { stprev = temp ; fprev = fp ; gprev = gp ; } if ( checkSmallStep ( ) ) { if ( verbose != null ) verbose . println ( "WARNING: Small steps" )...
Using the found bracket for alpha it searches for a better estimate .
122,464
protected boolean checkSmallStep ( ) { double max = Math . max ( stp , stprev ) ; return ( Math . abs ( stp - stprev ) / max < tolStep ) ; }
Checks to see if alpha is changing by a significant amount . If it change is too small it can get stuck in a loop \
122,465
protected double interpolate ( double boundA , double boundB ) { double alphaNew ; if ( Double . isNaN ( gp ) ) { alphaNew = SearchInterpolate . quadratic ( fprev , gprev , stprev , fp , stp ) ; } else { alphaNew = SearchInterpolate . cubic2 ( fprev , gprev , stprev , fp , gp , stp ) ; if ( Double . isNaN ( alphaNew ) ...
Use either quadratic of cubic interpolation to guess the minimum .
122,466
private List < Results > process ( FunctionStoS f , FunctionStoS g , double ... initSteps ) { List < Results > results = new ArrayList < Results > ( ) ; for ( double step : initSteps ) { results . add ( performTest ( f , g , step , 0 , Double . POSITIVE_INFINITY ) ) ; } return results ; }
Processes and compile results for the function at the specified initial steps
122,467
public void sort ( int data [ ] , int begin , int end ) { histogram . fill ( 0 ) ; for ( int i = begin ; i < end ; i ++ ) { histogram . data [ data [ i ] - minValue ] ++ ; } int index = begin ; for ( int i = 0 ; i < histogram . size ; i ++ ) { int N = histogram . get ( i ) ; int value = i + minValue ; for ( int j = 0 ;...
Sorts the data in the array .
122,468
public void sort ( int input [ ] , int startIndex , int output [ ] , int startOutput , int length ) { histogram . fill ( 0 ) ; for ( int i = 0 ; i < length ; i ++ ) { histogram . data [ input [ i + startIndex ] - minValue ] ++ ; } int index = startOutput ; for ( int i = 0 ; i < histogram . size ; i ++ ) { int N = histo...
Sort routine which does not modify the input array . Input and output arrays can be the same instance .
122,469
public void computeDistance ( List < Point2D > obs , double [ ] distance ) { for ( int i = 0 ; i < obs . size ( ) ; i ++ ) { distance [ i ] = computeDistance ( obs . get ( i ) ) ; } }
There are some situations where processing everything as a list can speed things up a lot . This is not one of them .
122,470
public static void sort ( double [ ] data ) { int i = 0 , j ; final int n = data . length ; double a ; try { for ( j = 1 ; ; j ++ ) { a = data [ j ] ; try { for ( i = j ; data [ i - 1 ] > a ; i -- ) { data [ i ] = data [ i - 1 ] ; } } catch ( ArrayIndexOutOfBoundsException e ) { } data [ i ] = a ; } } catch ( ArrayInde...
Sorts data into ascending order
122,471
protected KdTree . Node computeBranch ( List < P > points , GrowQueue_I32 indexes ) { List < P > left = new ArrayList < > ( points . size ( ) / 2 ) ; List < P > right = new ArrayList < > ( points . size ( ) / 2 ) ; GrowQueue_I32 leftIndexes , rightIndexes ; if ( indexes == null ) { leftIndexes = null ; rightIndexes = n...
Given the data inside this particular node select a point for the node and compute the node s children
122,472
protected KdTree . Node computeChild ( List < P > points , GrowQueue_I32 indexes ) { if ( points . size ( ) == 0 ) return null ; if ( points . size ( ) == 1 ) { return createLeaf ( points , indexes ) ; } else { return computeBranch ( points , indexes ) ; } }
Creates a child by checking to see if it is a leaf or branch .
122,473
private KdTree . Node createLeaf ( List < P > points , GrowQueue_I32 indexes ) { int index = indexes == null ? - 1 : indexes . get ( 0 ) ; return memory . requestNode ( points . get ( 0 ) , index ) ; }
Convenient function for creating a leaf node
122,474
public void remove ( int first , int last ) { if ( last < first ) throw new IllegalArgumentException ( "first <= last" ) ; if ( last >= size ) throw new IllegalArgumentException ( "last must be less than the max size" ) ; int delta = last - first + 1 ; for ( int i = last + 1 ; i < size ; i ++ ) { data [ i - delta ] = d...
Removes elements from the list starting at first and ending at last
122,475
public void printHex ( ) { System . out . print ( "[ " ) ; for ( int i = 0 ; i < size ; i ++ ) { System . out . printf ( "0x%02X " , data [ i ] ) ; } System . out . print ( "]" ) ; }
Prints the queue to stdout as a hex array
122,476
public int indexOf ( byte value ) { for ( int i = 0 ; i < size ; i ++ ) { if ( data [ i ] == value ) return i ; } return - 1 ; }
Returns the index of the first element with the specified value . return - 1 if it wasn t found
122,477
public void computeRange ( SortableParameter_F32 input [ ] , int start , int length ) { if ( length == 0 ) { divisor = 0 ; return ; } float min , max ; min = max = input [ start ] . sortValue ; for ( int i = 1 ; i < length ; i ++ ) { float val = input [ start + i ] . sortValue ; if ( val < min ) min = val ; else if ( v...
Examines the list and computes the range from it
122,478
public void sortIndex ( float input [ ] , int start , int length , int indexes [ ] ) { for ( int i = 0 ; i < length ; i ++ ) indexes [ i ] = i ; for ( int i = 0 ; i < histIndexes . size ; i ++ ) { histIndexes . get ( i ) . reset ( ) ; } for ( int i = 0 ; i < length ; i ++ ) { int indexInput = i + start ; int discretize...
Sort routine which does not modify the input array and instead maintains a list of indexes .
122,479
public void sortObject ( SortableParameter_F32 input [ ] , int start , int length ) { for ( int i = 0 ; i < histIndexes . size ; i ++ ) { histObjs [ i ] . reset ( ) ; } for ( int i = 0 ; i < length ; i ++ ) { int indexInput = i + start ; SortableParameter_F32 p = input [ indexInput ] ; int discretized = ( int ) ( ( p ....
Sorts the input list
122,480
protected void searchNode ( P target , KdTree . Node n ) { while ( n != null ) { checkBestDistance ( n , target ) ; if ( n . isLeaf ( ) ) break ; KdTree . Node nearer , further ; double splitValue = distance . valueAt ( ( P ) n . point , n . split ) ; if ( distance . valueAt ( target , n . split ) <= splitValue ) { nea...
Traverse a node down to a leaf . Unexplored branches are added to the priority queue .
122,481
protected void addToQueue ( double closestDistanceSq , KdTree . Node node , P target ) { if ( ! node . isLeaf ( ) ) { Helper h ; if ( unused . isEmpty ( ) ) { h = new Helper ( ) ; } else { h = unused . remove ( unused . size ( ) - 1 ) ; } h . closestPossibleSq = closestDistanceSq ; h . node = node ; queue . add ( h ) ;...
Adds a node to the priority queue .
122,482
protected final double [ ] selectNextSeed ( List < double [ ] > points , double target ) { double sum = 0 ; for ( int i = 0 ; i < distance . size ( ) ; i ++ ) { sum += distance . get ( i ) ; double fraction = sum / totalDistance ; if ( fraction >= target ) return points . get ( i ) ; } throw new RuntimeException ( "Thi...
Randomly selects the next seed . The chance of a seed is based upon its distance from the closest cluster . Larger distances mean more likely .
122,483
protected final void updateDistances ( List < double [ ] > points , double [ ] clusterNew ) { totalDistance = 0 ; for ( int i = 0 ; i < distance . size ( ) ; i ++ ) { double dOld = distance . get ( i ) ; double dNew = StandardKMeans_F64 . distanceSq ( points . get ( i ) , clusterNew ) ; if ( dNew < dOld ) { distance . ...
Updates the list of distances from a point to the closest cluster . Update list of total distances
122,484
public void precomputeAll ( ) { precomputes . resize ( mixtures . size ( ) ) ; for ( int i = 0 ; i < precomputes . size ; i ++ ) { precomputes . get ( i ) . setGaussian ( mixtures . get ( i ) ) ; } }
Precomputes likelihood for all the mixtures
122,485
public static void fillCounting ( int [ ] array , int offset , int length ) { for ( int i = 0 ; i < length ; i ++ ) { array [ i + offset ] = i ; } }
Sets each element within range to a number counting up
122,486
public static void shuffle ( byte [ ] array , int offset , int length , Random rand ) { for ( int i = 0 ; i < length ; i ++ ) { int src = rand . nextInt ( length - i ) ; byte tmp = array [ offset + src + i ] ; array [ offset + src + i ] = array [ offset + i ] ; array [ offset + i ] = tmp ; } }
Randomly shuffle the array
122,487
public LineSearchMore94 setConvergence ( double ftol , double gtol , double xtol ) { if ( ftol < 0 ) throw new IllegalArgumentException ( "ftol must be >= 0 " ) ; if ( gtol < 0 ) throw new IllegalArgumentException ( "gtol must be >= 0 " ) ; if ( xtol < 0 ) throw new IllegalArgumentException ( "xtol must be >= 0 " ) ; t...
Configures the line search .
122,488
private void dcstep ( ) { double sgnd = gp * Math . signum ( gx ) ; double stpf ; if ( fp > fx ) { stpf = handleCase1 ( ) ; } else if ( sgnd < 0 ) { stpf = handleCase2 ( ) ; } else if ( Math . abs ( gp ) < Math . abs ( gx ) ) { stpf = handleCase3 ( ) ; } else { stpf = handleCase4 ( ) ; } if ( fp > fx ) { sty = stp ; fy...
Computes the new step and updates fx fy gx dy .
122,489
private double handleCase1 ( ) { double stpc = SearchInterpolate . cubic2 ( fx , gx , stx , fp , gp , stp ) ; double stpq = SearchInterpolate . quadratic ( fx , gx , stx , fp , stp ) ; bracket = true ; if ( Math . abs ( stpc - stx ) < Math . abs ( stpq - stx ) ) { return stpc ; } else { return stpc + ( stpq - stpc ) / ...
stp has a higher value than stx . The minimum must be between these two values . Pick a point which is close to stx since it has a lower value .
122,490
private double handleCase2 ( ) { double stpc = SearchInterpolate . cubic2 ( fp , gp , stp , fx , gx , stx ) ; double stpq = SearchInterpolate . quadratic2 ( gp , stp , gx , stx ) ; bracket = true ; if ( Math . abs ( stpc - stp ) > Math . abs ( stpq - stp ) ) { return stpc ; } else { return stpq ; } }
The sign of the derivative has swapped indicating that the function is on the other side of the dip and that a bracket has been found .
122,491
private double handleCase3 ( ) { double stpf ; double stpc = SearchInterpolate . cubicSafe ( fp , gp , stp , fx , gx , stx , stmin , stmax ) ; double stpq = SearchInterpolate . quadratic2 ( gp , stp , gx , stx ) ; if ( bracket ) { if ( Math . abs ( stpc - stp ) < Math . abs ( stpq - stp ) ) { stpf = stpc ; } else { stp...
The derivative at stp has a smaller magnitude than at stx and is likely to be closer to the minimum . However there are special cases that need to be dealt with here .
122,492
private double handleCase4 ( ) { if ( bracket ) { return SearchInterpolate . cubic2 ( fp , gp , stp , fy , gy , sty ) ; } else if ( stp > stx ) { return stmax ; } else { return stmin ; } }
Lower function value . On the same side of the dip because the gradients have the same sign . The magnitude of the derivative did not decrease .
122,493
private void computeAxisVariance ( List < P > points ) { int numPoints = points . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { mean [ i ] = 0 ; var [ i ] = 0 ; } for ( int i = 0 ; i < numPoints ; i ++ ) { P p = points . get ( i ) ; for ( int j = 0 ; j < N ; j ++ ) { mean [ j ] += distance . valueAt ( p , j ) ; } } for...
Select the maximum variance as the split
122,494
private void quickSelect ( List < P > points , int splitAxis , int medianNum ) { int numPoints = points . size ( ) ; if ( tmp . length < numPoints ) { tmp = new double [ numPoints ] ; indexes = new int [ numPoints ] ; } for ( int i = 0 ; i < numPoints ; i ++ ) { tmp [ i ] = distance . valueAt ( points . get ( i ) , spl...
Uses quick - select to find the median value
122,495
public void init ( List < T > list , int bucketSize ) { if ( list . size ( ) < bucketSize ) { throw new RuntimeException ( "There needs to be more than or equal to elements in the 'list' that there are in the bucket" ) ; } this . k = bucketSize ; this . c = bucketSize - 1 ; N = list . size ( ) ; bins = new int [ bucket...
Initialize with a new list and bucket size
122,496
public boolean next ( ) { if ( state == 2 ) return false ; else state = 1 ; bins [ c ] ++ ; if ( bins [ c ] >= N ) { boolean allgood = false ; for ( int i = c - 1 ; i >= 0 ; i -- ) { bins [ i ] ++ ; if ( bins [ i ] <= ( N - ( k - i ) ) ) { allgood = true ; for ( int j = i + 1 ; j < k ; j ++ ) { bins [ j ] = bins [ j - ...
This will shuffle the elements in and out of the bins . When all combinations have been exhausted an ExhaustedException will be thrown .
122,497
public List < T > getBucket ( List < T > storage ) { if ( storage == null ) storage = new ArrayList < T > ( ) ; else storage . clear ( ) ; for ( int i = 0 ; i < bins . length ; i ++ ) { storage . add ( a . get ( bins [ i ] ) ) ; } return storage ; }
Extracts the entire bucket . Will add elements to the provided list or create a new one
122,498
public List < T > getOutside ( List < T > storage ) { if ( storage == null ) { storage = new ArrayList < T > ( ) ; } else { storage . clear ( ) ; } storage . addAll ( a ) ; for ( int i = bins . length - 1 ; i >= 0 ; i -- ) { storage . remove ( bins [ i ] ) ; } return storage ; }
This returns all the items that are not currently inside the bucket
122,499
public void prune ( ) { Iterator < PointIndex < Point > > iter = allPoints . iterator ( ) ; int index = 0 ; while ( iter . hasNext ( ) ) { iter . next ( ) ; if ( origErrors [ index ++ ] >= pruneVal ) { iter . remove ( ) ; } } }
Removes all samples which have an error larger than the specified percentile error .