idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
22,400 | public static byte schemaToColumnType ( Schema s ) { Schema . Type typ = s . getType ( ) ; switch ( typ ) { case BOOLEAN : case INT : case LONG : case FLOAT : case DOUBLE : return Vec . T_NUM ; case ENUM : return Vec . T_CAT ; case STRING : return Vec . T_STR ; case NULL : return Vec . T_BAD ; case BYTES : return Vec . T_STR ; case UNION : List < Schema > unionSchemas = s . getTypes ( ) ; if ( unionSchemas . size ( ) == 1 ) { return schemaToColumnType ( unionSchemas . get ( 0 ) ) ; } else if ( unionSchemas . size ( ) == 2 ) { Schema s1 = unionSchemas . get ( 0 ) ; Schema s2 = unionSchemas . get ( 1 ) ; if ( s1 . getType ( ) . equals ( Schema . Type . NULL ) ) return schemaToColumnType ( s2 ) ; else if ( s2 . getType ( ) . equals ( Schema . Type . NULL ) ) return schemaToColumnType ( s1 ) ; } default : throw new IllegalArgumentException ( "Unsupported Avro schema type: " + s ) ; } } | Transform Avro schema into H2O type . |
22,401 | public static Schema . Field [ ] flatSchema ( Schema s ) { List < Schema . Field > fields = s . getFields ( ) ; Schema . Field [ ] flatSchema = new Schema . Field [ fields . size ( ) ] ; int cnt = 0 ; for ( Schema . Field f : fields ) { if ( isSupportedSchema ( f . schema ( ) ) ) { flatSchema [ cnt ] = f ; cnt ++ ; } } return cnt != flatSchema . length ? Arrays . copyOf ( flatSchema , cnt ) : flatSchema ; } | The method flattenize the given Avro schema . |
22,402 | static public Key [ ] exit ( Key ... keep ) { List < Key > keylist = new ArrayList < > ( ) ; if ( keep != null ) for ( Key k : keep ) if ( k != null ) keylist . add ( k ) ; Object [ ] arrkeep = keylist . toArray ( ) ; Arrays . sort ( arrkeep ) ; Stack < HashSet < Key > > keys = _scope . get ( ) . _keys ; if ( keys . size ( ) > 0 ) { Futures fs = new Futures ( ) ; for ( Key key : keys . pop ( ) ) { int found = Arrays . binarySearch ( arrkeep , key ) ; if ( ( arrkeep . length == 0 || found < 0 ) && key != null ) Keyed . remove ( key , fs ) ; } fs . blockForPending ( ) ; } return keep ; } | Exit the inner - most Scope remove all Keys created since the matching enter call except for the listed Keys . |
22,403 | public static InputStream getResource2 ( String uri ) { try { for ( File f : RESOURCE_FILES ) { File f2 = new File ( f , uri ) ; if ( f2 . exists ( ) ) return new FileInputStream ( f2 ) ; } ClassLoader cl = ClassLoader . getSystemClassLoader ( ) ; InputStream is = loadResource ( uri , cl ) ; if ( is == null && ( cl = Thread . currentThread ( ) . getContextClassLoader ( ) ) != null ) { is = loadResource ( uri , cl ) ; } if ( is == null && ( cl = JarHash . class . getClassLoader ( ) ) != null ) { is = loadResource ( uri , cl ) ; } if ( is != null ) return is ; } catch ( FileNotFoundException ignore ) { } Log . warn ( "Resource not found: " + uri ) ; return null ; } | from a possible local dev build . |
22,404 | private static void checkPermission ( ) { SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) security . checkPermission ( modifyThreadPermission ) ; } | If there is a security manager makes sure caller has permission to modify threads . |
22,405 | private void addWorker ( ) { Throwable ex = null ; ForkJoinWorkerThread wt = null ; try { if ( ( wt = factory . newThread ( this ) ) != null ) { wt . start ( ) ; return ; } } catch ( Throwable e ) { ex = e ; } deregisterWorker ( wt , ex ) ; } | Tries to create and start a worker |
22,406 | final void registerWorker ( WorkQueue w ) { Mutex lock = this . lock ; lock . lock ( ) ; try { WorkQueue [ ] ws = workQueues ; if ( w != null && ws != null ) { int rs , n = ws . length , m = n - 1 ; int s = nextSeed += SEED_INCREMENT ; w . seed = ( s == 0 ) ? 1 : s ; int r = ( s << 1 ) | 1 ; if ( ws [ r &= m ] != null ) { int probes = 0 ; int step = ( n <= 4 ) ? 2 : ( ( n >>> 1 ) & SQMASK ) + 2 ; while ( ws [ r = ( r + step ) & m ] != null ) { if ( ++ probes >= n ) { workQueues = ws = Arrays . copyOf ( ws , n <<= 1 ) ; m = n - 1 ; probes = 0 ; } } } w . eventCount = w . poolIndex = r ; ws [ r ] = w ; runState = ( ( rs = runState ) & SHUTDOWN ) | ( ( rs + 2 ) & ~ SHUTDOWN ) ; } } finally { lock . unlock ( ) ; } } | Callback from ForkJoinWorkerThread constructor to establish its poolIndex and record its WorkQueue . To avoid scanning bias due to packing entries in front of the workQueues array we treat the array as a simple power - of - two hash table using per - thread seed as hash expanding as needed . |
22,407 | final void deregisterWorker ( ForkJoinWorkerThread wt , Throwable ex ) { Mutex lock = this . lock ; WorkQueue w = null ; if ( wt != null && ( w = wt . workQueue ) != null ) { w . runState = - 1 ; stealCount . getAndAdd ( w . totalSteals + w . nsteals ) ; int idx = w . poolIndex ; lock . lock ( ) ; try { WorkQueue [ ] ws = workQueues ; if ( ws != null && idx >= 0 && idx < ws . length && ws [ idx ] == w ) ws [ idx ] = null ; } finally { lock . unlock ( ) ; } } long c ; do { } while ( ! U . compareAndSwapLong ( this , CTL , c = ctl , ( ( ( c - AC_UNIT ) & AC_MASK ) | ( ( c - TC_UNIT ) & TC_MASK ) | ( c & ~ ( AC_MASK | TC_MASK ) ) ) ) ) ; if ( ! tryTerminate ( false , false ) && w != null ) { w . cancelAll ( ) ; if ( w . array != null ) signalWork ( ) ; if ( ex == null ) ForkJoinTask . helpExpungeStaleExceptions ( ) ; } if ( ex != null ) U . throwException ( ex ) ; } | Final callback from terminating worker as well as upon failure to construct or start a worker in addWorker . Removes record of worker from array and adjusts counts . If pool is shutting down tries to complete termination . |
22,408 | final void signalWork ( ) { long c ; int u ; while ( ( u = ( int ) ( ( c = ctl ) >>> 32 ) ) < 0 ) { WorkQueue [ ] ws = workQueues ; int e , i ; WorkQueue w ; Thread p ; if ( ( e = ( int ) c ) > 0 ) { if ( ws != null && ( i = e & SMASK ) < ws . length && ( w = ws [ i ] ) != null && w . eventCount == ( e | INT_SIGN ) ) { long nc = ( ( ( long ) ( w . nextWait & E_MASK ) ) | ( ( long ) ( u + UAC_UNIT ) << 32 ) ) ; if ( U . compareAndSwapLong ( this , CTL , c , nc ) ) { w . eventCount = ( e + E_SEQ ) & E_MASK ; if ( ( p = w . parker ) != null ) U . unpark ( p ) ; break ; } } else break ; } else if ( e == 0 && ( u & SHORT_SIGN ) != 0 ) { long nc = ( long ) ( ( ( u + UTC_UNIT ) & UTC_MASK ) | ( ( u + UAC_UNIT ) & UAC_MASK ) ) << 32 ; if ( U . compareAndSwapLong ( this , CTL , c , nc ) ) { addWorker ( ) ; break ; } } else break ; } } | Tries to activate or create a worker if too few are active . |
22,409 | private void idleAwaitWork ( WorkQueue w , long currentCtl , long prevCtl ) { if ( w . eventCount < 0 && ! tryTerminate ( false , false ) && ( int ) prevCtl != 0 && ! hasQueuedSubmissions ( ) && ctl == currentCtl ) { Thread wt = Thread . currentThread ( ) ; Thread . yield ( ) ; while ( ctl == currentCtl ) { long startTime = System . nanoTime ( ) ; Thread . interrupted ( ) ; U . putObject ( wt , PARKBLOCKER , this ) ; w . parker = wt ; if ( ctl == currentCtl ) U . park ( false , SHRINK_RATE ) ; w . parker = null ; U . putObject ( wt , PARKBLOCKER , null ) ; if ( ctl != currentCtl ) break ; if ( System . nanoTime ( ) - startTime >= SHRINK_TIMEOUT && U . compareAndSwapLong ( this , CTL , currentCtl , prevCtl ) ) { w . eventCount = ( w . eventCount + E_SEQ ) | E_MASK ; w . runState = - 1 ; break ; } } } } | If inactivating worker w has caused the pool to become quiescent checks for pool termination and so long as this is not the only worker waits for event for up to SHRINK_RATE nanosecs . On timeout if ctl has not changed terminates the worker which will in turn wake up another worker to possibly repeat this process . |
22,410 | private void tryPollForAndExec ( WorkQueue joiner , ForkJoinTask < ? > task ) { WorkQueue [ ] ws ; if ( ( ws = workQueues ) != null ) { for ( int j = 1 ; j < ws . length && task . status >= 0 ; j += 2 ) { WorkQueue q = ws [ j ] ; if ( q != null && q . pollFor ( task ) ) { joiner . runSubtask ( task ) ; break ; } } } } | If task is at base of some steal queue steals and executes it . |
22,411 | public < T > ForkJoinTask < T > submit ( ForkJoinTask < T > task ) { if ( task == null ) throw new NullPointerException ( ) ; doSubmit ( task ) ; return task ; } | Submits a ForkJoinTask for execution . |
22,412 | public int getRunningThreadCount ( ) { int rc = 0 ; WorkQueue [ ] ws ; WorkQueue w ; if ( ( ws = workQueues ) != null ) { for ( int i = 1 ; i < ws . length ; i += 2 ) { if ( ( w = ws [ i ] ) != null && w . isApparentlyUnblocked ( ) ) ++ rc ; } } return rc ; } | Returns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization . This method may overestimate the number of running threads . |
22,413 | public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { long nanos = unit . toNanos ( timeout ) ; final Mutex lock = this . lock ; lock . lock ( ) ; try { for ( ; ; ) { if ( isTerminated ( ) ) return true ; if ( nanos <= 0 ) return false ; nanos = termination . awaitNanos ( nanos ) ; } } finally { lock . unlock ( ) ; } } | Blocks until all tasks have completed execution after a shutdown request or the timeout occurs or the current thread is interrupted whichever happens first . |
22,414 | protected < T > RunnableFuture < T > newTaskFor ( Runnable runnable , T value ) { return new ForkJoinTask . AdaptedRunnable < T > ( runnable , value ) ; } | implement RunnableFuture . |
22,415 | public Frame applyTargetEncoding ( Frame data , String targetColumnName , Map < String , Frame > targetEncodingMap , byte dataLeakageHandlingStrategy , String foldColumn , boolean withBlendedAvg , boolean imputeNAs , long seed ) { double defaultNoiseLevel = 0.01 ; int targetIndex = data . find ( targetColumnName ) ; Vec targetVec = data . vec ( targetIndex ) ; double noiseLevel = targetVec . isNumeric ( ) ? defaultNoiseLevel * ( targetVec . max ( ) - targetVec . min ( ) ) : defaultNoiseLevel ; return applyTargetEncoding ( data , targetColumnName , targetEncodingMap , dataLeakageHandlingStrategy , foldColumn , withBlendedAvg , noiseLevel , true , seed ) ; } | Overloaded for the case when user had not specified the noise parameter |
22,416 | private void extendPath ( PathPointer unique_path , int unique_depth , float zero_fraction , float one_fraction , int feature_index ) { unique_path . get ( unique_depth ) . feature_index = feature_index ; unique_path . get ( unique_depth ) . zero_fraction = zero_fraction ; unique_path . get ( unique_depth ) . one_fraction = one_fraction ; unique_path . get ( unique_depth ) . pweight = ( unique_depth == 0 ? 1.0f : 0.0f ) ; for ( int i = unique_depth - 1 ; i >= 0 ; i -- ) { unique_path . get ( i + 1 ) . pweight += one_fraction * unique_path . get ( i ) . pweight * ( i + 1 ) / ( float ) ( unique_depth + 1 ) ; unique_path . get ( i ) . pweight = zero_fraction * unique_path . get ( i ) . pweight * ( unique_depth - i ) / ( float ) ( unique_depth + 1 ) ; } } | extend our decision path with a fraction of one and zero extensions |
22,417 | private void unwindPath ( PathPointer unique_path , int unique_depth , int path_index ) { final float one_fraction = unique_path . get ( path_index ) . one_fraction ; final float zero_fraction = unique_path . get ( path_index ) . zero_fraction ; float next_one_portion = unique_path . get ( unique_depth ) . pweight ; for ( int i = unique_depth - 1 ; i >= 0 ; -- i ) { if ( one_fraction != 0 ) { final float tmp = unique_path . get ( i ) . pweight ; unique_path . get ( i ) . pweight = next_one_portion * ( unique_depth + 1 ) / ( ( i + 1 ) * one_fraction ) ; next_one_portion = tmp - unique_path . get ( i ) . pweight * zero_fraction * ( unique_depth - i ) / ( float ) ( unique_depth + 1 ) ; } else { unique_path . get ( i ) . pweight = ( unique_path . get ( i ) . pweight * ( unique_depth + 1 ) ) / ( zero_fraction * ( unique_depth - i ) ) ; } } for ( int i = path_index ; i < unique_depth ; ++ i ) { unique_path . get ( i ) . feature_index = unique_path . get ( i + 1 ) . feature_index ; unique_path . get ( i ) . zero_fraction = unique_path . get ( i + 1 ) . zero_fraction ; unique_path . get ( i ) . one_fraction = unique_path . get ( i + 1 ) . one_fraction ; } } | undo a previous extension of the decision path |
22,418 | private float unwoundPathSum ( final PathPointer unique_path , int unique_depth , int path_index ) { final float one_fraction = unique_path . get ( path_index ) . one_fraction ; final float zero_fraction = unique_path . get ( path_index ) . zero_fraction ; float next_one_portion = unique_path . get ( unique_depth ) . pweight ; float total = 0 ; for ( int i = unique_depth - 1 ; i >= 0 ; -- i ) { if ( one_fraction != 0 ) { final float tmp = next_one_portion * ( unique_depth + 1 ) / ( ( i + 1 ) * one_fraction ) ; total += tmp ; next_one_portion = unique_path . get ( i ) . pweight - tmp * zero_fraction * ( ( unique_depth - i ) / ( float ) ( unique_depth + 1 ) ) ; } else if ( zero_fraction != 0 ) { total += ( unique_path . get ( i ) . pweight / zero_fraction ) / ( ( unique_depth - i ) / ( float ) ( unique_depth + 1 ) ) ; } else { if ( unique_path . get ( i ) . pweight != 0 ) throw new IllegalStateException ( "Unique path " + i + " must have zero getWeight" ) ; } } return total ; } | we unwound a previous extension in the decision path |
22,419 | private void treeShap ( R feat , float [ ] phi , N node , S nodeStat , int unique_depth , PathPointer parent_unique_path , float parent_zero_fraction , float parent_one_fraction , int parent_feature_index , int condition , int condition_feature , float condition_fraction ) { if ( condition_fraction == 0 ) return ; PathPointer unique_path = parent_unique_path . move ( unique_depth ) ; if ( condition == 0 || condition_feature != parent_feature_index ) { extendPath ( unique_path , unique_depth , parent_zero_fraction , parent_one_fraction , parent_feature_index ) ; } final int split_index = node . getSplitIndex ( ) ; if ( node . isLeaf ( ) ) { for ( int i = 1 ; i <= unique_depth ; ++ i ) { final float w = unwoundPathSum ( unique_path , unique_depth , i ) ; final PathElement el = unique_path . get ( i ) ; phi [ el . feature_index ] += w * ( el . one_fraction - el . zero_fraction ) * node . getLeafValue ( ) * condition_fraction ; } } else { final int hot_index = node . next ( feat ) ; final int cold_index = hot_index == node . getLeftChildIndex ( ) ? node . getRightChildIndex ( ) : node . getLeftChildIndex ( ) ; final float w = nodeStat . getWeight ( ) ; final float hot_zero_fraction = stats [ hot_index ] . getWeight ( ) / w ; final float cold_zero_fraction = stats [ cold_index ] . getWeight ( ) / w ; float incoming_zero_fraction = 1 ; float incoming_one_fraction = 1 ; int path_index = 0 ; for ( ; path_index <= unique_depth ; ++ path_index ) { if ( unique_path . get ( path_index ) . feature_index == split_index ) break ; } if ( path_index != unique_depth + 1 ) { incoming_zero_fraction = unique_path . get ( path_index ) . zero_fraction ; incoming_one_fraction = unique_path . get ( path_index ) . one_fraction ; unwindPath ( unique_path , unique_depth , path_index ) ; unique_depth -= 1 ; } float hot_condition_fraction = condition_fraction ; float cold_condition_fraction = condition_fraction ; if ( condition > 0 && split_index == condition_feature ) { cold_condition_fraction = 0 ; unique_depth -= 1 ; } else if ( condition < 0 && split_index == condition_feature ) { hot_condition_fraction *= hot_zero_fraction ; cold_condition_fraction *= cold_zero_fraction ; unique_depth -= 1 ; } treeShap ( feat , phi , nodes [ hot_index ] , stats [ hot_index ] , unique_depth + 1 , unique_path , hot_zero_fraction * incoming_zero_fraction , incoming_one_fraction , split_index , condition , condition_feature , hot_condition_fraction ) ; treeShap ( feat , phi , nodes [ cold_index ] , stats [ cold_index ] , unique_depth + 1 , unique_path , cold_zero_fraction * incoming_zero_fraction , 0 , split_index , condition , condition_feature , cold_condition_fraction ) ; } } | recursive computation of SHAP values for a decision tree |
22,420 | void processEvent ( Event e ) { assert ! _processed ; if ( e . isSend ( ) ) { _sends . put ( e , new ArrayList < TimelineSnapshot . Event > ( ) ) ; for ( Event otherE : _events ) { if ( ( otherE != null ) && ( otherE != e ) && ( ! otherE . equals ( e ) ) && otherE . _blocked && otherE . match ( e ) ) { _edges . put ( otherE , e ) ; _sends . get ( e ) . add ( otherE ) ; otherE . _blocked = false ; } } } else { assert ! _edges . containsKey ( e ) ; int senderIdx = e . packH2O ( ) . index ( ) ; if ( senderIdx < 0 ) { Log . warn ( "no sender found! port = " + e . portPack ( ) + ", ip = " + e . addrPack ( ) . toString ( ) ) ; return ; } Event senderCnd = _events [ senderIdx ] ; if ( senderCnd != null ) { if ( isSenderRecvPair ( senderCnd , e ) ) { _edges . put ( e , senderCnd . clone ( ) ) ; _sends . get ( senderCnd ) . add ( e ) ; return ; } senderCnd = senderCnd . clone ( ) ; while ( senderCnd . prev ( ) ) { if ( isSenderRecvPair ( senderCnd , e ) ) { _edges . put ( e , senderCnd ) ; _sends . get ( senderCnd ) . add ( e ) ; return ; } } } e . _blocked = true ; } assert ( e == null ) || ( e . _eventIdx < TimeLine . MAX_EVENTS ) ; } | Process new event . For sender check if there are any blocked receives waiting for this send . For receiver try to find matching sender otherwise block . |
22,421 | public boolean hasNext ( ) { for ( int i = 0 ; i < _events . length ; ++ i ) if ( _events [ i ] != null && ( ! _events [ i ] . isEmpty ( ) || _events [ i ] . next ( ) ) ) { assert ( _events [ i ] == null ) || ( ( _events [ i ] . _eventIdx < TimeLine . MAX_EVENTS ) && ! _events [ i ] . isEmpty ( ) ) ; return true ; } else { assert ( _events [ i ] == null ) || ( ( _events [ i ] . _eventIdx < TimeLine . MAX_EVENTS ) && ! _events [ i ] . isEmpty ( ) ) ; _events [ i ] = null ; } return false ; } | Just check if there is any non null non - issued event . |
22,422 | public final Result solve ( GradientSolver gslvr , double [ ] coefs ) { return solve ( gslvr , coefs , gslvr . getGradient ( coefs ) , new ProgressMonitor ( ) { public boolean progress ( double [ ] beta , GradientInfo ginfo ) { return true ; } } ) ; } | Solve the optimization problem defined by the user - supplied ginfo function using L - BFGS algorithm . |
22,423 | public < V extends Val > V returning ( V val ) { if ( val instanceof ValFrame ) _ses . addRefCnt ( val . getFrame ( ) , 1 ) ; return val ; } | shared in the returning output Frame . |
22,424 | ValFrame addGlobals ( Frame fr ) { _ses . addGlobals ( fr ) ; return new ValFrame ( new Frame ( fr . _names . clone ( ) , fr . vecs ( ) . clone ( ) ) ) ; } | frame - so we can hack it without changing the global frame view . |
22,425 | double [ ] [ ] computeStatsFillModel ( LloydsIterationTask task , KMeansModel model , final Vec [ ] vecs , final double [ ] means , final double [ ] mults , final int [ ] modes , int k ) { if ( model . _parms . _standardize ) { model . _output . _centers_std_raw = task . _cMeans ; } model . _output . _centers_raw = destandardize ( task . _cMeans , _isCats , means , mults ) ; model . _output . _size = task . _size ; model . _output . _withinss = task . _cSqr ; double ssq = 0 ; for ( int i = 0 ; i < k ; i ++ ) ssq += model . _output . _withinss [ i ] ; model . _output . _tot_withinss = ssq ; if ( k == 1 ) { model . _output . _totss = model . _output . _tot_withinss ; } else { TotSS totss = new TotSS ( means , mults , modes , train ( ) . domains ( ) , train ( ) . cardinality ( ) ) . doAll ( vecs ) ; model . _output . _totss = totss . _tss ; } model . _output . _betweenss = model . _output . _totss - model . _output . _tot_withinss ; model . _output . _iterations ++ ; model . _output . _history_withinss = ArrayUtils . copyAndFillOf ( model . _output . _history_withinss , model . _output . _history_withinss . length + 1 , model . _output . _tot_withinss ) ; model . _output . _k = ArrayUtils . copyAndFillOf ( model . _output . _k , model . _output . _k . length + 1 , k ) ; model . _output . _training_time_ms = ArrayUtils . copyAndFillOf ( model . _output . _training_time_ms , model . _output . _training_time_ms . length + 1 , System . currentTimeMillis ( ) ) ; model . _output . _reassigned_count = ArrayUtils . copyAndFillOf ( model . _output . _reassigned_count , model . _output . _reassigned_count . length + 1 , task . _reassigned_count ) ; model . _output . _model_summary = createModelSummaryTable ( model . _output ) ; model . _output . _scoring_history = createScoringHistoryTable ( model . _output ) ; model . _output . _training_metrics = makeTrainingMetrics ( model ) ; return task . _cMeans ; } | etc ) . Return new centers . |
22,426 | void storePersist ( ) throws java . io . IOException { if ( isDeleted ( ) ) return ; if ( isPersisted ( ) ) return ; H2O . getPM ( ) . store ( backend ( ) , this ) ; assert ! isPersisted ( ) ; setDsk ( ) ; if ( isDeleted ( ) ) H2O . getPM ( ) . delete ( backend ( ) , this ) ; } | Best - effort store complete Values to disk . |
22,427 | byte [ ] loadPersist ( ) { assert isPersisted ( ) ; try { byte [ ] res = H2O . getPM ( ) . load ( backend ( ) , this ) ; assert ! isDeleted ( ) ; return res ; } catch ( IOException ioe ) { throw Log . throwErr ( ioe ) ; } } | Load some or all of completely persisted Values |
22,428 | public static String nameOfPersist ( int x ) { switch ( x ) { case ICE : return "ICE" ; case HDFS : return "HDFS" ; case S3 : return "S3" ; case NFS : return "NFS" ; case TCP : return "TCP" ; case GCS : return "GCS" ; default : return null ; } } | One of ICE HDFS S3 GCS NFS or TCP according to where this Value is persisted . |
22,429 | private byte [ ] replicas ( ) { byte [ ] r = _replicas ; if ( r != null ) return r ; byte [ ] nr = new byte [ H2O . CLOUD . size ( ) + 1 + 10 ] ; if ( REPLICAS_UPDATER . compareAndSet ( this , null , nr ) ) return nr ; r = _replicas ; assert r != null ; return r ; } | Fills in the _replicas field atomically on first set of a replica . |
22,430 | boolean read_lock ( ) { while ( true ) { int old = _rwlock . get ( ) ; if ( old == - 1 ) return false ; assert old >= 0 ; if ( RW_CAS ( old , old + 1 , "rlock+" ) ) return true ; } } | Bump the read lock once per pending - GET or pending - Invalidate |
22,431 | public static Value STORE_get ( Key key ) { Value val = H2O . STORE . get ( key ) ; if ( val == null ) return null ; if ( ! val . isNull ( ) ) return val ; if ( val . _rwlock . get ( ) == 0 ) H2O . putIfMatch ( key , null , val ) ; return null ; } | Return the not - Null value or the true null . |
22,432 | public boolean isReleasable ( ) { int r = _rwlock . get ( ) ; if ( _key . home ( ) ) { return r <= 0 ; } else { assert r == 2 || r == - 1 ; return r == - 1 ; } } | Return true if blocking is unnecessary . Alas used in TWO places and the blocking API forces them to share here . |
22,433 | static public ModelMetricsRegression make ( Vec predicted , Vec actual , DistributionFamily family ) { if ( predicted == null || actual == null ) throw new IllegalArgumentException ( "Missing actual or predicted targets for regression metrics!" ) ; if ( ! predicted . isNumeric ( ) ) throw new IllegalArgumentException ( "Predicted values must be numeric for regression metrics." ) ; if ( ! actual . isNumeric ( ) ) throw new IllegalArgumentException ( "Actual values must be numeric for regression metrics." ) ; if ( family == DistributionFamily . quantile || family == DistributionFamily . tweedie || family == DistributionFamily . huber ) throw new IllegalArgumentException ( "Unsupported distribution family, requires additional parameters which cannot be specified right now." ) ; Frame predsActual = new Frame ( predicted ) ; predsActual . add ( "actual" , actual ) ; MetricBuilderRegression mb = new RegressionMetrics ( family ) . doAll ( predsActual ) . _mb ; ModelMetricsRegression mm = ( ModelMetricsRegression ) mb . makeModelMetrics ( null , predsActual , null , null ) ; mm . _description = "Computed on user-given predictions and targets, distribution: " + ( family == null ? DistributionFamily . gaussian . toString ( ) : family . toString ( ) ) + "." ; return mm ; } | Build a Regression ModelMetrics object from predicted and actual targets |
22,434 | static Frame toFrame ( Vector v , Key key ) { final int log_rows_per_chunk = Math . max ( 1 , FileVec . DFLT_LOG2_CHUNK_SIZE - ( int ) Math . floor ( Math . log ( 1 ) / Math . log ( 2. ) ) ) ; Vec vv = makeCon ( 0 , v . size ( ) , log_rows_per_chunk , false ) ; Frame f = new Frame ( key , new Vec [ ] { vv } , true ) ; try ( Vec . Writer vw = f . vecs ( ) [ 0 ] . open ( ) ) { for ( int r = 0 ; r < v . size ( ) ; ++ r ) vw . set ( r , v . get ( r ) ) ; } DKV . put ( key , f ) ; return f ; } | Helper to convert a Vector into a Frame |
22,435 | public void waitUntilAllReceived ( int timeout ) throws ExternalFrameConfirmationException { try { byte flag = ExternalFrameConfirmationCheck . getConfirmation ( ab , timeout ) ; assert ( flag == ExternalFrameHandler . CONFIRM_READING_DONE ) ; } catch ( TimeoutException ex ) { throw new ExternalFrameConfirmationException ( "Timeout for confirmation exceeded!" ) ; } catch ( InterruptedException e ) { throw new ExternalFrameConfirmationException ( "Confirmation thread interrupted!" ) ; } catch ( ExecutionException e ) { throw new ExternalFrameConfirmationException ( "Confirmation failed!" ) ; } } | This method ensures the application waits for all bytes to be received before continuing in the application s control flow . |
22,436 | @ SuppressWarnings ( "unused" ) public MetadataV3 listRoutes ( int version , MetadataV3 docs ) { MarkdownBuilder builder = new MarkdownBuilder ( ) ; builder . comment ( "Preview with http://jbt.github.io/markdown-editor" ) ; builder . heading1 ( "REST API Routes Table of Contents" ) ; builder . hline ( ) ; builder . tableHeader ( "HTTP method" , "URI pattern" , "Input schema" , "Output schema" , "Summary" ) ; docs . routes = new RouteV3 [ RequestServer . numRoutes ( ) ] ; int i = 0 ; for ( Route route : RequestServer . routes ( ) ) { RouteV3 schema = new RouteV3 ( route ) ; docs . routes [ i ] = schema ; MetadataV3 look = new MetadataV3 ( ) ; look . routes = new RouteV3 [ 1 ] ; look . routes [ 0 ] = schema ; look . path = route . _url ; look . http_method = route . _http_method ; fetchRoute ( version , look ) ; schema . input_schema = look . routes [ 0 ] . input_schema ; schema . output_schema = look . routes [ 0 ] . output_schema ; builder . tableRow ( route . _http_method , route . _url , Handler . getHandlerMethodInputSchema ( route . _handler_method ) . getSimpleName ( ) , Handler . getHandlerMethodOutputSchema ( route . _handler_method ) . getSimpleName ( ) , route . _summary ) ; i ++ ; } docs . markdown = builder . toString ( ) ; return docs ; } | Return a list of all REST API Routes and a Markdown Table of Contents . |
22,437 | public MetadataV3 fetchRoute ( int version , MetadataV3 docs ) { Route route = null ; if ( docs . path != null && docs . http_method != null ) { try { route = RequestServer . lookupRoute ( new RequestUri ( docs . http_method , docs . path ) ) ; } catch ( MalformedURLException e ) { route = null ; } } else { if ( docs . path != null ) try { docs . num = Integer . parseInt ( docs . path ) ; } catch ( NumberFormatException e ) { } if ( docs . num >= 0 && docs . num < RequestServer . numRoutes ( ) ) route = RequestServer . routes ( ) . get ( docs . num ) ; docs . routes = new RouteV3 [ ] { new RouteV3 ( route ) } ; } if ( route == null ) return null ; Schema sinput , soutput ; if ( route . _handler_class . equals ( water . api . ModelBuilderHandler . class ) || route . _handler_class . equals ( water . api . GridSearchHandler . class ) ) { String ss [ ] = route . _url . split ( "/" ) ; String algoURLName = ss [ 3 ] ; String algoName = ModelBuilder . algoName ( algoURLName ) ; String schemaDir = ModelBuilder . schemaDirectory ( algoURLName ) ; int version2 = Integer . valueOf ( ss [ 1 ] ) ; try { String inputSchemaName = schemaDir + algoName + "V" + version2 ; sinput = ( Schema ) TypeMap . getTheFreezableOrThrow ( TypeMap . onIce ( inputSchemaName ) ) ; } catch ( java . lang . ClassNotFoundException e ) { sinput = ( Schema ) TypeMap . theFreezable ( TypeMap . onIce ( schemaDir + algoName + "V3" ) ) ; } sinput . init_meta ( ) ; soutput = sinput ; } else { sinput = Schema . newInstance ( Handler . getHandlerMethodInputSchema ( route . _handler_method ) ) ; soutput = Schema . newInstance ( Handler . getHandlerMethodOutputSchema ( route . _handler_method ) ) ; } docs . routes [ 0 ] . input_schema = sinput . getClass ( ) . getSimpleName ( ) ; docs . routes [ 0 ] . output_schema = soutput . getClass ( ) . getSimpleName ( ) ; docs . routes [ 0 ] . markdown = route . markdown ( sinput , soutput ) . toString ( ) ; return docs ; } | Also called through reflection by RequestServer |
22,438 | @ SuppressWarnings ( "unused" ) public MetadataV3 listSchemas ( int version , MetadataV3 docs ) { Map < String , Class < ? extends Schema > > ss = SchemaServer . schemas ( ) ; docs . schemas = new SchemaMetadataV3 [ ss . size ( ) ] ; int i = 0 ; for ( Class < ? extends Schema > schema_class : ss . values ( ) ) { Schema schema = Schema . newInstance ( schema_class ) ; try { Iced impl = ( Iced ) schema . getImplClass ( ) . newInstance ( ) ; schema . fillFromImpl ( impl ) ; } catch ( Exception e ) { } docs . schemas [ i ++ ] = new SchemaMetadataV3 ( new SchemaMetadata ( schema ) ) ; } return docs ; } | Fetch the metadata for all the Schemas . |
22,439 | @ SuppressWarnings ( "unused" ) public GridsV99 list ( int version , GridsV99 s ) { final Key [ ] gridKeys = KeySnapshot . globalSnapshot ( ) . filter ( new KeySnapshot . KVFilter ( ) { public boolean filter ( KeySnapshot . KeyInfo k ) { return Value . isSubclassOf ( k . _type , Grid . class ) ; } } ) . keys ( ) ; s . grids = new GridSchemaV99 [ gridKeys . length ] ; for ( int i = 0 ; i < gridKeys . length ; i ++ ) { s . grids [ i ] = new GridSchemaV99 ( ) ; s . grids [ i ] . fillFromImpl ( getFromDKV ( "(none)" , gridKeys [ i ] , Grid . class ) ) ; } return s ; } | Return all the grids . |
22,440 | @ SuppressWarnings ( "unused" ) public GridSchemaV99 fetch ( int version , GridSchemaV99 s ) { return s . fillFromImpl ( getFromDKV ( "grid_id" , s . grid_id . key ( ) , Grid . class ) ) ; } | Return a specified grid . |
22,441 | public final float getLeafValue ( FVec feat , int root_id ) { int pid = root_id ; int pos = pid * NODE_SIZE + 4 ; int cleft_ = UnsafeUtils . get4 ( _nodes , pos ) ; while ( cleft_ != - 1 ) { final int sindex_ = UnsafeUtils . get4 ( _nodes , pos + 8 ) ; final float fvalue = feat . fvalue ( ( int ) ( sindex_ & ( ( 1L << 31 ) - 1L ) ) ) ; if ( Float . isNaN ( fvalue ) ) { pid = ( sindex_ >>> 31 ) != 0 ? cleft_ : UnsafeUtils . get4 ( _nodes , pos + 4 ) ; } else { final float value_ = UnsafeUtils . get4f ( _nodes , pos + 12 ) ; pid = ( fvalue < value_ ) ? cleft_ : UnsafeUtils . get4 ( _nodes , pos + 4 ) ; } pos = pid * NODE_SIZE + 4 ; cleft_ = UnsafeUtils . get4 ( _nodes , pos ) ; } return UnsafeUtils . get4f ( _nodes , pos + 12 ) ; } | Retrieves nodes from root to leaf and returns leaf value . |
22,442 | private static void runCopy ( final long start , final long len , final int keySize , final int batchSize , final long otmp [ ] [ ] , final byte xtmp [ ] [ ] , final long o [ ] [ ] , final byte x [ ] [ ] ) { long numRowsToCopy = len ; int sourceBatch = 0 , sourceOffset = 0 ; int targetBatch = ( int ) ( start / batchSize ) , targetOffset = ( int ) ( start % batchSize ) ; int targetBatchRemaining = batchSize - targetOffset ; int sourceBatchRemaining = batchSize - sourceOffset ; while ( numRowsToCopy > 0 ) { final int thisCopy = ( int ) Math . min ( numRowsToCopy , Math . min ( sourceBatchRemaining , targetBatchRemaining ) ) ; System . arraycopy ( otmp [ sourceBatch ] , sourceOffset , o [ targetBatch ] , targetOffset , thisCopy ) ; System . arraycopy ( xtmp [ sourceBatch ] , sourceOffset * keySize , x [ targetBatch ] , targetOffset * keySize , thisCopy * keySize ) ; numRowsToCopy -= thisCopy ; sourceOffset += thisCopy ; sourceBatchRemaining -= thisCopy ; targetOffset += thisCopy ; targetBatchRemaining -= thisCopy ; if ( sourceBatchRemaining == 0 ) { sourceBatch ++ ; sourceOffset = 0 ; sourceBatchRemaining = batchSize ; } if ( targetBatchRemaining == 0 ) { targetBatch ++ ; targetOffset = 0 ; targetBatchRemaining = batchSize ; } } } | Hot loop pulled out from the main run code |
22,443 | private Frame closeFrame ( Key key , String [ ] names , String [ ] [ ] domains , Futures fs ) { if ( _output_types == null ) return null ; final int noutputs = _output_types . length ; Vec [ ] vecs = new Vec [ noutputs ] ; if ( _appendables == null || _appendables . length == 0 ) for ( int i = 0 ; i < noutputs ; i ++ ) vecs [ i ] = _fr . anyVec ( ) . makeZero ( ) ; else { int rowLayout = _appendables [ 0 ] . compute_rowLayout ( ) ; for ( int i = 0 ; i < noutputs ; i ++ ) { _appendables [ i ] . setDomain ( domains == null ? null : domains [ i ] ) ; vecs [ i ] = _appendables [ i ] . close ( rowLayout , fs ) ; } } return new Frame ( key , names , vecs ) ; } | the work - horse for the outputFrame calls |
22,444 | private void configureConnector ( String proto , Connector connector ) { connector . setRequestHeaderSize ( getSysPropInt ( proto + ".requestHeaderSize" , 32 * 1024 ) ) ; connector . setRequestBufferSize ( getSysPropInt ( proto + ".requestBufferSize" , 32 * 1024 ) ) ; connector . setResponseHeaderSize ( getSysPropInt ( proto + ".responseHeaderSize" , connector . getResponseHeaderSize ( ) ) ) ; connector . setResponseBufferSize ( getSysPropInt ( proto + ".responseBufferSize" , connector . getResponseBufferSize ( ) ) ) ; } | see PUBDEV - 5939 for details |
22,445 | public static int numRoutes ( int version ) { int count = 0 ; for ( Route route : routesList ) if ( route . getVersion ( ) == version ) count ++ ; return count ; } | Calculates number of routes having the specified version . |
22,446 | public static Route registerEndpoint ( String method_uri , Class < ? extends RestApiHandler > handler_clz ) { try { RestApiHandler handler = handler_clz . newInstance ( ) ; return registerEndpoint ( handler . name ( ) , method_uri , handler_clz , null , handler . help ( ) ) ; } catch ( Exception e ) { throw H2O . fail ( e . getMessage ( ) ) ; } } | Register an HTTP request handler for the given URL pattern . |
22,447 | public static HttpLogFilter defaultFilter ( ) { return new HttpLogFilter ( ) { public LogFilterLevel filter ( RequestUri uri , Properties header , Properties parms ) { String url = uri . getUrl ( ) ; if ( url . endsWith ( ".css" ) || url . endsWith ( ".js" ) || url . endsWith ( ".png" ) || url . endsWith ( ".ico" ) ) { return LogFilterLevel . DO_NOT_LOG ; } String [ ] path = uri . getPath ( ) ; if ( path [ 2 ] . equals ( "PersistS3" ) || path [ 2 ] . equals ( "ImportSQLTable" ) || path [ 2 ] . equals ( "DecryptionSetup" ) ) { return LogFilterLevel . URL_ONLY ; } if ( path [ 2 ] . equals ( "Cloud" ) || path [ 2 ] . equals ( "Jobs" ) && uri . isGetMethod ( ) || path [ 2 ] . equals ( "Log" ) || path [ 2 ] . equals ( "Progress" ) || path [ 2 ] . equals ( "Typeahead" ) || path [ 2 ] . equals ( "WaterMeterCpuTicks" ) ) { return LogFilterLevel . DO_NOT_LOG ; } return LogFilterLevel . LOG ; } } ; } | Provide the default filters for H2O s HTTP logging . |
22,448 | private static NanoResponse maybeServeSpecial ( RequestUri uri ) { assert uri != null ; if ( uri . isHeadMethod ( ) ) { if ( uri . getUrl ( ) . equals ( "/" ) ) return new NanoResponse ( HTTP_OK , MIME_PLAINTEXT , "" ) ; } if ( uri . isGetMethod ( ) ) { String [ ] path = uri . getPath ( ) ; if ( path [ 2 ] . equals ( "" ) ) return redirectToFlow ( ) ; if ( path [ 2 ] . equals ( "Logs" ) && path [ 3 ] . equals ( "download" ) ) return downloadLogs ( ) ; if ( path [ 2 ] . equals ( "NodePersistentStorage.bin" ) && path . length == 6 ) return downloadNps ( path [ 3 ] , path [ 4 ] ) ; } return null ; } | Handle any URLs that bypass the standard route approach . This is stuff that has abnormal non - JSON response payloads . |
22,449 | private static NanoResponse getResource ( RequestType request_type , String url ) { byte [ ] bytes = _cache . get ( url ) ; if ( bytes == null ) { try ( InputStream resource = water . init . JarHash . getResource2 ( url ) ) { if ( resource != null ) { try { bytes = toByteArray ( resource ) ; } catch ( IOException e ) { Log . err ( e ) ; } } } catch ( IOException ignore ) { } } if ( bytes == null || bytes . length == 0 ) return response404 ( "Resource " + url , request_type ) ; int i = url . lastIndexOf ( '.' ) ; String mime ; switch ( url . substring ( i + 1 ) ) { case "js" : mime = MIME_JS ; break ; case "css" : mime = MIME_CSS ; break ; case "htm" : case "html" : mime = MIME_HTML ; break ; case "jpg" : case "jpeg" : mime = MIME_JPEG ; break ; case "png" : mime = MIME_PNG ; break ; case "svg" : mime = MIME_SVG ; break ; case "gif" : mime = MIME_GIF ; break ; case "woff" : mime = MIME_WOFF ; break ; default : mime = MIME_DEFAULT_BINARY ; } NanoResponse res = new NanoResponse ( HTTP_OK , mime , new ByteArrayInputStream ( bytes ) ) ; res . addHeader ( "Content-Length" , Long . toString ( bytes . length ) ) ; return res ; } | Returns the response containing the given uri with the appropriate mime type . |
22,450 | public ParseSetup createParserSetup ( Key [ ] inputs , ParseSetup requiredSetup ) { FileVec f ; Object frameOrVec = DKV . getGet ( inputs [ 0 ] ) ; if ( frameOrVec instanceof water . fvec . Frame ) f = ( FileVec ) ( ( Frame ) frameOrVec ) . vec ( 0 ) ; else f = ( FileVec ) frameOrVec ; return readSetup ( f , requiredSetup . getColumnNames ( ) , requiredSetup . getColumnTypes ( ) ) ; } | Use only the first file to setup everything . |
22,451 | public ParseSetup readSetup ( FileVec f , String [ ] columnNames , byte [ ] columnTypes ) { try { Reader orcFileReader = getReader ( f ) ; StructObjectInspector insp = ( StructObjectInspector ) orcFileReader . getObjectInspector ( ) ; OrcParser . OrcParseSetup stp = OrcParser . deriveParseSetup ( orcFileReader , insp ) ; if ( ! ( columnNames == null ) && ( stp . getAllColNames ( ) . length == columnNames . length ) ) { stp . setColumnNames ( columnNames ) ; stp . setAllColNames ( columnNames ) ; } if ( columnTypes != null ) { byte [ ] old_columnTypes = stp . getColumnTypes ( ) ; String [ ] old_columnTypeNames = stp . getColumnTypesString ( ) ; for ( int index = 0 ; index < columnTypes . length ; index ++ ) { if ( columnTypes [ index ] != old_columnTypes [ index ] ) { if ( supported_type_conversions [ old_columnTypes [ index ] ] [ columnTypes [ index ] ] == 1 ) { old_columnTypes [ index ] = columnTypes [ index ] ; } else { stp . addErrs ( new ParseWriter . UnsupportedTypeOverride ( f . _key . toString ( ) , Vec . TYPE_STR [ old_columnTypes [ index ] ] , Vec . TYPE_STR [ columnTypes [ index ] ] , columnNames [ index ] ) ) ; } } if ( columnTypes [ index ] == Vec . T_CAT || columnTypes [ index ] == Vec . T_BAD || columnTypes [ index ] == Vec . T_TIME ) old_columnTypes [ index ] = columnTypes [ index ] ; } stp . setColumnTypes ( old_columnTypes ) ; stp . setColumnTypeStrings ( old_columnTypeNames ) ; } List < StripeInformation > stripesInfo = orcFileReader . getStripes ( ) ; if ( stripesInfo . size ( ) == 0 ) { f . setChunkSize ( stp . _chunk_size = ( int ) f . length ( ) ) ; return stp ; } f . setNChunks ( stripesInfo . size ( ) ) ; stp . _chunk_size = f . _chunkSize ; assert f . nChunks ( ) == stripesInfo . size ( ) ; return stp ; } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } } | This method will create the readers and others info needed to parse an orc file . In addition it will not over - ride the columnNames columnTypes that the user may want to force upon it . However we only allow users to set column types to enum at this point and ignore all the other requests . |
22,452 | public int compareTo ( Object o ) { SortedClassProbability other = ( SortedClassProbability ) o ; if ( this . probability < other . probability ) { return - 1 ; } else if ( this . probability > other . probability ) { return 1 ; } else { return 0 ; } } | Comparison implementation for this object type . |
22,453 | @ SuppressWarnings ( "unused" ) public ParseV3 parse ( int version , ParseV3 parse ) { ParserInfo parserInfo = ParserService . INSTANCE . getByName ( parse . parse_type ) . info ( ) ; ParseSetup setup = new ParseSetup ( parserInfo , parse . separator , parse . single_quotes , parse . check_header , parse . number_columns , delNulls ( parse . column_names ) , ParseSetup . strToColumnTypes ( parse . column_types ) , parse . domains , parse . na_strings , null , new ParseWriter . ParseErr [ 0 ] , parse . chunk_size , parse . decrypt_tool != null ? parse . decrypt_tool . key ( ) : null , parse . skipped_columns , parse . custom_non_data_line_markers != null ? parse . custom_non_data_line_markers . getBytes ( ) : null ) ; if ( parse . source_frames == null ) throw new H2OIllegalArgumentException ( "Data for Frame '" + parse . destination_frame . name + "' is not available. Please check that the path is valid (for all H2O nodes).'" ) ; Key [ ] srcs = new Key [ parse . source_frames . length ] ; for ( int i = 0 ; i < parse . source_frames . length ; i ++ ) srcs [ i ] = parse . source_frames [ i ] . key ( ) ; if ( ( setup . getParseType ( ) . name ( ) . toLowerCase ( ) . equals ( "svmlight" ) || ( setup . getParseType ( ) . name ( ) . toLowerCase ( ) . equals ( "avro" ) ) ) && ( ( setup . getSkippedColumns ( ) != null ) && ( setup . getSkippedColumns ( ) . length > 0 ) ) ) throw new H2OIllegalArgumentException ( "Parser: skipped_columns are not supported for SVMlight or Avro parsers." ) ; if ( setup . getSkippedColumns ( ) != null && ( ( setup . get_parse_columns_indices ( ) == null ) || ( setup . get_parse_columns_indices ( ) . length == 0 ) ) ) throw new H2OIllegalArgumentException ( "Parser: all columns in the file are skipped and no H2OFrame" + " can be returned." ) ; parse . job = new JobV3 ( ParseDataset . parse ( parse . destination_frame . key ( ) , srcs , parse . delete_on_done , setup , parse . blocking ) . _job ) ; if ( parse . blocking ) { Frame fr = DKV . getGet ( parse . destination_frame . key ( ) ) ; parse . rows = fr . numRows ( ) ; } return parse ; } | Entry point for parsing . |
22,454 | public static Job [ ] jobs ( ) { final Value val = DKV . get ( LIST ) ; if ( val == null ) return new Job [ 0 ] ; JobList jl = val . get ( ) ; Job [ ] jobs = new Job [ jl . _jobs . length ] ; int j = 0 ; for ( int i = 0 ; i < jl . _jobs . length ; i ++ ) { final Value job = DKV . get ( jl . _jobs [ i ] ) ; if ( job != null ) jobs [ j ++ ] = job . get ( ) ; } if ( j == jobs . length ) return jobs ; jobs = Arrays . copyOf ( jobs , j ) ; Key keys [ ] = new Key [ j ] ; for ( int i = 0 ; i < j ; i ++ ) keys [ i ] = jobs [ i ] . _key ; DKV . DputIfMatch ( LIST , new Value ( LIST , new JobList ( keys ) ) , val , new Futures ( ) ) ; return jobs ; } | The list of all Jobs past and present . |
22,455 | public T get ( ) { Barrier2 bar = _barrier ; if ( bar != null ) bar . join ( ) ; assert isStopped ( ) ; if ( _ex != null ) throw new RuntimeException ( ( Throwable ) AutoBuffer . javaSerializeReadPojo ( _ex ) ) ; return _result == null ? null : _result . get ( ) ; } | Blocks until the Job completes |
22,456 | static private boolean isIdentChar ( char x ) { return ( x == '$' ) || ( ( x >= 'a' ) && ( x <= 'z' ) ) || ( ( x >= 'A' ) && ( x <= 'Z' ) ) || ( ( x >= '0' ) && ( x <= '9' ) ) || ( x == '_' ) ; } | Passes only valid placeholder name characters |
22,457 | private ValFrame fast_table ( Vec v1 , int ncols , String colname ) { if ( ncols != 1 || ! v1 . isInt ( ) ) return null ; long spanl = ( long ) v1 . max ( ) - ( long ) v1 . min ( ) + 1 ; if ( spanl > 1000000 ) return null ; AstTable . FastCnt fastCnt = new AstTable . FastCnt ( ( long ) v1 . min ( ) , ( int ) spanl ) . doAll ( v1 ) ; final long cnts [ ] = fastCnt . _cnts ; final long minVal = fastCnt . _min ; Vec dataLayoutVec = Vec . makeCon ( 0 , cnts . length ) ; Frame fr = new MRTask ( ) { public void map ( Chunk cs [ ] , NewChunk nc0 , NewChunk nc1 ) { final Chunk c = cs [ 0 ] ; for ( int i = 0 ; i < c . _len ; ++ i ) { int idx = ( int ) ( i + c . start ( ) ) ; if ( cnts [ idx ] > 0 ) { nc0 . addNum ( idx + minVal ) ; nc1 . addNum ( cnts [ idx ] ) ; } } } } . doAll ( new byte [ ] { Vec . T_NUM , Vec . T_NUM } , dataLayoutVec ) . outputFrame ( new String [ ] { colname , "Count" } , new String [ ] [ ] { v1 . domain ( ) , null } ) ; dataLayoutVec . remove ( ) ; return new ValFrame ( fr ) ; } | Fast - path for 1 integer column |
22,458 | public final LocalCompressedForest fetch ( ) { int ntrees = _treeKeys . length ; CompressedTree [ ] [ ] trees = new CompressedTree [ ntrees ] [ ] ; for ( int t = 0 ; t < ntrees ; t ++ ) { Key [ ] treek = _treeKeys [ t ] ; trees [ t ] = new CompressedTree [ treek . length ] ; for ( int i = 0 ; i < treek . length ; i ++ ) if ( treek [ i ] != null ) trees [ t ] [ i ] = DKV . get ( treek [ i ] ) . get ( ) ; } return new LocalCompressedForest ( trees , _domains ) ; } | Fetches trees from DKV and converts to a node - local structure . |
22,459 | public static int extractVersionFromSchemaName ( String clz_name ) { int idx = clz_name . lastIndexOf ( 'V' ) ; if ( idx == - 1 ) return - 1 ; try { return Integer . valueOf ( clz_name . substring ( idx + 1 ) ) ; } catch ( NumberFormatException ex ) { return - 1 ; } } | Extract the version number from the schema class name . Returns - 1 if there s no version number at the end of the classname . |
22,460 | public static Class < ? extends Iced > getImplClass ( Class < ? extends Schema > clz ) { Class < ? extends Iced > impl_class = ReflectionUtils . findActualClassParameter ( clz , 0 ) ; if ( null == impl_class ) Log . warn ( "Failed to find an impl class for Schema: " + clz ) ; return impl_class ; } | Return the class of the implementation type parameter I for the given Schema class . Used by the metadata facilities and the reflection - base field - copying magic in PojoUtils . |
22,461 | public Class < I > getImplClass ( ) { return _impl_class != null ? _impl_class : ( _impl_class = ReflectionUtils . findActualClassParameter ( this . getClass ( ) , 0 ) ) ; } | Return the class of the implementation type parameter I for this Schema . Used by generic code which deals with arbitrary schemas and their backing impl classes . Never returns null . |
22,462 | static private < T > T parseInteger ( String s , Class < T > return_type ) { try { java . math . BigDecimal num = new java . math . BigDecimal ( s ) ; T result = ( T ) num . getClass ( ) . getDeclaredMethod ( return_type . getSimpleName ( ) + "ValueExact" , new Class [ 0 ] ) . invoke ( num ) ; return result ; } catch ( InvocationTargetException ite ) { throw new NumberFormatException ( "The expression's numeric value is out of the range of type " + return_type . getSimpleName ( ) ) ; } catch ( NoSuchMethodException nsme ) { throw new IllegalArgumentException ( return_type . getSimpleName ( ) + " is not an integer data type" ) ; } catch ( IllegalAccessException iae ) { throw H2O . fail ( "Cannot parse expression as " + return_type . getSimpleName ( ) + " (Illegal Access)" ) ; } } | Parses a string into an integer data type specified by parameter return_type . Accepts any format that is accepted by java s BigDecimal class . - Throws a NumberFormatException if the evaluated string is not an integer or if the value is too large to be stored into return_type without overflow . - Throws an IllegalAgumentException if return_type is not an integer data type . |
22,463 | public static < T extends Schema > T newInstance ( Class < T > clz ) { try { return clz . newInstance ( ) ; } catch ( Exception e ) { throw H2O . fail ( "Failed to instantiate schema of class: " + clz . getCanonicalName ( ) , e ) ; } } | Returns a new Schema instance . Does not throw nor returns null . |
22,464 | private void writeModelDetails ( ) throws IOException { ModelSchemaV3 modelSchema = ( ModelSchemaV3 ) SchemaServer . schema ( 3 , model ) . fillFromImpl ( model ) ; startWritingTextFile ( "experimental/modelDetails.json" ) ; writeln ( modelSchema . toJsonString ( ) ) ; finishWritingTextFile ( ) ; } | Create file that contains model details in JSON format . This information is pulled from the models schema . |
22,465 | protected void writeMap ( AutoBuffer ab , int mode ) { Object [ ] kvs = _map . raw_array ( ) ; switch ( mode ) { case 1 : for ( int i = 2 ; i < kvs . length ; i += 2 ) if ( kvs [ i ] instanceof String && kvs [ i + 1 ] instanceof String ) ab . putStr ( ( String ) kvs [ i ] ) . putStr ( ( String ) kvs [ i + 1 ] ) ; break ; case 2 : for ( int i = 2 ; i < kvs . length ; i += 2 ) if ( kvs [ i ] instanceof String && kvs [ i + 1 ] instanceof Iced ) ab . putStr ( ( String ) kvs [ i ] ) . put ( ( Freezable ) kvs [ i + 1 ] ) ; break ; case 3 : for ( int i = 2 ; i < kvs . length ; i += 2 ) if ( kvs [ i ] instanceof Iced && kvs [ i + 1 ] instanceof String ) ab . put ( ( Freezable ) kvs [ i ] ) . putStr ( ( String ) kvs [ i + 1 ] ) ; break ; case 4 : for ( int i = 2 ; i < kvs . length ; i += 2 ) if ( kvs [ i ] instanceof Freezable && kvs [ i + 1 ] instanceof Freezable ) ab . put ( ( Freezable ) kvs [ i ] ) . put ( ( Freezable ) kvs [ i + 1 ] ) ; break ; case 5 : for ( int i = 2 ; i < kvs . length ; i += 2 ) if ( kvs [ i ] instanceof String && kvs [ i + 1 ] instanceof Freezable [ ] ) { Freezable [ ] vals = ( Freezable [ ] ) kvs [ i + 1 ] ; ab . putStr ( ( String ) kvs [ i ] ) . put4 ( vals . length ) ; for ( Freezable v : vals ) ab . put ( v ) ; } break ; case 6 : for ( int i = 2 ; i < kvs . length ; i += 2 ) if ( kvs [ i ] instanceof Freezable && kvs [ i + 1 ] instanceof Freezable [ ] ) { Freezable [ ] vals = ( Freezable [ ] ) kvs [ i + 1 ] ; ab . put ( ( Freezable ) kvs [ i ] ) . put4 ( vals . length ) ; for ( Freezable v : vals ) ab . put ( v ) ; } break ; default : throw H2O . fail ( ) ; } } | Map - writing optimized for NBHM |
22,466 | private boolean casTail ( Node cmp , Node val ) { return UNSAFE . compareAndSwapObject ( this , tailOffset , cmp , val ) ; } | CAS methods for fields |
22,467 | private Node firstOfMode ( boolean isData ) { for ( Node p = head ; p != null ; p = succ ( p ) ) { if ( ! p . isMatched ( ) ) return ( p . isData == isData ) ? p : null ; } return null ; } | Returns the first unmatched node of the given mode or null if none . Used by methods isEmpty hasWaitingConsumer . |
22,468 | private E firstDataItem ( ) { for ( Node p = head ; p != null ; p = succ ( p ) ) { Object item = p . item ; if ( p . isData ) { if ( item != null && item != p ) return LinkedTransferQueue . < E > cast ( item ) ; } else if ( item == null ) return null ; } return null ; } | Returns the item in the first unmatched node with isData ; or null if none . Used by peek . |
22,469 | public void transfer ( E e ) throws InterruptedException { if ( xfer ( e , true , SYNC , 0 ) != null ) { Thread . interrupted ( ) ; throw new InterruptedException ( ) ; } } | Transfers the element to a consumer waiting if necessary to do so . |
22,470 | public static < T > Class < T > findActualClassParameter ( Class clz , int parm ) { Class parm_class = null ; if ( clz . getGenericSuperclass ( ) instanceof ParameterizedType ) { Type [ ] handler_type_parms = ( ( ParameterizedType ) ( clz . getGenericSuperclass ( ) ) ) . getActualTypeArguments ( ) ; if ( handler_type_parms [ parm ] instanceof Class ) { parm_class = ( Class ) handler_type_parms [ parm ] ; } else if ( handler_type_parms [ parm ] instanceof TypeVariable ) { TypeVariable v = ( TypeVariable ) ( handler_type_parms [ parm ] ) ; Type t = v . getBounds ( ) [ 0 ] ; if ( t instanceof Class ) parm_class = ( Class ) t ; else if ( t instanceof ParameterizedType ) parm_class = ( Class ) ( ( ParameterizedType ) t ) . getRawType ( ) ; } else if ( handler_type_parms [ parm ] instanceof ParameterizedType ) { parm_class = ( Class ) ( ( ParameterizedType ) ( handler_type_parms [ parm ] ) ) . getRawType ( ) ; } else { String msg = "Iced parameter for handler: " + clz + " uses a type parameterization scheme that we don't yet handle: " + handler_type_parms [ parm ] ; Log . warn ( msg ) ; throw H2O . fail ( msg ) ; } } else { parm_class = Iced . class ; } return ( Class < T > ) parm_class ; } | Reflection helper which returns the actual class for a type parameter even if itself is parameterized . |
22,471 | public static Class findMethodParameterClass ( Method method , int parm ) { Class [ ] clzes = method . getParameterTypes ( ) ; if ( clzes . length <= parm ) throw H2O . fail ( "Asked for the class of parameter number: " + parm + " of method: " + method + ", which only has: " + clzes . length + " parameters." ) ; return clzes [ parm ] ; } | Reflection helper which returns the actual class for a method s parameter . |
22,472 | public static Class findActualFieldClass ( Class clz , Field f ) { Type generic_type = f . getGenericType ( ) ; if ( ! ( generic_type instanceof TypeVariable ) ) return f . getType ( ) ; TypeVariable [ ] tvs = clz . getSuperclass ( ) . getTypeParameters ( ) ; TypeVariable tv = ( TypeVariable ) generic_type ; String type_param_name = tv . getName ( ) ; int which_tv = - 1 ; for ( int i = 0 ; i < tvs . length ; i ++ ) if ( type_param_name . equals ( tvs [ i ] . getName ( ) ) ) which_tv = i ; if ( - 1 == which_tv ) { return f . getType ( ) ; } ParameterizedType generic_super = ( ParameterizedType ) clz . getGenericSuperclass ( ) ; if ( generic_super . getActualTypeArguments ( ) [ which_tv ] instanceof Class ) return ( Class ) generic_super . getActualTypeArguments ( ) [ which_tv ] ; return findActualFieldClass ( clz . getSuperclass ( ) , f ) ; } | Reflection helper which returns the actual class for a field which has a parameterized type . E . g . DeepLearningV2 s parameters class is in parent ModelBuilderSchema and is parameterized by type parameter P . |
22,473 | public static double asDouble ( Object o ) { if ( o == null ) return Double . NaN ; if ( o instanceof Integer ) return ( ( Integer ) o ) ; if ( o instanceof Long ) return ( ( Long ) o ) ; if ( o instanceof Float ) return ( ( Float ) o ) ; if ( o instanceof Double ) return ( ( Double ) o ) ; if ( o instanceof Enum ) return ( ( Enum ) o ) . ordinal ( ) ; System . out . println ( "Do not know how to convert a " + o . getClass ( ) + " to a double" ) ; throw H2O . fail ( ) ; } | Best effort conversion from an Object to a double |
22,474 | private static int getDataRows ( Chunk [ ] chunks , Frame f , int [ ] chunksIds , int cols ) { double totalRows = 0 ; if ( null != chunks ) { for ( Chunk ch : chunks ) { totalRows += ch . len ( ) ; } } else { for ( int chunkId : chunksIds ) { totalRows += f . anyVec ( ) . chunkLen ( chunkId ) ; } } return ( int ) Math . ceil ( totalRows * cols / SPARSE_MATRIX_DIM ) ; } | FIXME this and the other method should subtract rows where response is 0 |
22,475 | private static long sumChunksLength ( int [ ] chunkIds , Vec vec , Vec weightsVector , int [ ] chunkLengths ) { for ( int i = 0 ; i < chunkIds . length ; i ++ ) { final int chunk = chunkIds [ i ] ; chunkLengths [ i ] = vec . chunkLen ( chunk ) ; if ( weightsVector == null ) continue ; Chunk weightVecChunk = weightsVector . chunkForChunkIdx ( chunk ) ; if ( weightVecChunk . atd ( 0 ) == 0 ) chunkLengths [ i ] -- ; int nzIndex = 0 ; do { nzIndex = weightVecChunk . nextNZ ( nzIndex , true ) ; if ( nzIndex < 0 || nzIndex >= weightVecChunk . _len ) break ; if ( weightVecChunk . atd ( nzIndex ) == 0 ) chunkLengths [ i ] -- ; } while ( true ) ; } long totalChunkLength = 0 ; for ( int cl : chunkLengths ) { totalChunkLength += cl ; } return totalChunkLength ; } | Counts a total sum of chunks inside a vector . Only chunks present in chunkIds are considered . |
22,476 | private static void enlargeTables ( float [ ] [ ] data , int [ ] [ ] rowIndex , int cols , int currentRow , int currentCol ) { while ( data [ currentRow ] . length < currentCol + cols ) { if ( data [ currentRow ] . length == SPARSE_MATRIX_DIM ) { currentCol = 0 ; cols -= ( data [ currentRow ] . length - currentCol ) ; currentRow ++ ; data [ currentRow ] = malloc4f ( ALLOCATED_ARRAY_LEN ) ; rowIndex [ currentRow ] = malloc4 ( ALLOCATED_ARRAY_LEN ) ; } else { int newLen = ( int ) Math . min ( ( long ) data [ currentRow ] . length << 1L , ( long ) SPARSE_MATRIX_DIM ) ; data [ currentRow ] = Arrays . copyOf ( data [ currentRow ] , newLen ) ; rowIndex [ currentRow ] = Arrays . copyOf ( rowIndex [ currentRow ] , newLen ) ; } } } | Assumes both matrices are getting filled at the same rate and will require the same amount of space |
22,477 | void defaultGBMs ( ) { Algo algo = Algo . GBM ; WorkAllocations . Work work = workAllocations . getAllocation ( algo , JobType . ModelBuild ) ; if ( work == null ) return ; Job gbmJob ; GBMParameters gbmParameters = new GBMParameters ( ) ; setCommonModelBuilderParams ( gbmParameters ) ; gbmParameters . _score_tree_interval = 5 ; gbmParameters . _histogram_type = SharedTreeParameters . HistogramType . AUTO ; gbmParameters . _ntrees = 1000 ; gbmParameters . _sample_rate = 0.8 ; gbmParameters . _col_sample_rate = 0.8 ; gbmParameters . _col_sample_rate_per_tree = 0.8 ; gbmParameters . _max_depth = 6 ; gbmParameters . _min_rows = 1 ; gbmJob = trainModel ( null , work , gbmParameters ) ; pollAndUpdateProgress ( Stage . ModelTraining , "GBM 1" , work , this . job ( ) , gbmJob ) ; gbmParameters . _max_depth = 7 ; gbmParameters . _min_rows = 10 ; gbmJob = trainModel ( null , work , gbmParameters ) ; pollAndUpdateProgress ( Stage . ModelTraining , "GBM 2" , work , this . job ( ) , gbmJob ) ; gbmParameters . _max_depth = 8 ; gbmParameters . _min_rows = 10 ; gbmJob = trainModel ( null , work , gbmParameters ) ; pollAndUpdateProgress ( Stage . ModelTraining , "GBM 3" , work , this . job ( ) , gbmJob ) ; gbmParameters . _max_depth = 10 ; gbmParameters . _min_rows = 10 ; gbmJob = trainModel ( null , work , gbmParameters ) ; pollAndUpdateProgress ( Stage . ModelTraining , "GBM 4" , work , this . job ( ) , gbmJob ) ; gbmParameters . _max_depth = 15 ; gbmParameters . _min_rows = 100 ; gbmJob = trainModel ( null , work , gbmParameters ) ; pollAndUpdateProgress ( Stage . ModelTraining , "GBM 5" , work , this . job ( ) , gbmJob ) ; } | Build Arno s magical 5 default GBMs . |
22,478 | protected Futures remove_impl ( Futures fs ) { if ( trainingFrame != null && origTrainingFrame != null ) Frame . deleteTempFrameAndItsNonSharedVecs ( trainingFrame , origTrainingFrame ) ; if ( leaderboard != null ) leaderboard . remove ( fs ) ; if ( userFeedback != null ) userFeedback . remove ( fs ) ; return super . remove_impl ( fs ) ; } | Delete the AutoML - related objects but leave the grids and models that it built . |
22,479 | private void addModels ( final Key < Model > [ ] newModels ) { int before = leaderboard ( ) . getModelCount ( ) ; leaderboard ( ) . addModels ( newModels ) ; int after = leaderboard ( ) . getModelCount ( ) ; modelCount . addAndGet ( after - before ) ; } | Also the leaderboard will reject duplicate models so use the difference in Leaderboard length here . |
22,480 | @ SuppressWarnings ( "unused" ) public ModelBuildersV3 list ( int version , ModelBuildersV3 m ) { m . model_builders = new ModelBuilderSchema . IcedHashMapStringModelBuilderSchema ( ) ; for ( String algo : ModelBuilder . algos ( ) ) { ModelBuilder builder = ModelBuilder . make ( algo , null , null ) ; m . model_builders . put ( algo . toLowerCase ( ) , ( ModelBuilderSchema ) SchemaServer . schema ( version , builder ) . fillFromImpl ( builder ) ) ; } return m ; } | Return all the modelbuilders . |
22,481 | @ SuppressWarnings ( "unused" ) public ModelIdV3 calcModelId ( int version , ModelBuildersV3 m ) { m . model_builders = new ModelBuilderSchema . IcedHashMapStringModelBuilderSchema ( ) ; String model_id = H2O . calcNextUniqueModelId ( m . algo ) ; ModelIdV3 mm = new ModelIdV3 ( ) ; mm . model_id = model_id ; return mm ; } | Calculate next unique model_id . |
22,482 | public void registerRestApiExtensions ( ) { if ( restApiExtensionsRegistered ) { throw H2O . fail ( "APIs already registered" ) ; } for ( AbstractH2OExtension e : getCoreExtensions ( ) ) { e . printInitialized ( ) ; } Log . info ( "Registered " + coreExtensions . size ( ) + " core extensions in: " + registerCoreExtensionsMillis + "ms" ) ; Log . info ( "Registered H2O core extensions: " + Arrays . toString ( getCoreExtensionNames ( ) ) ) ; if ( listenerExtensions . size ( ) > 0 ) { Log . info ( "Registered: " + listenerExtensions . size ( ) + " listener extensions in: " + registerListenerExtensionsMillis + "ms" ) ; Log . info ( "Registered Listeners extensions: " + Arrays . toString ( getListenerExtensionNames ( ) ) ) ; } if ( authExtensions . size ( ) > 0 ) { Log . info ( "Registered: " + authExtensions . size ( ) + " auth extensions in: " + registerAuthExtensionsMillis + "ms" ) ; Log . info ( "Registered Auth extensions: " + Arrays . toString ( getAuthExtensionNames ( ) ) ) ; } long before = System . currentTimeMillis ( ) ; RequestServer . DummyRestApiContext dummyRestApiContext = new RequestServer . DummyRestApiContext ( ) ; ServiceLoader < RestApiExtension > restApiExtensionLoader = ServiceLoader . load ( RestApiExtension . class ) ; for ( RestApiExtension r : restApiExtensionLoader ) { try { if ( isEnabled ( r ) ) { r . registerEndPoints ( dummyRestApiContext ) ; r . registerSchemas ( dummyRestApiContext ) ; restApiExtensions . put ( r . getName ( ) , r ) ; } } catch ( Exception e ) { Log . info ( "Cannot register extension: " + r + ". Skipping it..." ) ; } } restApiExtensionsRegistered = true ; long registerApisMillis = System . currentTimeMillis ( ) - before ; Log . info ( "Registered: " + RequestServer . numRoutes ( ) + " REST APIs in: " + registerApisMillis + "ms" ) ; Log . info ( "Registered REST API extensions: " + Arrays . toString ( getRestApiExtensionNames ( ) ) ) ; SchemaServer . registerAllSchemasIfNecessary ( dummyRestApiContext . getAllSchemas ( ) ) ; } | Register REST API routes . |
22,483 | public void registerListenerExtensions ( ) { if ( listenerExtensionsRegistered ) { throw H2O . fail ( "Listeners already registered" ) ; } long before = System . currentTimeMillis ( ) ; ServiceLoader < H2OListenerExtension > extensionsLoader = ServiceLoader . load ( H2OListenerExtension . class ) ; for ( H2OListenerExtension ext : extensionsLoader ) { ext . init ( ) ; listenerExtensions . put ( ext . getName ( ) , ext ) ; } listenerExtensionsRegistered = true ; registerListenerExtensionsMillis = System . currentTimeMillis ( ) - before ; } | Register various listener extensions |
22,484 | private void initializeDataTransformationErrorsCount ( GenModel model ) { String responseColumnName = model . isSupervised ( ) ? model . getResponseName ( ) : null ; dataTransformationErrorsCountPerColumn = new ConcurrentHashMap < > ( ) ; for ( String column : model . getNames ( ) ) { if ( ! model . isSupervised ( ) || ! column . equals ( responseColumnName ) ) { dataTransformationErrorsCountPerColumn . put ( column , new AtomicLong ( ) ) ; } } dataTransformationErrorsCountPerColumn = Collections . unmodifiableMap ( dataTransformationErrorsCountPerColumn ) ; } | Initializes the map of data transformation errors for each column that is not related to response variable excluding response column . The map is initialized as unmodifiable and thread - safe . |
22,485 | public long getTotalUnknownCategoricalLevelsSeen ( ) { long total = 0 ; for ( AtomicLong l : unknownCategoricalsPerColumn . values ( ) ) { total += l . get ( ) ; } return total ; } | Counts and returns all previously unseen categorical variables across all columns . Results may vary when called during prediction phase . |
22,486 | ProblemType guessProblemType ( ) { if ( _problem_type == auto ) { boolean image = false ; boolean text = false ; String first = null ; Vec v = train ( ) . vec ( 0 ) ; if ( v . isString ( ) || v . isCategorical ( ) ) { BufferedString bs = new BufferedString ( ) ; first = v . atStr ( bs , 0 ) . toString ( ) ; try { ImageIO . read ( new File ( first ) ) ; image = true ; } catch ( Throwable t ) { } try { ImageIO . read ( new URL ( first ) ) ; image = true ; } catch ( Throwable t ) { } } if ( first != null ) { if ( ! image && ( first . endsWith ( ".jpg" ) || first . endsWith ( ".png" ) || first . endsWith ( ".tif" ) ) ) { image = true ; Log . warn ( "Cannot read first image at " + first + " - Check data." ) ; } else if ( v . isString ( ) && train ( ) . numCols ( ) <= 4 ) { text = true ; } } if ( image ) return ProblemType . image ; else if ( text ) return ProblemType . text ; else return ProblemType . dataset ; } else { return _problem_type ; } } | Attempt to guess the problem type from the dataset |
22,487 | private void score0 ( double [ ] data , double [ ] preds , int treeIdx ) { Key [ ] keys = _output . _treeKeys [ treeIdx ] ; for ( int c = 0 ; c < keys . length ; c ++ ) { if ( keys [ c ] != null ) { double pred = DKV . get ( keys [ c ] ) . < CompressedTree > get ( ) . score ( data , _output . _domains ) ; assert ( ! Double . isInfinite ( pred ) ) ; preds [ keys . length == 1 ? 0 : c + 1 ] += pred ; } } } | Score per line per tree |
22,488 | protected M deepClone ( Key < M > result ) { M newModel = IcedUtils . deepCopy ( self ( ) ) ; newModel . _key = result ; newModel . _output . clearModelMetrics ( ) ; newModel . _output . _training_metrics = null ; newModel . _output . _validation_metrics = null ; Key [ ] [ ] treeKeys = newModel . _output . _treeKeys ; for ( int i = 0 ; i < treeKeys . length ; i ++ ) { for ( int j = 0 ; j < treeKeys [ i ] . length ; j ++ ) { if ( treeKeys [ i ] [ j ] == null ) continue ; CompressedTree ct = DKV . get ( treeKeys [ i ] [ j ] ) . get ( ) ; CompressedTree newCt = IcedUtils . deepCopy ( ct ) ; newCt . _key = CompressedTree . makeTreeKey ( i , j ) ; DKV . put ( treeKeys [ i ] [ j ] = newCt . _key , newCt ) ; } } Key [ ] [ ] treeKeysAux = newModel . _output . _treeKeysAux ; if ( treeKeysAux != null ) { for ( int i = 0 ; i < treeKeysAux . length ; i ++ ) { for ( int j = 0 ; j < treeKeysAux [ i ] . length ; j ++ ) { if ( treeKeysAux [ i ] [ j ] == null ) continue ; CompressedTree ct = DKV . get ( treeKeysAux [ i ] [ j ] ) . get ( ) ; CompressedTree newCt = IcedUtils . deepCopy ( ct ) ; newCt . _key = Key . make ( createAuxKey ( treeKeys [ i ] [ j ] . toString ( ) ) ) ; DKV . put ( treeKeysAux [ i ] [ j ] = newCt . _key , newCt ) ; } } } return newModel ; } | Performs deep clone of given model . |
22,489 | public SharedTreeSubgraph getSharedTreeSubgraph ( final int tidx , final int cls ) { if ( tidx < 0 || tidx >= _output . _ntrees ) { throw new IllegalArgumentException ( "Invalid tree index: " + tidx + ". Tree index must be in range [0, " + ( _output . _ntrees - 1 ) + "]." ) ; } final CompressedTree auxCompressedTree = _output . _treeKeysAux [ tidx ] [ cls ] . get ( ) ; return _output . _treeKeys [ tidx ] [ cls ] . get ( ) . toSharedTreeSubgraph ( auxCompressedTree , _output . _names , _output . _domains ) ; } | Converts a given tree of the ensemble to a user - understandable representation . |
22,490 | public void notifyAboutCloudSize ( InetAddress ip , int port , InetAddress leaderIp , int leaderPort , int size ) { notifyAboutCloudSize ( ip , port , size ) ; } | Tell the embedding software that this H2O instance belongs to a cloud of a certain size . This may be nonblocking . |
22,491 | public double [ ] getRow ( ) { if ( _fr . numRows ( ) != 1 ) throw new IllegalArgumentException ( "Trying to get a single row from a multirow frame: " + _fr . numRows ( ) + "!=1" ) ; double res [ ] = new double [ _fr . numCols ( ) ] ; for ( int i = 0 ; i < _fr . numCols ( ) ; ++ i ) res [ i ] = _fr . vec ( i ) . at ( 0 ) ; return res ; } | Extract row from a single - row frame . |
22,492 | public final TypeV putIfMatchUnlocked ( Object key , Object newVal , Object oldVal ) { if ( oldVal == null ) oldVal = TOMBSTONE ; if ( newVal == null ) newVal = TOMBSTONE ; final TypeV res = ( TypeV ) putIfMatch ( this , _kvs , key , newVal , oldVal ) ; assert ! ( res instanceof Prime ) ; return res == TOMBSTONE ? null : res ; } | then the put inserted newVal otherwise it failed . |
22,493 | private void writeObject ( java . io . ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; for ( Object K : keySet ( ) ) { final Object V = get ( K ) ; s . writeObject ( K ) ; s . writeObject ( V ) ; } s . writeObject ( null ) ; s . writeObject ( null ) ; } | Write a NBHM to a stream |
22,494 | private void readObject ( java . io . ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; initialize ( MIN_SIZE ) ; for ( ; ; ) { final TypeK K = ( TypeK ) s . readObject ( ) ; final TypeV V = ( TypeV ) s . readObject ( ) ; if ( K == null ) break ; put ( K , V ) ; } } | Read a CHM from a stream |
22,495 | private long computeShift ( final BigInteger max , final int i ) { int biggestBit = 0 ; int rangeD = max . subtract ( _base [ i ] ) . add ( BigInteger . ONE ) . add ( BigInteger . ONE ) . bitLength ( ) ; biggestBit = _isInt [ i ] ? rangeD : ( rangeD == 64 ? 64 : rangeD + 1 ) ; if ( biggestBit < 8 ) Log . warn ( "biggest bit should be >= 8 otherwise need to dip into next column (TODO)" ) ; assert biggestBit >= 1 ; _shift [ i ] = Math . max ( 8 , biggestBit ) - 8 ; long MSBwidth = 1L << _shift [ i ] ; BigInteger msbWidth = BigInteger . valueOf ( MSBwidth ) ; if ( _base [ i ] . mod ( msbWidth ) . compareTo ( BigInteger . ZERO ) != 0 ) { _base [ i ] = _isInt [ i ] ? msbWidth . multiply ( _base [ i ] . divide ( msbWidth ) . add ( _base [ i ] . signum ( ) < 0 ? BigInteger . valueOf ( - 1L ) : BigInteger . ZERO ) ) : msbWidth . multiply ( _base [ i ] . divide ( msbWidth ) ) ; ; assert _base [ i ] . mod ( msbWidth ) . compareTo ( BigInteger . ZERO ) == 0 ; } return max . subtract ( _base [ i ] ) . add ( BigInteger . ONE ) . shiftRight ( _shift [ i ] ) . intValue ( ) ; } | power of the shift . |
22,496 | public static < DT extends DTask > RPC < DT > call ( H2ONode target , DT dtask ) { return new RPC ( target , dtask ) . call ( ) ; } | 5 sec max timeout cap on exponential decay of retries |
22,497 | private void handleCompleter ( CountedCompleter cc ) { assert cc instanceof H2OCountedCompleter ; if ( _fjtasks == null || ! _fjtasks . contains ( cc ) ) addCompleter ( ( H2OCountedCompleter ) cc ) ; _dt . setCompleter ( null ) ; } | so completion is signaled after the remote comes back . |
22,498 | private RPC < V > handleLocal ( ) { assert _dt . getCompleter ( ) == null ; _dt . setCompleter ( new H2O . H2OCallback < DTask > ( ) { public void callback ( DTask dt ) { synchronized ( RPC . this ) { _done = true ; RPC . this . notifyAll ( ) ; } doAllCompletions ( ) ; } public boolean onExceptionalCompletion ( Throwable ex , CountedCompleter dt ) { synchronized ( RPC . this ) { if ( _done ) return true ; _dt . setException ( ex ) ; _done = true ; RPC . this . notifyAll ( ) ; } doAllCompletions ( ) ; return true ; } } ) ; H2O . submitTask ( _dt ) ; return this ; } | If running on self just submit to queues & do locally |
22,499 | public V get ( ) { Thread cThr = Thread . currentThread ( ) ; int priority = ( cThr instanceof FJWThr ) ? ( ( FJWThr ) cThr ) . _priority : - 1 ; assert _dt . priority ( ) > priority || ( _dt . priority ( ) == priority && _dt instanceof MRTask ) : "*** Attempting to block on task (" + _dt . getClass ( ) + ") with equal or lower priority. Can lead to deadlock! " + _dt . priority ( ) + " <= " + priority ; if ( _done ) return result ( ) ; try { ForkJoinPool . managedBlock ( this ) ; } catch ( InterruptedException ignore ) { } if ( _done ) return result ( ) ; assert isCancelled ( ) ; return null ; } | Throws a DException if the remote throws wrapping the original exception . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.