idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
22,500 | public final boolean cancel ( boolean mayInterruptIfRunning ) { boolean did = false ; synchronized ( this ) { if ( ! isCancelled ( ) ) { did = true ; _target . taskRemove ( _tasknum ) ; _target = null ; } notifyAll ( ) ; } return did ; } | Attempt to cancel job |
22,501 | static void tcp_ack ( final AutoBuffer ab ) throws IOException { int task = ab . getTask ( ) ; RPC rpc = ab . _h2o . taskGet ( task ) ; if ( rpc == null || rpc . _done ) { ab . drainClose ( ) ; } else { assert rpc . _tasknum == task ; assert ! rpc . _done ; try { rpc . response ( ab ) ; } catch ( AutoBuffer . AutoBufferException e ) { throw Log . throwErr ( e . _ioe ) ; } } new AutoBuffer ( ab . _h2o , H2O . ACK_ACK_PRIORITY ) . putTask ( UDP . udp . ackack . ordinal ( ) , task ) . close ( ) ; } | reader thread . |
22,502 | static AutoBuffer ackack ( AutoBuffer ab , int tnum ) { return ab . clearForWriting ( H2O . ACK_ACK_PRIORITY ) . putTask ( UDP . udp . ackack . ordinal ( ) , tnum ) ; } | On all paths send an ACKACK back |
22,503 | private boolean sz_check ( AutoBuffer ab ) { final int absize = ab . size ( ) ; if ( _size == 0 ) { _size = absize ; return true ; } return _size == absize ; } | i . e . resends sent identical data . |
22,504 | public final long getDelay ( TimeUnit unit ) { long delay = ( _started + _retry ) - System . currentTimeMillis ( ) ; return unit . convert ( delay , TimeUnit . MILLISECONDS ) ; } | How long until we should do the timeout action? |
22,505 | public final int compareTo ( Delayed t ) { RPC < ? > dt = ( RPC < ? > ) t ; long nextTime = _started + _retry , dtNextTime = dt . _started + dt . _retry ; return nextTime == dtNextTime ? 0 : ( nextTime > dtNextTime ? 1 : - 1 ) ; } | Needed for the DelayQueue API |
22,506 | public static ScoreKeeper [ ] scoreKeepers ( ScoringInfo [ ] scoring_history ) { ScoreKeeper [ ] sk = new ScoreKeeper [ scoring_history . length ] ; for ( int i = 0 ; i < sk . length ; ++ i ) { sk [ i ] = scoring_history [ i ] . cross_validation ? scoring_history [ i ] . scored_xval : scoring_history [ i ] . validation ? scoring_history [ i ] . scored_valid : scoring_history [ i ] . scored_train ; } return sk ; } | For a given array of ScoringInfo return an array of the cross - validation validation or training ScoreKeepers as available . |
22,507 | public ValRow slice ( int [ ] cols ) { double [ ] ds = new double [ cols . length ] ; String [ ] ns = new String [ cols . length ] ; for ( int i = 0 ; i < cols . length ; ++ i ) { ds [ i ] = _ds [ cols [ i ] ] ; ns [ i ] = _names [ cols [ i ] ] ; } return new ValRow ( ds , ns ) ; } | Creates a new ValRow by selecting elements at the specified indices . |
22,508 | public static double [ ] toPreds ( double in [ ] , float [ ] out , double [ ] preds , int nclasses , double [ ] priorClassDistrib , double defaultThreshold ) { if ( nclasses > 2 ) { for ( int i = 0 ; i < out . length ; ++ i ) preds [ 1 + i ] = out [ i ] ; preds [ 0 ] = GenModel . getPrediction ( preds , priorClassDistrib , in , defaultThreshold ) ; } else if ( nclasses == 2 ) { preds [ 1 ] = 1f - out [ 0 ] ; preds [ 2 ] = out [ 0 ] ; preds [ 0 ] = GenModel . getPrediction ( preds , priorClassDistrib , in , defaultThreshold ) ; } else { preds [ 0 ] = out [ 0 ] ; } return preds ; } | for float output |
22,509 | static public byte [ ] convertStringToByteArr ( String s ) { if ( ( s . length ( ) % 2 ) != 0 ) { throw new RuntimeException ( "String length must be even (was " + s . length ( ) + ")" ) ; } ArrayList < Byte > byteArrayList = new ArrayList < Byte > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i = i + 2 ) { String s2 = s . substring ( i , i + 2 ) ; Integer i2 = Integer . parseInt ( s2 , 16 ) ; Byte b2 = ( byte ) ( i2 & 0xff ) ; byteArrayList . add ( b2 ) ; } byte [ ] byteArr = new byte [ byteArrayList . size ( ) ] ; for ( int i = 0 ; i < byteArr . length ; i ++ ) { byteArr [ i ] = byteArrayList . get ( i ) ; } return byteArr ; } | Hexadecimal string to brute - force convert into an array of bytes . The length of the string must be even . The length of the string is 2x the length of the byte array . |
22,510 | public int run ( String [ ] args ) { int rv = - 1 ; try { rv = run2 ( args ) ; } catch ( org . apache . hadoop . mapred . FileAlreadyExistsException e ) { if ( ctrlc != null ) { ctrlc . setComplete ( ) ; } System . out . println ( "ERROR: " + ( e . getMessage ( ) != null ? e . getMessage ( ) : "(null)" ) ) ; System . exit ( 1 ) ; } catch ( Exception e ) { System . out . println ( "ERROR: " + ( e . getMessage ( ) != null ? e . getMessage ( ) : "(null)" ) ) ; e . printStackTrace ( ) ; System . exit ( 1 ) ; } return rv ; } | The run method called by ToolRunner . |
22,511 | public static void delete ( Key key ) { Value val = DKV . get ( key ) ; if ( val == null ) return ; ( ( Lockable ) val . get ( ) ) . delete ( ) ; } | Write - lock key and delete ; blocking . Throws IAE if the key is already locked . |
22,512 | public final Futures delete ( Key < Job > job_key , Futures fs ) { if ( _key != null ) { Log . debug ( "lock-then-delete " + _key + " by job " + job_key ) ; new PriorWriteLock ( job_key ) . invoke ( _key ) ; } return remove ( fs ) ; } | Write - lock this and delete . Throws IAE if the _key is already locked . |
22,513 | public void read_lock ( Key < Job > job_key ) { if ( _key != null ) { Log . debug ( "shared-read-lock " + _key + " by job " + job_key ) ; new ReadLock ( job_key ) . invoke ( _key ) ; } } | Atomically get a read - lock on this preventing future deletes or updates |
22,514 | private boolean is_locked ( Key < Job > job_key ) { if ( _lockers == null ) return false ; for ( int i = ( _lockers . length == 1 ? 0 : 1 ) ; i < _lockers . length ; i ++ ) { Key k = _lockers [ i ] ; if ( job_key == k || ( job_key != null && k != null && job_key . equals ( k ) ) ) return true ; } return false ; } | Accessors for locking state . Minimal self - checking ; primitive results |
22,515 | public byte [ ] getBoosterBytes ( ) { final H2ONode boosterNode = getBoosterNode ( ) ; final byte [ ] boosterBytes ; if ( H2O . SELF . equals ( boosterNode ) ) { boosterBytes = XGBoost . getRawArray ( XGBoostUpdater . getUpdater ( _modelKey ) . getBooster ( ) ) ; } else { Log . debug ( "Booster will be retrieved from a remote node, node=" + boosterNode ) ; FetchBoosterTask t = new FetchBoosterTask ( _modelKey ) ; boosterBytes = new RPC < > ( boosterNode , t ) . call ( ) . get ( ) . _boosterBytes ; } return boosterBytes ; } | This is called from driver |
22,516 | public int [ ] diffCols ( int [ ] filterThese ) { HashSet < Integer > filter = new HashSet < > ( ) ; for ( int i : filterThese ) filter . add ( i ) ; ArrayList < Integer > res = new ArrayList < > ( ) ; for ( int i = 0 ; i < _cols . length ; ++ i ) { if ( _cols [ i ] . _ignored || _cols [ i ] . _response || filter . contains ( i ) ) continue ; res . add ( i ) ; } return intListToA ( res ) ; } | Get the non - ignored columns that are not in the filter ; do not include the response . |
22,517 | public long na_FeatureCount ( ) { if ( _featsWithNa != - 1 ) return _featsWithNa ; long cnt = 0 ; for ( int i = 0 ; i < _cols . length ; ++ i ) { if ( ! _cols [ i ] . _ignored && ! _cols [ i ] . _response && _cols [ i ] . _percentNA != 0 ) { cnt += 1 ; } } return ( _featsWithNa = cnt ) ; } | count of features with nas |
22,518 | public long rowsWithNa ( ) { if ( _rowsWithNa != - 1 ) return _rowsWithNa ; String x = String . format ( "(na.omit %s)" , _fr . _key ) ; Val res = Rapids . exec ( x ) ; Frame f = res . getFrame ( ) ; long cnt = _fr . numRows ( ) - f . numRows ( ) ; f . delete ( ) ; return ( _rowsWithNa = cnt ) ; } | count of rows with nas |
22,519 | public long nClass ( ) { if ( _nclass != - 1 ) return _nclass ; if ( _isClassification == true ) { long cnt = 0 ; cnt = _fr . vec ( _response ) . domain ( ) . length ; return ( _nclass = cnt ) ; } else { return ( _nclass = 0 ) ; } } | number of classes if classification problem |
22,520 | public boolean isAnyNumeric ( ) { int cnt = 0 ; for ( int i = 0 ; i < _cols . length ; ++ i ) { if ( ! _cols [ i ] . _ignored && ! _cols [ i ] . _response && _cols [ i ] . _isNumeric ) { cnt = 1 ; break ; } } if ( cnt == 1 ) return true ; else return false ; } | checks if there are any numeric features in the frame |
22,521 | public boolean isAnyCategorical ( ) { int cnt = 0 ; for ( int i = 0 ; i < _cols . length ; ++ i ) { if ( ! _cols [ i ] . _ignored && ! _cols [ i ] . _response && _cols [ i ] . _isCategorical ) { cnt = 1 ; break ; } } if ( cnt == 1 ) return true ; else return false ; } | checks if there are any categorical features in the frame |
22,522 | public FrameMetadata computeFrameMetaPass1 ( ) { MetaPass1 [ ] tasks = new MetaPass1 [ _fr . numCols ( ) ] ; for ( int i = 0 ; i < tasks . length ; ++ i ) tasks [ i ] = new MetaPass1 ( i , this ) ; _isClassification = tasks [ _response ] . _isClassification ; MetaCollector . ParallelTasks metaCollector = new MetaCollector . ParallelTasks < > ( tasks ) ; long start = System . currentTimeMillis ( ) ; H2O . submitTask ( metaCollector ) . join ( ) ; _userFeedback . info ( Stage . FeatureAnalysis , "Frame metadata analyzer pass 1 completed in " + ( System . currentTimeMillis ( ) - start ) / 1000. + " seconds" ) ; double sumTimeToMRTaskPerCol = 0 ; ArrayList < Integer > dropCols = new ArrayList < > ( ) ; for ( MetaPass1 cmt : tasks ) { if ( cmt . _colMeta . _ignored ) dropCols . add ( cmt . _colMeta . _idx ) ; else _cols [ cmt . _colMeta . _idx ] = cmt . _colMeta ; sumTimeToMRTaskPerCol += cmt . _elapsed ; } _userFeedback . info ( Stage . FeatureAnalysis , "Average time to analyze each column: " + String . format ( "%.5f" , ( sumTimeToMRTaskPerCol / tasks . length ) / 1000.0 ) + " seconds" ) ; if ( dropCols . size ( ) > 0 ) dropIgnoredCols ( intListToA ( dropCols ) ) ; return this ; } | blocking call to compute 1st pass of column metadata |
22,523 | public synchronized void setException ( Throwable ex ) { if ( _ex == null ) { _ex = AutoBuffer . javaSerializeWritePojo ( ( ( ex instanceof DistributedException ) ? ( DistributedException ) ex : new DistributedException ( ex , false ) ) ) ; } } | Capture the first exception in _ex . Later setException attempts are ignored . |
22,524 | @ SuppressWarnings ( "unused" ) public ModelMetricsListSchemaV3 delete ( int version , ModelMetricsListSchemaV3 s ) { ModelMetricsList m = s . createAndFillImpl ( ) ; s . fillFromImpl ( m . delete ( ) ) ; return s ; } | Delete one or more ModelMetrics . |
22,525 | @ SuppressWarnings ( "unused" ) public ModelMetricsMakerSchemaV3 make ( int version , ModelMetricsMakerSchemaV3 s ) { if ( null == s . predictions_frame ) throw new H2OIllegalArgumentException ( "predictions_frame" , "make" , s . predictions_frame ) ; Frame pred = DKV . getGet ( s . predictions_frame ) ; if ( null == pred ) throw new H2OKeyNotFoundArgumentException ( "predictions_frame" , "make" , s . predictions_frame ) ; if ( null == s . actuals_frame ) throw new H2OIllegalArgumentException ( "actuals_frame" , "make" , s . actuals_frame ) ; Frame act = DKV . getGet ( s . actuals_frame ) ; if ( null == act ) throw new H2OKeyNotFoundArgumentException ( "actuals_frame" , "make" , s . actuals_frame ) ; if ( s . domain == null ) { if ( pred . numCols ( ) != 1 ) { throw new H2OIllegalArgumentException ( "predictions_frame" , "make" , "For regression problems (domain=null), the predictions_frame must have exactly 1 column." ) ; } ModelMetricsRegression mm = ModelMetricsRegression . make ( pred . anyVec ( ) , act . anyVec ( ) , s . distribution ) ; s . model_metrics = new ModelMetricsRegressionV3 ( ) . fillFromImpl ( mm ) ; } else if ( s . domain . length == 2 ) { if ( pred . numCols ( ) != 1 ) { throw new H2OIllegalArgumentException ( "predictions_frame" , "make" , "For domains with 2 class labels, the predictions_frame must have exactly one column containing the class-1 probabilities." ) ; } ModelMetricsBinomial mm = ModelMetricsBinomial . make ( pred . anyVec ( ) , act . anyVec ( ) , s . domain ) ; s . model_metrics = new ModelMetricsBinomialV3 ( ) . fillFromImpl ( mm ) ; } else if ( s . domain . length > 2 ) { if ( pred . numCols ( ) != s . domain . length ) { throw new H2OIllegalArgumentException ( "predictions_frame" , "make" , "For domains with " + s . domain . length + " class labels, the predictions_frame must have exactly " + s . domain . length + " columns containing the class-probabilities." ) ; } if ( s . distribution == DistributionFamily . ordinal ) { ModelMetricsOrdinal mm = ModelMetricsOrdinal . make ( pred , act . anyVec ( ) , s . domain ) ; s . model_metrics = new ModelMetricsOrdinalV3 ( ) . fillFromImpl ( mm ) ; } else { ModelMetricsMultinomial mm = ModelMetricsMultinomial . make ( pred , act . anyVec ( ) , s . domain ) ; s . model_metrics = new ModelMetricsMultinomialV3 ( ) . fillFromImpl ( mm ) ; } } else { throw H2O . unimpl ( ) ; } return s ; } | Make a model metrics object from actual and predicted values |
22,526 | public void reduce ( JStackCollectorTask that ) { for ( int i = 0 ; i < _traces . length ; ++ i ) if ( _traces [ i ] == null ) _traces [ i ] = that . _traces [ i ] ; } | One per Node |
22,527 | private int isH2OHTTPRequestThread ( StackTraceElement [ ] elms ) { for ( int i = 0 ; i < elms . length ; ++ i ) if ( elms [ i ] . getClassName ( ) . equals ( "....JettyHTTPD$H2oDefaultServlet" ) ) return i ; return elms . length ; } | bruteforce search for H2O Servlet don t call until other obvious cases were filtered out |
22,528 | public static AstNumList check ( long dstX , AstRoot ast ) { AstNumList dim ; if ( ast instanceof AstNumList ) dim = ( AstNumList ) ast ; else if ( ast instanceof AstNum ) dim = new AstNumList ( ( ( AstNum ) ast ) . getNum ( ) ) ; else throw new IllegalArgumentException ( "Requires a number-list, but found a " + ast . getClass ( ) ) ; if ( dim . isEmpty ( ) ) return dim ; for ( int col : dim . expand4 ( ) ) if ( ! ( 0 <= col && col < dstX ) ) throw new IllegalArgumentException ( "Selection must be an integer from 0 to " + dstX ) ; return dim ; } | Argument check helper |
22,529 | public static IcedHashMap < G , String > doGroups ( Frame fr , int [ ] gbCols , AGG [ ] aggs ) { return doGroups ( fr , gbCols , aggs , false ) ; } | results using aggs . Return an array of groups with the aggregate results . |
22,530 | public static Frame buildOutput ( int [ ] gbCols , int noutCols , Frame fr , String [ ] fcnames , int ngrps , MRTask mrfill ) { final int nCols = gbCols . length + noutCols ; String [ ] names = new String [ nCols ] ; String [ ] [ ] domains = new String [ nCols ] [ ] ; byte [ ] types = new byte [ nCols ] ; for ( int i = 0 ; i < gbCols . length ; i ++ ) { names [ i ] = fr . name ( gbCols [ i ] ) ; domains [ i ] = fr . domains ( ) [ gbCols [ i ] ] ; types [ i ] = fr . vec ( names [ i ] ) . get_type ( ) ; } for ( int i = 0 ; i < fcnames . length ; i ++ ) { names [ i + gbCols . length ] = fcnames [ i ] ; types [ i + gbCols . length ] = Vec . T_NUM ; } Vec v = Vec . makeZero ( ngrps ) ; Frame f = mrfill . doAll ( types , new Frame ( v ) ) . outputFrame ( names , domains ) ; v . remove ( ) ; return f ; } | Build output frame from the multi - column results |
22,531 | public long numericChunkRollup ( Chunk c , long start , long checksum ) { long pinfs = 0 , ninfs = 0 , naCnt = 0 , nzCnt = 0 ; boolean isInt = _rs . _isInt ; boolean hasNA = c . hasNA ( ) ; boolean hasFloat = c . hasFloat ( ) ; double dmin = _rs . _mins [ _rs . _mins . length - 1 ] ; double dmax = _rs . _maxs [ _rs . _maxs . length - 1 ] ; assert ( _rs . _pinfs == 0 ) ; assert ( _rs . _ninfs == 0 ) ; assert ( _rs . _naCnt == 0 ) ; assert ( _rs . _nzCnt == 0 ) ; assert ( dmin == Double . MAX_VALUE ) ; assert ( dmax == - Double . MAX_VALUE ) ; long rows = 0 ; double mean = 0 ; double M2 = 0 ; for ( int i = c . nextNZ ( - 1 ) ; i < c . _len ; i = c . nextNZ ( i ) ) { if ( hasNA && c . isNA ( i ) ) naCnt ++ ; else { double x = c . atd ( i ) ; long l = hasFloat ? Double . doubleToRawLongBits ( x ) : c . at8 ( i ) ; if ( l != 0 ) checksum ^= ( 17 * ( start + i ) ) ^ 23 * l ; if ( x == Double . POSITIVE_INFINITY ) pinfs ++ ; else if ( x == Double . NEGATIVE_INFINITY ) ninfs ++ ; else { if ( x != 0 ) nzCnt ++ ; if ( x < dmin ) dmin = _rs . min ( x ) ; if ( x > dmax ) dmax = _rs . max ( x ) ; if ( isInt ) isInt = ( long ) x == x ; rows ++ ; double delta = x - mean ; mean += delta / rows ; M2 += delta * ( x - mean ) ; } } } _rs . _pinfs = pinfs ; _rs . _ninfs = ninfs ; _rs . _naCnt = naCnt ; _rs . _nzCnt = nzCnt ; _rs . _rows += rows ; _rs . _isInt = isInt ; _rs . _mean = mean ; _rs . _sigma = M2 ; return checksum ; } | MASTER TEMPLATE - All methods below are COPY & PASTED from this template and some optimizations are performed based on the chunk types |
22,532 | @ SuppressWarnings ( "unused" ) public JobsV3 list ( int version , JobsV3 s ) { Job [ ] jobs = Job . jobs ( ) ; s . jobs = new JobV3 [ jobs . length ] ; int i = 0 ; for ( Job j : jobs ) { try { s . jobs [ i ] = ( JobV3 ) SchemaServer . schema ( version , j ) . fillFromImpl ( j ) ; } catch ( H2ONotFoundArgumentException e ) { s . jobs [ i ] = new JobV3 ( ) . fillFromImpl ( j ) ; } i ++ ; } return s ; } | Impl class for a collection of jobs ; only used in the API to make it easier to cons up the jobs array via the magic of PojoUtils . copyProperties . |
22,533 | public Chunk chunkForChunkIdx ( int cidx ) { Chunk crows = rows ( ) . chunkForChunkIdx ( cidx ) ; return new SubsetChunk ( crows , this , masterVec ( ) ) ; } | A subset chunk |
22,534 | public static Key encodeKey ( String bucket , String key ) { Key res = encodeKeyImpl ( bucket , key ) ; return res ; } | Creates the key for given S3 bucket and key . Returns the H2O key or null if the key cannot be created . |
22,535 | private static String [ ] decodePath ( String s ) { assert s . startsWith ( KEY_PREFIX ) && s . indexOf ( '/' ) >= 0 : "Attempting to decode non s3 key: " + s ; s = s . substring ( KEY_PREFIX_LEN ) ; int dlm = s . indexOf ( '/' ) ; if ( dlm < 0 ) return new String [ ] { s , null } ; String bucket = s . substring ( 0 , dlm ) ; String key = s . substring ( dlm + 1 ) ; return new String [ ] { bucket , key } ; } | Decompose S3 name into bucket name and key name |
22,536 | private static S3Object getObjectForKey ( Key k , long offset , long length ) throws IOException { String [ ] bk = decodeKey ( k ) ; GetObjectRequest r = new GetObjectRequest ( bk [ 0 ] , bk [ 1 ] ) ; r . setRange ( offset , offset + length - 1 ) ; return getClient ( ) . getObject ( r ) ; } | Gets the S3 object associated with the key that can read length bytes from offset |
22,537 | private static ObjectMetadata getObjectMetadataForKey ( Key k ) { String [ ] bk = decodeKey ( k ) ; assert ( bk . length == 2 ) ; return getClient ( ) . getObjectMetadata ( bk [ 0 ] , bk [ 1 ] ) ; } | Gets the object metadata associated with given key . |
22,538 | private void leaf2 ( int mask ) throws T { assert ( mask == 0 || ( ( mask & 16 ) == 16 && ( mask & 32 ) == 32 ) ) : "Unknown mask: " + mask ; leaf ( _ts . get4f ( ) ) ; } | Call either the single - class leaf or the full - prediction leaf |
22,539 | public byte [ ] getPreviewChunkBytes ( int chkIdx ) { if ( chkIdx >= nChunks ( ) ) throw new H2OIllegalArgumentException ( "Asked for chunk index beyond the number of chunks." ) ; if ( chkIdx == 0 ) return chunkForChunkIdx ( chkIdx ) . _mem ; else { byte [ ] mem = chunkForChunkIdx ( chkIdx ) . _mem ; int i = 0 , j = mem . length - 1 ; while ( i < mem . length && mem [ i ] != CHAR_CR && mem [ i ] != CHAR_LF ) i ++ ; while ( j > i && mem [ j ] != CHAR_CR && mem [ j ] != CHAR_LF ) j -- ; if ( j - i > 1 ) return Arrays . copyOfRange ( mem , i , j ) ; else return null ; } } | Get all the bytes of a given chunk . Useful for previewing sections of files . |
22,540 | void checkRecallValidity ( ) { double x0 = recall . exec ( this , 0 ) ; for ( int i = 1 ; i < _nBins ; i ++ ) { double x1 = recall . exec ( this , i ) ; if ( x0 > x1 ) throw new H2OIllegalArgumentException ( String . valueOf ( i ) , "recall" , x0 + " > " + x1 ) ; x0 = x1 ; } } | Checks that recall is a non - decreasing function |
22,541 | private double compute_auc ( ) { if ( _fps [ _nBins - 1 ] == 0 ) return 1.0 ; if ( _tps [ _nBins - 1 ] == 0 ) return 0.0 ; double tp0 = 0 , fp0 = 0 ; double area = 0 ; for ( int i = 0 ; i < _nBins ; i ++ ) { area += ( _fps [ i ] - fp0 ) * ( _tps [ i ] + tp0 ) / 2.0 ; tp0 = _tps [ i ] ; fp0 = _fps [ i ] ; } return area / _p / _n ; } | points . TPR and FPR are monotonically increasing from 0 to 1 . |
22,542 | public double [ ] [ ] buildCM ( int idx ) { return new double [ ] [ ] { { tn ( idx ) , fp ( idx ) } , { fn ( idx ) , tp ( idx ) } } ; } | Build a CM for a threshold index . - typed as doubles because of double observation weights |
22,543 | public static Frame parseFrame ( Key okey , URI ... uris ) throws IOException { return parseFrame ( okey , null , uris ) ; } | Parse given set of URIs and produce a frame s key representing output . |
22,544 | public SharedTreeGraph _computeGraph ( int treeToPrint ) { SharedTreeGraph g = new SharedTreeGraph ( ) ; if ( treeToPrint >= _ntree_groups ) { throw new IllegalArgumentException ( "Tree " + treeToPrint + " does not exist (max " + _ntree_groups + ")" ) ; } int j ; if ( treeToPrint >= 0 ) { j = treeToPrint ; } else { j = 0 ; } for ( ; j < _ntree_groups ; j ++ ) { for ( int i = 0 ; i < _ntrees_per_group ; i ++ ) { int itree = treeIndex ( j , i ) ; String [ ] domainValues = isSupervised ( ) ? getDomainValues ( getResponseIdx ( ) ) : null ; String treeName = treeName ( j , i , domainValues ) ; SharedTreeSubgraph sg = g . makeSubgraph ( treeName ) ; computeTreeGraph ( sg , _compressed_trees [ itree ] , _compressed_trees_aux [ itree ] , getNames ( ) , getDomainValues ( ) ) ; } if ( treeToPrint >= 0 ) { break ; } } return g ; } | Compute a graph of the forest . |
22,545 | protected void scoreAllTrees ( double [ ] row , double [ ] preds ) { java . util . Arrays . fill ( preds , 0 ) ; scoreTreeRange ( row , 0 , _ntree_groups , preds ) ; } | Score all trees and fill in the preds array . |
22,546 | @ SuppressWarnings ( "ConstantConditions" ) public static double scoreTree0 ( byte [ ] tree , double [ ] row , boolean computeLeafAssignment ) { ByteBufferWrapper ab = new ByteBufferWrapper ( tree ) ; GenmodelBitSet bs = null ; long bitsRight = 0 ; int level = 0 ; while ( true ) { int nodeType = ab . get1U ( ) ; int colId = ab . get2 ( ) ; if ( colId == 65535 ) return ab . get4f ( ) ; int naSplitDir = ab . get1U ( ) ; boolean naVsRest = naSplitDir == NsdNaVsRest ; boolean leftward = naSplitDir == NsdNaLeft || naSplitDir == NsdLeft ; int lmask = ( nodeType & 51 ) ; int equal = ( nodeType & 12 ) ; assert equal != 4 ; float splitVal = - 1 ; if ( ! naVsRest ) { if ( equal == 0 ) { splitVal = ab . get4f ( ) ; } else { if ( bs == null ) bs = new GenmodelBitSet ( 0 ) ; if ( equal == 8 ) bs . fill2 ( tree , ab ) ; else bs . fill3_1 ( tree , ab ) ; } } double d = row [ colId ] ; if ( Double . isNaN ( d ) ? ! leftward : ! naVsRest && ( equal == 0 ? d >= splitVal : bs . contains0 ( ( int ) d ) ) ) { switch ( lmask ) { case 0 : ab . skip ( ab . get1U ( ) ) ; break ; case 1 : ab . skip ( ab . get2 ( ) ) ; break ; case 2 : ab . skip ( ab . get3 ( ) ) ; break ; case 3 : ab . skip ( ab . get4 ( ) ) ; break ; case 48 : ab . skip ( 4 ) ; break ; default : assert false : "illegal lmask value " + lmask + " in tree " + Arrays . toString ( tree ) ; } if ( computeLeafAssignment && level < 64 ) bitsRight |= 1 << level ; lmask = ( nodeType & 0xC0 ) >> 2 ; } else { if ( lmask <= 3 ) ab . skip ( lmask + 1 ) ; } level ++ ; if ( ( lmask & 16 ) != 0 ) { if ( computeLeafAssignment ) { bitsRight |= 1 << level ; return Double . longBitsToDouble ( bitsRight ) ; } else { return ab . get4f ( ) ; } } } } | SET IN STONE FOR MOJO VERSION 1 . 00 - DO NOT CHANGE |
22,547 | public AbstractPrediction predict ( RowData data , ModelCategory mc ) throws PredictException { switch ( mc ) { case AutoEncoder : return predictAutoEncoder ( data ) ; case Binomial : return predictBinomial ( data ) ; case Multinomial : return predictMultinomial ( data ) ; case Ordinal : return predictOrdinal ( data ) ; case Clustering : return predictClustering ( data ) ; case Regression : return predictRegression ( data ) ; case DimReduction : return predictDimReduction ( data ) ; case WordEmbedding : return predictWord2Vec ( data ) ; case AnomalyDetection : return predictAnomalyDetection ( data ) ; case Unknown : throw new PredictException ( "Unknown model category" ) ; default : throw new PredictException ( "Unhandled model category (" + m . getModelCategory ( ) + ") in switch statement" ) ; } } | Make a prediction on a new data point . |
22,548 | public AutoEncoderModelPrediction predictAutoEncoder ( RowData data ) throws PredictException { validateModelCategory ( ModelCategory . AutoEncoder ) ; int size = m . getPredsSize ( ModelCategory . AutoEncoder ) ; double [ ] output = new double [ size ] ; double [ ] rawData = nanArray ( m . nfeatures ( ) ) ; rawData = fillRawData ( data , rawData ) ; output = m . score0 ( rawData , output ) ; AutoEncoderModelPrediction p = new AutoEncoderModelPrediction ( ) ; p . original = expandRawData ( rawData , output . length ) ; p . reconstructed = output ; p . reconstructedRowData = reconstructedToRowData ( output ) ; if ( m instanceof DeeplearningMojoModel ) { DeeplearningMojoModel mojoModel = ( ( DeeplearningMojoModel ) m ) ; p . mse = mojoModel . calculateReconstructionErrorPerRowData ( p . original , p . reconstructed ) ; } return p ; } | Make a prediction on a new data point using an AutoEncoder model . |
22,549 | private double [ ] expandRawData ( double [ ] data , int size ) { double [ ] expanded = new double [ size ] ; int pos = 0 ; for ( int i = 0 ; i < data . length ; i ++ ) { if ( m . _domains [ i ] == null ) { expanded [ pos ] = data [ i ] ; pos ++ ; } else { int idx = Double . isNaN ( data [ i ] ) ? m . _domains [ i ] . length : ( int ) data [ i ] ; expanded [ pos + idx ] = 1.0 ; pos += m . _domains [ i ] . length + 1 ; } } return expanded ; } | Creates a 1 - hot encoded representation of the input data . |
22,550 | private RowData reconstructedToRowData ( double [ ] reconstructed ) { RowData rd = new RowData ( ) ; int pos = 0 ; for ( int i = 0 ; i < m . nfeatures ( ) ; i ++ ) { Object value ; if ( m . _domains [ i ] == null ) { value = reconstructed [ pos ++ ] ; } else { value = catValuesAsMap ( m . _domains [ i ] , reconstructed , pos ) ; pos += m . _domains [ i ] . length + 1 ; } rd . put ( m . _names [ i ] , value ) ; } return rd ; } | Converts output of AutoEncoder to a RowData structure . Categorical fields are represented by a map of domain values - > reconstructed values missing domain value is represented by a null key |
22,551 | public MultinomialModelPrediction predictMultinomial ( RowData data , double offset ) throws PredictException { double [ ] preds = preamble ( ModelCategory . Multinomial , data , offset ) ; MultinomialModelPrediction p = new MultinomialModelPrediction ( ) ; if ( enableLeafAssignment ) { SharedTreeMojoModel . LeafNodeAssignments assignments = leafNodeAssignmentExtended ( data ) ; p . leafNodeAssignments = assignments . _paths ; p . leafNodeAssignmentIds = assignments . _nodeIds ; } p . classProbabilities = new double [ m . getNumResponseClasses ( ) ] ; p . labelIndex = ( int ) preds [ 0 ] ; String [ ] domainValues = m . getDomainValues ( m . getResponseIdx ( ) ) ; p . label = domainValues [ p . labelIndex ] ; System . arraycopy ( preds , 1 , p . classProbabilities , 0 , p . classProbabilities . length ) ; if ( enableStagedProbabilities ) { double [ ] rawData = nanArray ( m . nfeatures ( ) ) ; rawData = fillRawData ( data , rawData ) ; p . stageProbabilities = ( ( SharedTreeMojoModel ) m ) . scoreStagedPredictions ( rawData , preds . length ) ; } return p ; } | Make a prediction on a new data point using a Multinomial model . |
22,552 | public OrdinalModelPrediction predictOrdinal ( RowData data , double offset ) throws PredictException { double [ ] preds = preamble ( ModelCategory . Ordinal , data , offset ) ; OrdinalModelPrediction p = new OrdinalModelPrediction ( ) ; p . classProbabilities = new double [ m . getNumResponseClasses ( ) ] ; p . labelIndex = ( int ) preds [ 0 ] ; String [ ] domainValues = m . getDomainValues ( m . getResponseIdx ( ) ) ; p . label = domainValues [ p . labelIndex ] ; System . arraycopy ( preds , 1 , p . classProbabilities , 0 , p . classProbabilities . length ) ; return p ; } | Make a prediction on a new data point using a Ordinal model . |
22,553 | private SortedClassProbability [ ] sortByDescendingClassProbability ( String [ ] domainValues , double [ ] classProbabilities ) { assert ( classProbabilities . length == domainValues . length ) ; SortedClassProbability [ ] arr = new SortedClassProbability [ domainValues . length ] ; for ( int i = 0 ; i < domainValues . length ; i ++ ) { arr [ i ] = new SortedClassProbability ( ) ; arr [ i ] . name = domainValues [ i ] ; arr [ i ] . probability = classProbabilities [ i ] ; } Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; return arr ; } | Sort in descending order . |
22,554 | public SortedClassProbability [ ] sortByDescendingClassProbability ( BinomialModelPrediction p ) { String [ ] domainValues = m . getDomainValues ( m . getResponseIdx ( ) ) ; double [ ] classProbabilities = p . classProbabilities ; return sortByDescendingClassProbability ( domainValues , classProbabilities ) ; } | A helper function to return an array of binomial class probabilities for a prediction in sorted order . The returned array has the most probable class in position 0 . |
22,555 | public ClusteringModelPrediction predictClustering ( RowData data ) throws PredictException { ClusteringModelPrediction p = new ClusteringModelPrediction ( ) ; if ( useExtendedOutput && ( m instanceof IClusteringModel ) ) { IClusteringModel cm = ( IClusteringModel ) m ; double [ ] rawData = nanArray ( m . nfeatures ( ) ) ; rawData = fillRawData ( data , rawData ) ; final int k = cm . getNumClusters ( ) ; p . distances = new double [ k ] ; p . cluster = cm . distances ( rawData , p . distances ) ; } else { double [ ] preds = preamble ( ModelCategory . Clustering , data ) ; p . cluster = ( int ) preds [ 0 ] ; } return p ; } | Make a prediction on a new data point using a Clustering model . |
22,556 | public RegressionModelPrediction predictRegression ( RowData data , double offset ) throws PredictException { double [ ] preds = preamble ( ModelCategory . Regression , data , offset ) ; RegressionModelPrediction p = new RegressionModelPrediction ( ) ; if ( enableLeafAssignment ) { SharedTreeMojoModel . LeafNodeAssignments assignments = leafNodeAssignmentExtended ( data ) ; p . leafNodeAssignments = assignments . _paths ; p . leafNodeAssignmentIds = assignments . _nodeIds ; } p . value = preds [ 0 ] ; if ( enableStagedProbabilities ) { double [ ] rawData = nanArray ( m . nfeatures ( ) ) ; rawData = fillRawData ( data , rawData ) ; p . stageProbabilities = ( ( SharedTreeMojoModel ) m ) . scoreStagedPredictions ( rawData , preds . length ) ; } if ( enableContributions ) { double [ ] rawData = nanArray ( m . nfeatures ( ) ) ; rawData = fillRawData ( data , rawData ) ; p . contributions = predictContributions . calculateContributions ( rawData ) ; } return p ; } | Make a prediction on a new data point using a Regression model . |
22,557 | public static boolean haveBackend ( ) { for ( DeepWaterParameters . Backend b : DeepWaterParameters . Backend . values ( ) ) { if ( DeepwaterMojoModel . createDeepWaterBackend ( b . toString ( ) ) != null ) return true ; } return false ; } | Check whether we have any Deep Water native backends available |
22,558 | @ SuppressWarnings ( "unused" ) public ModelsV3 list ( int version , ModelsV3 s ) { Models m = s . createAndFillImpl ( ) ; m . models = Model . fetchAll ( ) ; return ( ModelsV3 ) s . fillFromImplWithSynopsis ( m ) ; } | Return all the models . |
22,559 | @ SuppressWarnings ( "unused" ) public ModelsV3 delete ( int version , ModelsV3 s ) { Model model = getFromDKV ( "key" , s . model_id . key ( ) ) ; model . delete ( ) ; return s ; } | Remove an unlocked model . Fails if model is in - use . |
22,560 | protected Iterable < String > readtext ( String name , boolean unescapeNewlines ) throws IOException { ArrayList < String > res = new ArrayList < > ( 50 ) ; BufferedReader br = _reader . getTextFile ( name ) ; try { String line ; while ( true ) { line = br . readLine ( ) ; if ( line == null ) break ; if ( unescapeNewlines ) line = StringEscapeUtils . unescapeNewlines ( line ) ; res . add ( line . trim ( ) ) ; } br . close ( ) ; } finally { try { br . close ( ) ; } catch ( IOException e ) { } } return res ; } | Retrieve text previously saved using startWritingTextFile + writeln as an array of lines . Each line is trimmed to remove the leading and trailing whitespace . Removes escaping of the new line characters in enabled . |
22,561 | public static ByteChannel getConnection ( String h2oNodeHostname , int h2oNodeApiPort , short nodeTimeStamp ) throws IOException { SocketChannelFactory socketFactory = SocketChannelFactory . instance ( H2OSecurityManager . instance ( ) ) ; return H2ONode . openChan ( TCPReceiverThread . TCP_EXTERNAL , socketFactory , h2oNodeHostname , h2oNodeApiPort + 1 , nodeTimeStamp ) ; } | Get connection to a specific h2o node . The caller of this method is usually non - H2O node who wants to read H2O frames or write to H2O frames from non - H2O environment such as Spark executor . This node usually does not have H2O running . |
22,562 | private static void putMarkerAndSend ( AutoBuffer ab , ByteChannel channel , long data ) throws IOException { if ( data == NUM_MARKER_NEXT_BYTE_FOLLOWS ) { ab . put1 ( MARKER_ORIGINAL_VALUE ) ; } writeToChannel ( ab , channel ) ; } | Sends another byte as a marker if it s needed and send the data |
22,563 | public void doIt ( ) { if ( nodeidx == - 1 ) { GetLogsTask t = new GetLogsTask ( ) ; t . doIt ( ) ; bytes = t . _bytes ; } else { H2ONode node = H2O . CLOUD . _memary [ nodeidx ] ; GetLogsTask t = new GetLogsTask ( ) ; Log . trace ( "GetLogsTask starting to node " + nodeidx + "..." ) ; new RPC < > ( node , t ) . call ( ) . get ( ) ; Log . trace ( "GetLogsTask completed to node " + nodeidx ) ; bytes = t . _bytes ; } } | Do the work . |
22,564 | public SharedTreeNode makeRootNode ( ) { assert nodesArray . size ( ) == 0 ; SharedTreeNode n = new SharedTreeNode ( 0 , null , subgraphNumber , 0 ) ; n . setInclusiveNa ( true ) ; nodesArray . add ( n ) ; rootNode = n ; return n ; } | Make the root node in the tree . |
22,565 | public SharedTreeNode makeLeftChildNode ( SharedTreeNode parent ) { SharedTreeNode child = new SharedTreeNode ( nodesArray . size ( ) , parent , subgraphNumber , parent . getDepth ( ) + 1 ) ; nodesArray . add ( child ) ; makeLeftEdge ( parent , child ) ; return child ; } | Make the left child of a node . |
22,566 | public SharedTreeNode makeRightChildNode ( SharedTreeNode parent ) { SharedTreeNode child = new SharedTreeNode ( nodesArray . size ( ) , parent , subgraphNumber , parent . getDepth ( ) + 1 ) ; nodesArray . add ( child ) ; makeRightEdge ( parent , child ) ; return child ; } | Make the right child of a node . |
22,567 | public static Table extractTableFromJson ( final JsonObject modelJson , final String tablePath ) { Objects . requireNonNull ( modelJson ) ; JsonElement potentialTableJson = findInJson ( modelJson , tablePath ) ; if ( potentialTableJson . isJsonNull ( ) ) { System . out . println ( String . format ( "Failed to extract element '%s' MojoModel dump." , tablePath ) ) ; return null ; } final JsonObject tableJson = potentialTableJson . getAsJsonObject ( ) ; final int rowCount = tableJson . get ( "rowcount" ) . getAsInt ( ) ; final String [ ] columnHeaders ; final Table . ColumnType [ ] columnTypes ; final Object [ ] [ ] data ; final JsonArray columns = findInJson ( tableJson , "columns" ) . getAsJsonArray ( ) ; final int columnCount = columns . size ( ) ; columnHeaders = new String [ columnCount ] ; columnTypes = new Table . ColumnType [ columnCount ] ; for ( int i = 0 ; i < columnCount ; i ++ ) { final JsonObject column = columns . get ( i ) . getAsJsonObject ( ) ; columnHeaders [ i ] = column . get ( "description" ) . getAsString ( ) ; columnTypes [ i ] = Table . ColumnType . extractType ( column . get ( "type" ) . getAsString ( ) ) ; } JsonArray dataColumns = findInJson ( tableJson , "data" ) . getAsJsonArray ( ) ; data = new Object [ columnCount ] [ rowCount ] ; for ( int i = 0 ; i < columnCount ; i ++ ) { JsonArray column = dataColumns . get ( i ) . getAsJsonArray ( ) ; for ( int j = 0 ; j < rowCount ; j ++ ) { final JsonPrimitive primitiveValue = column . get ( j ) . getAsJsonPrimitive ( ) ; switch ( columnTypes [ i ] ) { case LONG : data [ i ] [ j ] = primitiveValue . getAsLong ( ) ; break ; case DOUBLE : data [ i ] [ j ] = primitiveValue . getAsDouble ( ) ; break ; case STRING : data [ i ] [ j ] = primitiveValue . getAsString ( ) ; break ; } } } return new Table ( tableJson . get ( "name" ) . getAsString ( ) , tableJson . get ( "description" ) . getAsString ( ) , new String [ rowCount ] , columnHeaders , columnTypes , "" , data ) ; } | Extracts a Table from H2O s model serialized into JSON . |
22,568 | private static JsonElement findInJson ( JsonElement jsonElement , String jsonPath ) { final String [ ] route = JSON_PATH_PATTERN . split ( jsonPath ) ; JsonElement result = jsonElement ; for ( String key : route ) { key = key . trim ( ) ; if ( key . isEmpty ( ) ) continue ; if ( result == null ) { result = JsonNull . INSTANCE ; break ; } if ( result . isJsonObject ( ) ) { result = ( ( JsonObject ) result ) . get ( key ) ; } else if ( result . isJsonArray ( ) ) { int value = Integer . valueOf ( key ) - 1 ; result = ( ( JsonArray ) result ) . get ( value ) ; } else break ; } return result ; } | Finds an element in GSON s JSON document representation |
22,569 | static public < T extends Iced > T deepCopy ( T iced ) { if ( iced == null ) return null ; AutoBuffer ab = new AutoBuffer ( ) ; iced . write ( ab ) ; ab . flipForReading ( ) ; return ( T ) TypeMap . newInstance ( iced . frozenType ( ) ) . read ( ab ) ; } | Deep - copy clone given iced object . |
22,570 | public final void sendMessage ( ByteBuffer bb , byte msg_priority ) { UDP_TCP_SendThread sendThread = _sendThread ; if ( sendThread == null ) { if ( _removed_from_cloud ) { Log . warn ( "Node " + this + " is not active in the cloud anymore but we want to communicate with it." + "Re-opening the communication channel." ) ; } sendThread = startSendThread ( ) ; } assert sendThread != null ; sendThread . sendMessage ( bb , msg_priority ) ; } | null if Node was removed from cloud or we didn t need to communicate with it yet |
22,571 | RPC . RPCCall record_task ( RPC . RPCCall rpc ) { final RPC . RPCCall x = _work . putIfAbsent ( rpc . _tsknum , rpc ) ; if ( x != null ) return x ; if ( rpc . _tsknum > _removed_task_ids . get ( ) ) return null ; _work . remove ( rpc . _tsknum ) ; return _removed_task ; } | also ACKACK d . |
22,572 | synchronized List < AstPrimitive > getAllPrims ( ) { List < AstPrimitive > prims = new ArrayList < > ( ) ; for ( AstPrimitive prim : _loader ) { prims . add ( prim ) ; } return prims ; } | Locates all available non - core primitives of the Rapid language . |
22,573 | public static AstRoot parse ( String rapids ) { Rapids r = new Rapids ( rapids ) ; AstRoot res = r . parseNext ( ) ; if ( r . skipWS ( ) != ' ' ) throw new IllegalASTException ( "Syntax error: illegal Rapids expression `" + rapids + "`" ) ; return res ; } | Parse a Rapids expression string into an Abstract Syntax Tree object . |
22,574 | public static Val exec ( String rapids ) { Session session = new Session ( ) ; try { H2O . incrementActiveRapidsCounter ( ) ; AstRoot ast = Rapids . parse ( rapids ) ; Val val = session . exec ( ast , null ) ; return session . end ( val ) ; } catch ( Throwable ex ) { throw session . endQuietly ( ex ) ; } finally { H2O . decrementActiveRapidsCounter ( ) ; } } | Execute a single rapids call in a short - lived session |
22,575 | private AstStrList parseStringList ( ) { ArrayList < String > strs = new ArrayList < > ( 10 ) ; while ( isQuote ( skipWS ( ) ) ) { strs . add ( string ( ) ) ; if ( skipWS ( ) == ',' ) eatChar ( ',' ) ; } return new AstStrList ( strs ) ; } | Parse a list of strings . Strings can be either in single - or in double quotes . |
22,576 | private char skipWS ( ) { char c = ' ' ; while ( _x < _str . length ( ) && isWS ( c = peek ( 0 ) ) ) _x ++ ; return c ; } | Advance parse pointer to the first non - whitespace character and return that character . If such non - whitespace character cannot be found then return . |
22,577 | private String string ( ) { char quote = peek ( 0 ) ; int start = ++ _x ; boolean has_escapes = false ; while ( _x < _str . length ( ) ) { char c = peek ( 0 ) ; if ( c == '\\' ) { has_escapes = true ; char cc = peek ( 1 ) ; if ( simpleEscapeSequences . containsKey ( cc ) ) { _x += 2 ; } else if ( cc == 'x' ) { _x += 4 ; } else if ( cc == 'u' ) { _x += 6 ; } else if ( cc == 'U' ) { _x += 10 ; } else throw new IllegalASTException ( "Invalid escape sequence \\" + cc ) ; } else if ( c == quote ) { _x ++ ; if ( has_escapes ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = start ; i < _x - 1 ; i ++ ) { char ch = _str . charAt ( i ) ; if ( ch == '\\' ) { char cc = _str . charAt ( ++ i ) ; if ( simpleEscapeSequences . containsKey ( cc ) ) { sb . append ( simpleEscapeSequences . get ( cc ) ) ; } else { int n = ( cc == 'x' ) ? 2 : ( cc == 'u' ) ? 4 : ( cc == 'U' ) ? 8 : - 1 ; int hex = - 1 ; try { hex = StringUtils . unhex ( _str . substring ( i + 1 , i + 1 + n ) ) ; } catch ( NumberFormatException e ) { throw new IllegalASTException ( e . toString ( ) ) ; } if ( hex > 0x10FFFF ) throw new IllegalASTException ( "Illegal unicode codepoint " + hex ) ; sb . append ( Character . toChars ( hex ) ) ; i += n ; } } else { sb . append ( ch ) ; } } return sb . toString ( ) ; } else { return _str . substring ( start , _x - 1 ) ; } } else { _x ++ ; } } throw new IllegalASTException ( "Unterminated string at " + start ) ; } | Parse a string from the token stream . |
22,578 | private static String key2Str_impl ( Key k ) { StringBuilder sb = new StringBuilder ( k . _kb . length / 2 + 4 ) ; int i = 0 ; if ( k . _kb [ 0 ] < 32 ) { sb . append ( '%' ) ; int j = k . _kb . length - 1 ; while ( j >= 0 && k . _kb [ j ] >= 32 && k . _kb [ j ] < 128 ) j -- ; for ( ; i <= j ; i ++ ) { byte b = k . _kb [ i ] ; int nib0 = ( ( b >>> 4 ) & 15 ) + '0' ; if ( nib0 > '9' ) nib0 += 'A' - 10 - '0' ; int nib1 = ( ( b >>> 0 ) & 15 ) + '0' ; if ( nib1 > '9' ) nib1 += 'A' - 10 - '0' ; sb . append ( ( char ) nib0 ) . append ( ( char ) nib1 ) ; } sb . append ( '%' ) ; } return escapeBytes ( k . _kb , i , sb ) . toString ( ) ; } | Convert a Key to a suitable filename string |
22,579 | private static Key str2Key_impl ( String s ) { String key = s ; byte [ ] kb = new byte [ ( key . length ( ) - 1 ) / 2 ] ; int i = 0 , j = 0 ; if ( ( key . length ( ) > 2 ) && ( key . charAt ( 0 ) == '%' ) && ( key . charAt ( 1 ) >= '0' ) && ( key . charAt ( 1 ) <= '9' ) ) { for ( i = 1 ; i < key . length ( ) ; i += 2 ) { if ( key . charAt ( i ) == '%' ) break ; char b0 = ( char ) ( key . charAt ( i ) - '0' ) ; if ( b0 > 9 ) b0 += '0' + 10 - 'A' ; char b1 = ( char ) ( key . charAt ( i + 1 ) - '0' ) ; if ( b1 > 9 ) b1 += '0' + 10 - 'A' ; kb [ j ++ ] = ( byte ) ( ( b0 << 4 ) | b1 ) ; } i ++ ; } for ( ; i < key . length ( ) ; ++ i ) { byte b = ( byte ) key . charAt ( i ) ; if ( b == '%' ) { switch ( key . charAt ( ++ i ) ) { case '%' : b = '%' ; break ; case 'c' : b = ':' ; break ; case 'd' : b = '.' ; break ; case 'g' : b = '>' ; break ; case 'l' : b = '<' ; break ; case 'q' : b = '"' ; break ; case 's' : b = '/' ; break ; case 'b' : b = '\\' ; break ; case 'z' : b = '\0' ; break ; default : Log . warn ( "Invalid format of filename " + s + " at index " + i ) ; } } if ( j >= kb . length ) kb = Arrays . copyOf ( kb , Math . max ( 2 , j * 2 ) ) ; kb [ j ++ ] = b ; } return Key . make ( Arrays . copyOf ( kb , j ) ) ; } | Convert a filename string to a Key |
22,580 | public int [ ] columns ( String [ ] names ) { int [ ] idxs = new int [ _strs . length ] ; for ( int i = 0 ; i < _strs . length ; i ++ ) { int idx = idxs [ i ] = water . util . ArrayUtils . find ( names , _strs [ i ] ) ; if ( idx == - 1 ) throw new IllegalArgumentException ( "Column " + _strs [ i ] + " not found" ) ; } return idxs ; } | Select columns by number or String . |
22,581 | protected double [ ] score0 ( double [ ] data , double [ ] preds ) { float [ ] f = new float [ _parms . _mini_batch_size * data . length ] ; for ( int i = 0 ; i < data . length ; ++ i ) f [ i ] = ( float ) data [ i ] ; float [ ] predFloats = model_info . _backend . predict ( model_info . getModel ( ) . get ( ) , f ) ; if ( _output . nclasses ( ) >= 2 ) { for ( int i = 1 ; i < _output . nclasses ( ) + 1 ; ++ i ) preds [ i ] = predFloats [ i ] ; } else { preds [ 0 ] = predFloats [ 0 ] ; } return preds ; } | Single - instance scoring - slow not optimized for mini - batches - do not use unless you know what you re doing |
22,582 | public TwoDimTable createCentroidStatsTable ( ) { if ( _size == null || _withinss == null ) return null ; List < String > colHeaders = new ArrayList < > ( ) ; List < String > colTypes = new ArrayList < > ( ) ; List < String > colFormat = new ArrayList < > ( ) ; colHeaders . add ( "Centroid" ) ; colTypes . add ( "long" ) ; colFormat . add ( "%d" ) ; colHeaders . add ( "Size" ) ; colTypes . add ( "double" ) ; colFormat . add ( "%.5f" ) ; colHeaders . add ( "Within Cluster Sum of Squares" ) ; colTypes . add ( "double" ) ; colFormat . add ( "%.5f" ) ; final int K = _size . length ; assert ( _withinss . length == K ) ; TwoDimTable table = new TwoDimTable ( "Centroid Statistics" , null , new String [ K ] , colHeaders . toArray ( new String [ 0 ] ) , colTypes . toArray ( new String [ 0 ] ) , colFormat . toArray ( new String [ 0 ] ) , "" ) ; for ( int k = 0 ; k < K ; ++ k ) { int col = 0 ; table . set ( k , col ++ , k + 1 ) ; table . set ( k , col ++ , _size [ k ] ) ; table . set ( k , col , _withinss [ k ] ) ; } return table ; } | Populate TwoDimTable from members _size and _withinss |
22,583 | private ModelMetrics . MetricBuilder createMetricsBuilder ( final int responseClassesNum , final String [ ] responseDomain ) { switch ( responseClassesNum ) { case 1 : return new ModelMetricsRegression . MetricBuilderRegression ( ) ; case 2 : return new ModelMetricsBinomial . MetricBuilderBinomial ( responseDomain ) ; default : return new ModelMetricsMultinomial . MetricBuilderMultinomial ( responseClassesNum , responseDomain ) ; } } | Constructs a MetricBuilder for this XGBoostScoreTask based on parameters of response variable |
22,584 | public static Frame sort ( final Frame fr , int [ ] cols , int [ ] ascending ) { if ( cols . length == 0 ) return fr ; for ( int col : cols ) if ( col < 0 || col >= fr . numCols ( ) ) throw new IllegalArgumentException ( "Column " + col + " is out of range of " + fr . numCols ( ) ) ; int id_maps [ ] [ ] = new int [ cols . length ] [ ] ; for ( int i = 0 ; i < cols . length ; i ++ ) { Vec vec = fr . vec ( cols [ i ] ) ; if ( vec . isCategorical ( ) ) { String [ ] domain = vec . domain ( ) ; id_maps [ i ] = new int [ domain . length ] ; for ( int j = 0 ; j < domain . length ; j ++ ) id_maps [ i ] [ j ] = j ; } } return Merge . merge ( fr , new Frame ( new Vec [ 0 ] ) , cols , new int [ 0 ] , true , id_maps , ascending , new int [ 0 ] ) ; } | It is not currently an in - place sort so the data is doubled and a sorted copy is returned . |
22,585 | private boolean findInclusiveNa ( int colIdToFind ) { if ( parent == null ) { return true ; } else if ( parent . getColId ( ) == colIdToFind ) { return inclusiveNa ; } return parent . findInclusiveNa ( colIdToFind ) ; } | Calculate whether the NA value for a particular colId can reach this node . |
22,586 | private BitSet calculateChildInclusiveLevels ( boolean includeAllLevels , boolean discardAllLevels , boolean nodeBitsetDoesContain ) { BitSet inheritedInclusiveLevels = findInclusiveLevels ( colId ) ; BitSet childInclusiveLevels = new BitSet ( ) ; for ( int i = 0 ; i < domainValues . length ; i ++ ) { boolean includeThisLevel = false ; { if ( discardAllLevels ) { includeThisLevel = false ; } else if ( includeAllLevels ) { includeThisLevel = calculateIncludeThisLevel ( inheritedInclusiveLevels , i ) ; } else if ( bs . isInRange ( i ) && bs . contains ( i ) == nodeBitsetDoesContain ) { includeThisLevel = calculateIncludeThisLevel ( inheritedInclusiveLevels , i ) ; } } if ( includeThisLevel ) { childInclusiveLevels . set ( i ) ; } } return childInclusiveLevels ; } | Calculate the set of levels that flow through to a child . |
22,587 | void printDotNodesAtLevel ( PrintStream os , int levelToPrint , boolean detail , PrintMojo . PrintTreeOptions treeOptions ) { if ( getDepth ( ) == levelToPrint ) { printDotNode ( os , detail , treeOptions ) ; return ; } assert ( getDepth ( ) < levelToPrint ) ; if ( leftChild != null ) { leftChild . printDotNodesAtLevel ( os , levelToPrint , detail , treeOptions ) ; } if ( rightChild != null ) { rightChild . printDotNodesAtLevel ( os , levelToPrint , detail , treeOptions ) ; } } | Recursively print nodes at a particular depth level in the tree . Useful to group them so they render properly . |
22,588 | void printDotEdges ( PrintStream os , int maxLevelsToPrintPerEdge , float totalWeight , boolean detail , PrintMojo . PrintTreeOptions treeOptions ) { assert ( leftChild == null ) == ( rightChild == null ) ; if ( leftChild != null ) { os . print ( "\"" + getDotName ( ) + "\"" + " -> " + "\"" + leftChild . getDotName ( ) + "\"" + " [" ) ; ArrayList < String > arr = new ArrayList < > ( ) ; if ( leftChild . getInclusiveNa ( ) ) { arr . add ( "[NA]" ) ; } if ( naVsRest ) { arr . add ( "[Not NA]" ) ; } else { if ( ! isBitset ( ) ) { arr . add ( "<" ) ; } } printDotEdgesCommon ( os , maxLevelsToPrintPerEdge , arr , leftChild , totalWeight , detail , treeOptions ) ; } if ( rightChild != null ) { os . print ( "\"" + getDotName ( ) + "\"" + " -> " + "\"" + rightChild . getDotName ( ) + "\"" + " [" ) ; ArrayList < String > arr = new ArrayList < > ( ) ; if ( rightChild . getInclusiveNa ( ) ) { arr . add ( "[NA]" ) ; } if ( ! naVsRest ) { if ( ! isBitset ( ) ) { arr . add ( ">=" ) ; } } printDotEdgesCommon ( os , maxLevelsToPrintPerEdge , arr , rightChild , totalWeight , detail , treeOptions ) ; } } | Recursively print all edges in the tree . |
22,589 | public static FrameNodes findFrameNodes ( Frame fr ) { boolean [ ] nodesHoldingFrame = new boolean [ H2O . CLOUD . size ( ) ] ; Vec vec = fr . anyVec ( ) ; for ( int chunkNr = 0 ; chunkNr < vec . nChunks ( ) ; chunkNr ++ ) { int home = vec . chunkKey ( chunkNr ) . home_node ( ) . index ( ) ; if ( ! nodesHoldingFrame [ home ] ) nodesHoldingFrame [ home ] = true ; } return new FrameNodes ( fr , nodesHoldingFrame ) ; } | Finds what nodes actually do carry some of data of a given Frame |
22,590 | public static byte schemaToColumnType ( String s ) { switch ( s . toLowerCase ( ) ) { case "boolean" : case "smallint" : case "tinyint" : case "bigint" : case "int" : case "float" : case "double" : case "decimal" : return Vec . T_NUM ; case "timestamp" : case "date" : return Vec . T_TIME ; case "enum" : return Vec . T_CAT ; case "string" : case "varchar" : case "char" : return Vec . T_STR ; default : throw new IllegalArgumentException ( "Unsupported Orc schema type: " + s ) ; } } | Transform Orc column types into H2O type . |
22,591 | public static DecryptionTool get ( Key < DecryptionTool > key ) { if ( key == null ) return new NullDecryptionTool ( ) ; DecryptionTool decrypt = DKV . getGet ( key ) ; return decrypt == null ? new NullDecryptionTool ( ) : decrypt ; } | Retrieves a Decryption Tool from DKV using a given key . |
22,592 | static SecretKeySpec readSecretKey ( DecryptionSetup ds ) { Keyed < ? > ksObject = DKV . getGet ( ds . _keystore_id ) ; ByteVec ksVec = ( ByteVec ) ( ksObject instanceof Frame ? ( ( Frame ) ksObject ) . vec ( 0 ) : ksObject ) ; InputStream ksStream = ksVec . openStream ( null ) ; try { KeyStore keystore = KeyStore . getInstance ( ds . _keystore_type ) ; keystore . load ( ksStream , ds . _password ) ; if ( ! keystore . containsAlias ( ds . _key_alias ) ) { throw new IllegalArgumentException ( "Alias for key not found" ) ; } java . security . Key key = keystore . getKey ( ds . _key_alias , ds . _password ) ; return new SecretKeySpec ( key . getEncoded ( ) , key . getAlgorithm ( ) ) ; } catch ( GeneralSecurityException e ) { throw new RuntimeException ( "Unable to load key " + ds . _key_alias + " from keystore " + ds . _keystore_id , e ) ; } catch ( IOException e ) { throw new RuntimeException ( "Failed to read keystore " + ds . _keystore_id , e ) ; } } | Retrieves a Secret Key using a given Decryption Setup . |
22,593 | public static DecryptionTool make ( DecryptionSetup ds ) { if ( ds . _decrypt_tool_id == null ) ds . _decrypt_tool_id = Key . make ( ) ; try { Class < ? > dtClass = DecryptionTool . class . getClassLoader ( ) . loadClass ( ds . _decrypt_impl ) ; if ( ! DecryptionTool . class . isAssignableFrom ( dtClass ) ) { throw new IllegalArgumentException ( "Class " + ds . _decrypt_impl + " doesn't implement a Decryption Tool." ) ; } Constructor < ? > constructor = dtClass . getConstructor ( DecryptionSetup . class ) ; DecryptionTool dt = ( DecryptionTool ) constructor . newInstance ( ds ) ; DKV . put ( dt ) ; return dt ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "Unknown decrypt tool: " + ds . _decrypt_impl , e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( "Invalid implementation of Decryption Tool (missing constructor)." , e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Instantiates a Decryption Tool using a given Decryption Setup and installs it in DKV . |
22,594 | private double calcEntropy ( String str ) { HashMap < Character , Integer > freq = new HashMap < > ( ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char c = str . charAt ( i ) ; Integer count = freq . get ( c ) ; if ( count == null ) freq . put ( c , 1 ) ; else freq . put ( c , count + 1 ) ; } double sume = 0 ; int N = str . length ( ) ; double n ; for ( char c : freq . keySet ( ) ) { n = freq . get ( c ) ; sume += - n / N * Math . log ( n / N ) / Math . log ( 2 ) ; } return sume ; } | Shannon s entropy |
22,595 | public static MojoModel load ( String file ) throws IOException { File f = new File ( file ) ; if ( ! f . exists ( ) ) throw new FileNotFoundException ( "File " + file + " cannot be found." ) ; MojoReaderBackend cr = f . isDirectory ( ) ? new FolderMojoReaderBackend ( file ) : new ZipfileMojoReaderBackend ( file ) ; return ModelMojoReader . readFrom ( cr ) ; } | Primary factory method for constructing MojoModel instances . |
22,596 | public static < MP extends Model . Parameters , C extends HyperSpaceSearchCriteria > HyperSpaceWalker < MP , ? extends HyperSpaceSearchCriteria > create ( MP params , Map < String , Object [ ] > hyperParams , ModelParametersBuilderFactory < MP > paramsBuilderFactory , C search_criteria ) { HyperSpaceSearchCriteria . Strategy strategy = search_criteria . strategy ( ) ; if ( strategy == HyperSpaceSearchCriteria . Strategy . Cartesian ) { return new HyperSpaceWalker . CartesianWalker < > ( params , hyperParams , paramsBuilderFactory , ( HyperSpaceSearchCriteria . CartesianSearchCriteria ) search_criteria ) ; } else if ( strategy == HyperSpaceSearchCriteria . Strategy . RandomDiscrete ) { return new HyperSpaceWalker . RandomDiscreteValueWalker < > ( params , hyperParams , paramsBuilderFactory , ( HyperSpaceSearchCriteria . RandomDiscreteValueSearchCriteria ) search_criteria ) ; } else { throw new H2OIllegalArgumentException ( "strategy" , "GridSearch" , strategy ) ; } } | Factory method to create an instance based on the given HyperSpaceSearchCriteria instance . |
22,597 | public static boolean pathEquals ( String path1 , String path2 ) { return cleanPath ( path1 ) . equals ( cleanPath ( path2 ) ) ; } | Compare two paths after normalization of them . |
22,598 | public static String [ ] toStringArray ( Enumeration < String > enumeration ) { if ( enumeration == null ) { return null ; } List < String > list = java . util . Collections . list ( enumeration ) ; return list . toArray ( new String [ list . size ( ) ] ) ; } | Copy the given Enumeration into a String array . The Enumeration must contain String elements only . |
22,599 | public static < E > Iterator < E > toIterator ( Enumeration < E > enumeration ) { return new EnumerationIterator < E > ( enumeration ) ; } | Adapt an enumeration to an iterator . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.