idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
32,000
public long getMemoryUsageBytes ( ) { long total = 0 ; for ( int i = 0 ; i < maps_ . length ; i ++ ) { if ( maps_ [ i ] != null ) { total += maps_ [ i ] . getMemoryUsageBytes ( ) ; } } return total ; }
Returns total bytes used by all internal maps
32,001
public long getKeyMemoryUsageBytes ( ) { long total = 0 ; for ( int i = 0 ; i < maps_ . length ; i ++ ) { if ( maps_ [ i ] != null ) { total += ( long ) ( maps_ [ i ] . getActiveEntries ( ) ) * keySizeBytes_ ; } } return total ; }
Returns total bytes used for key storage
32,002
int getActiveMaps ( ) { int levels = 0 ; final int iMapsLen = maps_ . length ; for ( int i = 0 ; i < iMapsLen ; i ++ ) { if ( maps_ [ i ] != null ) { levels ++ ; } } return levels ; }
Returns the number of active internal maps so far . Only the base map is initialized in the constructor so this method would return 1 . As more keys are promoted up to higher level maps the return value would grow until the last level HLL map is allocated .
32,003
private boolean propagateToSharedSketch ( final long hash ) { while ( localPropagationInProgress . get ( ) ) { } localPropagationInProgress . set ( true ) ; final boolean res = shared . propagate ( localPropagationInProgress , null , hash ) ; thetaLong_ = shared . getVolatileTheta ( ) ; return res ; }
Propagates a single hash value to the shared sketch
32,004
private void propagateToSharedSketch ( ) { while ( localPropagationInProgress . get ( ) ) { } final CompactSketch compactSketch = compact ( propagateOrderedCompact , null ) ; localPropagationInProgress . set ( true ) ; shared . propagate ( localPropagationInProgress , compactSketch , ConcurrentSharedThetaSketch . NOT_SINGLE_HASH ) ; super . reset ( ) ; thetaLong_ = shared . getVolatileTheta ( ) ; }
Propagates the content of the buffer as a sketch to the shared sketch
32,005
private int countValidLevelsBelow ( final int tgtLvl ) { int count = 0 ; long bitPattern = ds_ . getBitPattern ( ) ; for ( int i = 0 ; ( i < tgtLvl ) && ( bitPattern > 0 ) ; ++ i , bitPattern >>>= 1 ) { if ( ( bitPattern & 1L ) > 0L ) { ++ count ; } } return count ; }
Counts number of full levels in the sketch below tgtLvl . Useful for computing the level offset in a compact sketch .
32,006
static void checkFamilyID ( final int familyID ) { final Family family = Family . idToFamily ( familyID ) ; if ( ! family . equals ( Family . QUANTILES ) ) { throw new SketchesArgumentException ( "Possible corruption: Invalid Family: " + family . toString ( ) ) ; } }
Checks the validity of the given family ID
32,007
static boolean checkPreLongsFlagsCap ( final int preambleLongs , final int flags , final long memCapBytes ) { final boolean empty = ( flags & EMPTY_FLAG_MASK ) > 0 ; final int minPre = Family . QUANTILES . getMinPreLongs ( ) ; final int maxPre = Family . QUANTILES . getMaxPreLongs ( ) ; final boolean valid = ( ( preambleLongs == minPre ) && empty ) || ( ( preambleLongs == maxPre ) && ! empty ) ; if ( ! valid ) { throw new SketchesArgumentException ( "Possible corruption: PreambleLongs inconsistent with empty state: " + preambleLongs ) ; } checkHeapFlags ( flags ) ; if ( memCapBytes < ( preambleLongs << 3 ) ) { throw new SketchesArgumentException ( "Possible corruption: Insufficient capacity for preamble: " + memCapBytes ) ; } return empty ; }
Checks the consistency of the flag bits and the state of preambleLong and the memory capacity and returns the empty state .
32,008
static void checkHeapFlags ( final int flags ) { final int allowedFlags = READ_ONLY_FLAG_MASK | EMPTY_FLAG_MASK | COMPACT_FLAG_MASK | ORDERED_FLAG_MASK ; final int flagsMask = ~ allowedFlags ; if ( ( flags & flagsMask ) > 0 ) { throw new SketchesArgumentException ( "Possible corruption: Invalid flags field: " + Integer . toBinaryString ( flags ) ) ; } }
Checks just the flags field of the preamble . Allowed flags are Read Only Empty Compact and ordered .
32,009
static boolean checkIsCompactMemory ( final Memory srcMem ) { final int flags = extractFlags ( srcMem ) ; final int compactFlags = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK ; return ( flags & compactFlags ) > 0 ; }
Checks just the flags field of an input Memory object . Returns true for a compact sketch false for an update sketch . Does not perform additional checks including sketch family .
32,010
static final void checkSplitPointsOrder ( final double [ ] values ) { if ( values == null ) { throw new SketchesArgumentException ( "Values cannot be null." ) ; } final int lenM1 = values . length - 1 ; for ( int j = 0 ; j < lenM1 ; j ++ ) { if ( values [ j ] < values [ j + 1 ] ) { continue ; } throw new SketchesArgumentException ( "Values must be unique, monotonically increasing and not NaN." ) ; } }
Checks the sequential validity of the given array of double values . They must be unique monotonically increasing and not NaN .
32,011
static int computeRetainedItems ( final int k , final long n ) { final int bbCnt = computeBaseBufferItems ( k , n ) ; final long bitPattern = computeBitPattern ( k , n ) ; final int validLevels = computeValidLevels ( bitPattern ) ; return bbCnt + ( validLevels * k ) ; }
Returns the number of retained valid items in the sketch given k and n .
32,012
static int lowLevelCompressBytes ( final byte [ ] byteArray , final int numBytesToEncode , final short [ ] encodingTable , final int [ ] compressedWords ) { int nextWordIndex = 0 ; long bitBuf = 0 ; int bufBits = 0 ; for ( int byteIndex = 0 ; byteIndex < numBytesToEncode ; byteIndex ++ ) { final int theByte = byteArray [ byteIndex ] & 0XFF ; final long codeInfo = ( encodingTable [ theByte ] & 0XFFFFL ) ; final long codeVal = codeInfo & 0XFFFL ; final int codeWordLength = ( int ) ( codeInfo >>> 12 ) ; bitBuf |= ( codeVal << bufBits ) ; bufBits += codeWordLength ; if ( bufBits >= 32 ) { compressedWords [ nextWordIndex ++ ] = ( int ) bitBuf ; bitBuf >>>= 32 ; bufBits -= 32 ; } } bufBits += 11 ; if ( bufBits >= 32 ) { compressedWords [ nextWordIndex ++ ] = ( int ) bitBuf ; bitBuf >>>= 32 ; bufBits -= 32 ; } if ( bufBits > 0 ) { assert ( bufBits < 32 ) ; compressedWords [ nextWordIndex ++ ] = ( int ) bitBuf ; } return nextWordIndex ; }
It is the caller s responsibility to ensure that the compressedWords array is long enough .
32,013
private static int [ ] uncompressTheSurprisingValues ( final CompressedState source ) { final int srcK = 1 << source . lgK ; final int numPairs = source . numCsv ; assert numPairs > 0 ; final int [ ] pairs = new int [ numPairs ] ; final int numBaseBits = CpcCompression . golombChooseNumberOfBaseBits ( srcK + numPairs , numPairs ) ; lowLevelUncompressPairs ( pairs , numPairs , numBaseBits , source . csvStream , source . csvLengthInts ) ; return pairs ; }
the length of this array is known to the source sketch .
32,014
private static int [ ] trickyGetPairsFromWindow ( final byte [ ] window , final int k , final int numPairsToGet , final int emptySpace ) { final int outputLength = emptySpace + numPairsToGet ; final int [ ] pairs = new int [ outputLength ] ; int rowIndex = 0 ; int pairIndex = emptySpace ; for ( rowIndex = 0 ; rowIndex < k ; rowIndex ++ ) { int wByte = window [ rowIndex ] & 0XFF ; while ( wByte != 0 ) { final int colIndex = Integer . numberOfTrailingZeros ( wByte ) ; wByte ^= ( 1 << colIndex ) ; pairs [ pairIndex ++ ] = ( rowIndex << 6 ) | colIndex ; } } assert ( pairIndex == outputLength ) ; return ( pairs ) ; }
will be filled in later by the caller .
32,015
private static void compressHybridFlavor ( final CompressedState target , final CpcSketch source ) { final int srcK = 1 << source . lgK ; final PairTable srcPairTable = source . pairTable ; final int srcNumPairs = srcPairTable . getNumPairs ( ) ; final int [ ] srcPairArr = PairTable . unwrappingGetItems ( srcPairTable , srcNumPairs ) ; introspectiveInsertionSort ( srcPairArr , 0 , srcNumPairs - 1 ) ; final byte [ ] srcSlidingWindow = source . slidingWindow ; final int srcWindowOffset = source . windowOffset ; final long srcNumCoupons = source . numCoupons ; assert ( srcSlidingWindow != null ) ; assert ( srcWindowOffset == 0 ) ; final long numPairs = srcNumCoupons - srcNumPairs ; assert numPairs < Integer . MAX_VALUE ; final int numPairsFromArray = ( int ) numPairs ; assert ( numPairsFromArray + srcNumPairs ) == srcNumCoupons ; final int [ ] allPairs = trickyGetPairsFromWindow ( srcSlidingWindow , srcK , numPairsFromArray , srcNumPairs ) ; PairTable . merge ( srcPairArr , 0 , srcNumPairs , allPairs , srcNumPairs , numPairsFromArray , allPairs , 0 ) ; compressTheSurprisingValues ( target , source , allPairs , ( int ) srcNumCoupons ) ; }
of a Pinned sketch before compressing it . Hence the name Hybrid .
32,016
private static void compressSlidingFlavor ( final CompressedState target , final CpcSketch source ) { compressTheWindow ( target , source ) ; final PairTable srcPairTable = source . pairTable ; final int numPairs = srcPairTable . getNumPairs ( ) ; if ( numPairs > 0 ) { final int [ ] pairs = PairTable . unwrappingGetItems ( srcPairTable , numPairs ) ; final int pseudoPhase = determinePseudoPhase ( source . lgK , source . numCoupons ) ; assert ( pseudoPhase < 16 ) ; final byte [ ] permutation = columnPermutationsForEncoding [ pseudoPhase ] ; final int offset = source . windowOffset ; assert ( ( offset > 0 ) && ( offset <= 56 ) ) ; for ( int i = 0 ; i < numPairs ; i ++ ) { final int rowCol = pairs [ i ] ; final int row = rowCol >>> 6 ; int col = ( rowCol & 63 ) ; col = ( ( col + 56 ) - offset ) & 63 ; assert ( col >= 0 ) && ( col < 56 ) ; col = permutation [ col ] ; pairs [ i ] = ( row << 6 ) | col ; } introspectiveInsertionSort ( pairs , 0 , numPairs - 1 ) ; compressTheSurprisingValues ( target , source , pairs , numPairs ) ; } }
Complicated by the existence of both a left fringe and a right fringe .
32,017
public void update ( final float value ) { if ( Float . isNaN ( value ) ) { return ; } if ( isEmpty ( ) ) { minValue_ = value ; maxValue_ = value ; } else { if ( value < minValue_ ) { minValue_ = value ; } if ( value > maxValue_ ) { maxValue_ = value ; } } if ( levels_ [ 0 ] == 0 ) { compressWhileUpdating ( ) ; } n_ ++ ; isLevelZeroSorted_ = false ; final int nextPos = levels_ [ 0 ] - 1 ; assert levels_ [ 0 ] >= 0 ; levels_ [ 0 ] = nextPos ; items_ [ nextPos ] = value ; }
Updates this sketch with the given data item .
32,018
public void merge ( final KllFloatsSketch other ) { if ( ( other == null ) || other . isEmpty ( ) ) { return ; } if ( m_ != other . m_ ) { throw new SketchesArgumentException ( "incompatible M: " + m_ + " and " + other . m_ ) ; } final long finalN = n_ + other . n_ ; for ( int i = other . levels_ [ 0 ] ; i < other . levels_ [ 1 ] ; i ++ ) { update ( other . items_ [ i ] ) ; } if ( other . numLevels_ >= 2 ) { mergeHigherLevels ( other , finalN ) ; } if ( Float . isNaN ( minValue_ ) || ( other . minValue_ < minValue_ ) ) { minValue_ = other . minValue_ ; } if ( Float . isNaN ( maxValue_ ) || ( other . maxValue_ > maxValue_ ) ) { maxValue_ = other . maxValue_ ; } n_ = finalN ; assertCorrectTotalWeight ( ) ; if ( other . isEstimationMode ( ) ) { minK_ = min ( minK_ , other . minK_ ) ; } }
Merges another sketch into this one .
32,019
public float getQuantile ( final double fraction ) { if ( isEmpty ( ) ) { return Float . NaN ; } if ( fraction == 0.0 ) { return minValue_ ; } if ( fraction == 1.0 ) { return maxValue_ ; } if ( ( fraction < 0.0 ) || ( fraction > 1.0 ) ) { throw new SketchesArgumentException ( "Fraction cannot be less than zero or greater than 1.0" ) ; } final KllFloatsQuantileCalculator quant = getQuantileCalculator ( ) ; return quant . getQuantile ( fraction ) ; }
Returns an approximation to the value of the data item that would be preceded by the given fraction of a hypothetical sorted version of the input stream so far .
32,020
public static int getKFromEpsilon ( final double epsilon , final boolean pmf ) { final double eps = max ( epsilon , 4.7634E-5 ) ; final double kdbl = pmf ? exp ( log ( 2.446 / eps ) / 0.9433 ) : exp ( log ( 2.296 / eps ) / 0.9723 ) ; final double krnd = round ( kdbl ) ; final double del = abs ( krnd - kdbl ) ; final int k = ( int ) ( ( del < 1E-6 ) ? krnd : ceil ( kdbl ) ) ; return max ( MIN_K , min ( MAX_K , k ) ) ; }
thousands of trials
32,021
public byte [ ] toByteArray ( ) { final byte [ ] bytes = new byte [ getSerializedSizeBytes ( ) ] ; final boolean isSingleItem = n_ == 1 ; bytes [ PREAMBLE_INTS_BYTE ] = ( byte ) ( isEmpty ( ) || isSingleItem ? PREAMBLE_INTS_SHORT : PREAMBLE_INTS_FULL ) ; bytes [ SER_VER_BYTE ] = isSingleItem ? serialVersionUID2 : serialVersionUID1 ; bytes [ FAMILY_BYTE ] = ( byte ) Family . KLL . getID ( ) ; bytes [ FLAGS_BYTE ] = ( byte ) ( ( isEmpty ( ) ? 1 << Flags . IS_EMPTY . ordinal ( ) : 0 ) | ( isLevelZeroSorted_ ? 1 << Flags . IS_LEVEL_ZERO_SORTED . ordinal ( ) : 0 ) | ( isSingleItem ? 1 << Flags . IS_SINGLE_ITEM . ordinal ( ) : 0 ) ) ; ByteArrayUtil . putShortLE ( bytes , K_SHORT , ( short ) k_ ) ; bytes [ M_BYTE ] = ( byte ) m_ ; if ( isEmpty ( ) ) { return bytes ; } int offset = DATA_START_SINGLE_ITEM ; if ( ! isSingleItem ) { ByteArrayUtil . putLongLE ( bytes , N_LONG , n_ ) ; ByteArrayUtil . putShortLE ( bytes , MIN_K_SHORT , ( short ) minK_ ) ; bytes [ NUM_LEVELS_BYTE ] = ( byte ) numLevels_ ; offset = DATA_START ; for ( int i = 0 ; i < numLevels_ ; i ++ ) { ByteArrayUtil . putIntLE ( bytes , offset , levels_ [ i ] ) ; offset += Integer . BYTES ; } ByteArrayUtil . putFloatLE ( bytes , offset , minValue_ ) ; offset += Float . BYTES ; ByteArrayUtil . putFloatLE ( bytes , offset , maxValue_ ) ; offset += Float . BYTES ; } final int numItems = getNumRetained ( ) ; for ( int i = 0 ; i < numItems ; i ++ ) { ByteArrayUtil . putFloatLE ( bytes , offset , items_ [ levels_ [ 0 ] + i ] ) ; offset += Float . BYTES ; } return bytes ; }
Returns serialized sketch in a byte array form .
32,022
public static KllFloatsSketch heapify ( final Memory mem ) { final int preambleInts = mem . getByte ( PREAMBLE_INTS_BYTE ) & 0xff ; final int serialVersion = mem . getByte ( SER_VER_BYTE ) & 0xff ; final int family = mem . getByte ( FAMILY_BYTE ) & 0xff ; final int flags = mem . getByte ( FLAGS_BYTE ) & 0xff ; final int m = mem . getByte ( M_BYTE ) & 0xff ; if ( m != DEFAULT_M ) { throw new SketchesArgumentException ( "Possible corruption: M must be " + DEFAULT_M + ": " + m ) ; } final boolean isEmpty = ( flags & ( 1 << Flags . IS_EMPTY . ordinal ( ) ) ) > 0 ; final boolean isSingleItem = ( flags & ( 1 << Flags . IS_SINGLE_ITEM . ordinal ( ) ) ) > 0 ; if ( isEmpty || isSingleItem ) { if ( preambleInts != PREAMBLE_INTS_SHORT ) { throw new SketchesArgumentException ( "Possible corruption: preambleInts must be " + PREAMBLE_INTS_SHORT + " for an empty or single item sketch: " + preambleInts ) ; } } else { if ( preambleInts != PREAMBLE_INTS_FULL ) { throw new SketchesArgumentException ( "Possible corruption: preambleInts must be " + PREAMBLE_INTS_FULL + " for a sketch with more than one item: " + preambleInts ) ; } } if ( ( serialVersion != serialVersionUID1 ) && ( serialVersion != serialVersionUID2 ) ) { throw new SketchesArgumentException ( "Possible corruption: serial version mismatch: expected " + serialVersionUID1 + " or " + serialVersionUID2 + ", got " + serialVersion ) ; } if ( family != Family . KLL . getID ( ) ) { throw new SketchesArgumentException ( "Possible corruption: family mismatch: expected " + Family . KLL . getID ( ) + ", got " + family ) ; } return new KllFloatsSketch ( mem ) ; }
Heapify takes the sketch image in Memory and instantiates an on - heap sketch . The resulting sketch will not retain any link to the source Memory .
32,023
static void checkK ( final int k ) { if ( ( k < MIN_K ) || ( k > MAX_K ) ) { throw new SketchesArgumentException ( "K must be >= " + MIN_K + " and <= " + MAX_K + ": " + k ) ; } }
Checks the validity of the given value k
32,024
private void compressWhileUpdating ( ) { final int level = findLevelToCompact ( ) ; if ( level == ( numLevels_ - 1 ) ) { addEmptyTopLevelToCompletelyFullSketch ( ) ; } final int rawBeg = levels_ [ level ] ; final int rawLim = levels_ [ level + 1 ] ; final int popAbove = levels_ [ level + 2 ] - rawLim ; final int rawPop = rawLim - rawBeg ; final boolean oddPop = KllHelper . isOdd ( rawPop ) ; final int adjBeg = oddPop ? rawBeg + 1 : rawBeg ; final int adjPop = oddPop ? rawPop - 1 : rawPop ; final int halfAdjPop = adjPop / 2 ; if ( level == 0 ) { Arrays . sort ( items_ , adjBeg , adjBeg + adjPop ) ; } if ( popAbove == 0 ) { KllHelper . randomlyHalveUp ( items_ , adjBeg , adjPop ) ; } else { KllHelper . randomlyHalveDown ( items_ , adjBeg , adjPop ) ; KllHelper . mergeSortedArrays ( items_ , adjBeg , halfAdjPop , items_ , rawLim , popAbove , items_ , adjBeg + halfAdjPop ) ; } levels_ [ level + 1 ] -= halfAdjPop ; if ( oddPop ) { levels_ [ level ] = levels_ [ level + 1 ] - 1 ; items_ [ levels_ [ level ] ] = items_ [ rawBeg ] ; } else { levels_ [ level ] = levels_ [ level + 1 ] ; } assert levels_ [ level ] == ( rawBeg + halfAdjPop ) ; if ( level > 0 ) { final int amount = rawBeg - levels_ [ 0 ] ; System . arraycopy ( items_ , levels_ [ 0 ] , items_ , levels_ [ 0 ] + halfAdjPop , amount ) ; for ( int lvl = 0 ; lvl < level ; lvl ++ ) { levels_ [ lvl ] += halfAdjPop ; } } }
It cannot be used while merging while reducing k or anything else .
32,025
public CompactDoublesSketch compact ( final WritableMemory dstMem ) { if ( dstMem == null ) { return HeapCompactDoublesSketch . createFromUpdateSketch ( this ) ; } return DirectCompactDoublesSketch . createFromUpdateSketch ( this , dstMem ) ; }
Returns a compact version of this sketch . If passing in a Memory object the compact sketch will use that direct memory ; otherwise an on - heap sketch will be returned .
32,026
public static < T > ItemsSketch < T > getInstance ( final Comparator < ? super T > comparator ) { return getInstance ( PreambleUtil . DEFAULT_K , comparator ) ; }
Obtains a new instance of an ItemsSketch using the DEFAULT_K .
32,027
public static < T > ItemsSketch < T > getInstance ( final int k , final Comparator < ? super T > comparator ) { final ItemsSketch < T > qs = new ItemsSketch < > ( k , comparator ) ; final int bufAlloc = 2 * Math . min ( DoublesSketch . MIN_K , k ) ; qs . n_ = 0 ; qs . combinedBufferItemCapacity_ = bufAlloc ; qs . combinedBuffer_ = new Object [ bufAlloc ] ; qs . baseBufferCount_ = 0 ; qs . bitPattern_ = 0 ; qs . minValue_ = null ; qs . maxValue_ = null ; return qs ; }
Obtains a new instance of an ItemsSketch .
32,028
public static < T > ItemsSketch < T > getInstance ( final Memory srcMem , final Comparator < ? super T > comparator , final ArrayOfItemsSerDe < T > serDe ) { final long memCapBytes = srcMem . getCapacity ( ) ; if ( memCapBytes < 8 ) { throw new SketchesArgumentException ( "Memory too small: " + memCapBytes ) ; } final int preambleLongs = extractPreLongs ( srcMem ) ; final int serVer = extractSerVer ( srcMem ) ; final int familyID = extractFamilyID ( srcMem ) ; final int flags = extractFlags ( srcMem ) ; final int k = extractK ( srcMem ) ; ItemsUtil . checkItemsSerVer ( serVer ) ; if ( ( serVer == 3 ) && ( ( flags & COMPACT_FLAG_MASK ) == 0 ) ) { throw new SketchesArgumentException ( "Non-compact Memory images are not supported." ) ; } final boolean empty = Util . checkPreLongsFlagsCap ( preambleLongs , flags , memCapBytes ) ; Util . checkFamilyID ( familyID ) ; final ItemsSketch < T > qs = getInstance ( k , comparator ) ; if ( empty ) { return qs ; } final long n = extractN ( srcMem ) ; final int extra = 2 ; final int numMemItems = Util . computeRetainedItems ( k , n ) + extra ; qs . n_ = n ; qs . combinedBufferItemCapacity_ = Util . computeCombinedBufferItemCapacity ( k , n ) ; qs . baseBufferCount_ = computeBaseBufferItems ( k , n ) ; qs . bitPattern_ = computeBitPattern ( k , n ) ; qs . combinedBuffer_ = new Object [ qs . combinedBufferItemCapacity_ ] ; final int srcMemItemsOffsetBytes = preambleLongs * Long . BYTES ; final Memory mReg = srcMem . region ( srcMemItemsOffsetBytes , srcMem . getCapacity ( ) - srcMemItemsOffsetBytes ) ; final T [ ] itemsArray = serDe . deserializeFromMemory ( mReg , numMemItems ) ; qs . itemsArrayToCombinedBuffer ( itemsArray ) ; return qs ; }
Heapifies the given srcMem which must be a Memory image of a ItemsSketch
32,029
static < T > ItemsSketch < T > copy ( final ItemsSketch < T > sketch ) { final ItemsSketch < T > qsCopy = ItemsSketch . getInstance ( sketch . k_ , sketch . comparator_ ) ; qsCopy . n_ = sketch . n_ ; qsCopy . minValue_ = sketch . getMinValue ( ) ; qsCopy . maxValue_ = sketch . getMaxValue ( ) ; qsCopy . combinedBufferItemCapacity_ = sketch . getCombinedBufferAllocatedCount ( ) ; qsCopy . baseBufferCount_ = sketch . getBaseBufferCount ( ) ; qsCopy . bitPattern_ = sketch . getBitPattern ( ) ; final Object [ ] combBuf = sketch . getCombinedBuffer ( ) ; qsCopy . combinedBuffer_ = Arrays . copyOf ( combBuf , combBuf . length ) ; return qsCopy ; }
Returns a copy of the given sketch
32,030
public void update ( final T dataItem ) { if ( dataItem == null ) { return ; } if ( ( maxValue_ == null ) || ( comparator_ . compare ( dataItem , maxValue_ ) > 0 ) ) { maxValue_ = dataItem ; } if ( ( minValue_ == null ) || ( comparator_ . compare ( dataItem , minValue_ ) < 0 ) ) { minValue_ = dataItem ; } if ( ( baseBufferCount_ + 1 ) > combinedBufferItemCapacity_ ) { ItemsSketch . growBaseBuffer ( this ) ; } combinedBuffer_ [ baseBufferCount_ ++ ] = dataItem ; n_ ++ ; if ( baseBufferCount_ == ( 2 * k_ ) ) { ItemsUtil . processFullBaseBuffer ( this ) ; } }
Updates this sketch with the given double data item
32,031
public T getQuantileUpperBound ( final double fraction ) { return getQuantile ( min ( 1.0 , fraction + Util . getNormalizedRankError ( k_ , false ) ) ) ; }
Gets the upper bound of the value interval in which the true quantile of the given rank exists with a confidence of at least 99% .
32,032
public T getQuantileLowerBound ( final double fraction ) { return getQuantile ( max ( 0 , fraction - Util . getNormalizedRankError ( k_ , false ) ) ) ; }
Gets the lower bound of the value interval in which the true quantile of the given rank exists with a confidence of at least 99% .
32,033
public void reset ( ) { n_ = 0 ; combinedBufferItemCapacity_ = 2 * Math . min ( DoublesSketch . MIN_K , k_ ) ; combinedBuffer_ = new Object [ combinedBufferItemCapacity_ ] ; baseBufferCount_ = 0 ; bitPattern_ = 0 ; minValue_ = null ; maxValue_ = null ; }
Resets this sketch to a virgin state but retains the original value of k .
32,034
public ItemsSketch < T > downSample ( final int newK ) { final ItemsSketch < T > newSketch = ItemsSketch . getInstance ( newK , comparator_ ) ; ItemsMergeImpl . downSamplingMergeInto ( this , newSketch ) ; return newSketch ; }
From an existing sketch this creates a new sketch that can have a smaller value of K . The original sketch is not modified .
32,035
public void putMemory ( final WritableMemory dstMem , final ArrayOfItemsSerDe < T > serDe ) { final byte [ ] byteArr = toByteArray ( serDe ) ; final long memCap = dstMem . getCapacity ( ) ; if ( memCap < byteArr . length ) { throw new SketchesArgumentException ( "Destination Memory not large enough: " + memCap + " < " + byteArr . length ) ; } dstMem . putByteArray ( 0 , byteArr , 0 , byteArr . length ) ; }
Puts the current sketch into the given Memory if there is sufficient space . Otherwise throws an error .
32,036
private void itemsArrayToCombinedBuffer ( final T [ ] itemsArray ) { final int extra = 2 ; minValue_ = itemsArray [ 0 ] ; maxValue_ = itemsArray [ 1 ] ; System . arraycopy ( itemsArray , extra , combinedBuffer_ , 0 , baseBufferCount_ ) ; long bits = bitPattern_ ; if ( bits > 0 ) { int index = extra + baseBufferCount_ ; for ( int level = 0 ; bits != 0L ; level ++ , bits >>>= 1 ) { if ( ( bits & 1L ) > 0L ) { System . arraycopy ( itemsArray , index , combinedBuffer_ , ( 2 + level ) * k_ , k_ ) ; index += k_ ; } } } }
Loads the Combined Buffer min and max from the given items array . The Combined Buffer is always in non - compact form and must be pre - allocated .
32,037
private void scanAllAsearchB ( ) { final long [ ] scanAArr = a_ . getCache ( ) ; final int arrLongsIn = scanAArr . length ; cache_ = new long [ arrLongsIn ] ; for ( int i = 0 ; i < arrLongsIn ; i ++ ) { final long hashIn = scanAArr [ i ] ; if ( ( hashIn <= 0L ) || ( hashIn >= thetaLong_ ) ) { continue ; } final int foundIdx = hashSearch ( bHashTable_ , lgArrLongsHT_ , hashIn ) ; if ( foundIdx > - 1 ) { continue ; } cache_ [ curCount_ ++ ] = hashIn ; } }
Sketch A is either unordered compact or hash table
32,038
public static double approximateLowerBoundOnP ( final long n , final long k , final double numStdDevs ) { checkInputs ( n , k ) ; if ( n == 0 ) { return 0.0 ; } else if ( k == 0 ) { return 0.0 ; } else if ( k == 1 ) { return ( exactLowerBoundOnPForKequalsOne ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else if ( k == n ) { return ( exactLowerBoundOnPForKequalsN ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else { final double x = abramowitzStegunFormula26p5p22 ( ( n - k ) + 1 , k , ( - 1.0 * numStdDevs ) ) ; return ( 1.0 - x ) ; } }
Computes lower bound of approximate Clopper - Pearson confidence interval for a binomial proportion .
32,039
public static double approximateUpperBoundOnP ( final long n , final long k , final double numStdDevs ) { checkInputs ( n , k ) ; if ( n == 0 ) { return 1.0 ; } else if ( k == n ) { return 1.0 ; } else if ( k == ( n - 1 ) ) { return ( exactUpperBoundOnPForKequalsNminusOne ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else if ( k == 0 ) { return ( exactUpperBoundOnPForKequalsZero ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else { final double x = abramowitzStegunFormula26p5p22 ( n - k , k + 1 , numStdDevs ) ; return ( 1.0 - x ) ; } }
Computes upper bound of approximate Clopper - Pearson confidence interval for a binomial proportion .
32,040
private static double erf_of_nonneg ( final double x ) { final double a1 = 0.0705230784 ; final double a3 = 0.0092705272 ; final double a5 = 0.0002765672 ; final double a2 = 0.0422820123 ; final double a4 = 0.0001520143 ; final double a6 = 0.0000430638 ; final double x2 = x * x ; final double x3 = x2 * x ; final double x4 = x2 * x2 ; final double x5 = x2 * x3 ; final double x6 = x3 * x3 ; final double sum = ( 1.0 + ( a1 * x ) + ( a2 * x2 ) + ( a3 * x3 ) + ( a4 * x4 ) + ( a5 * x5 ) + ( a6 * x6 ) ) ; final double sum2 = sum * sum ; final double sum4 = sum2 * sum2 ; final double sum8 = sum4 * sum4 ; final double sum16 = sum8 * sum8 ; return ( 1.0 - ( 1.0 / sum16 ) ) ; }
Abramowitz and Stegun formula 7 . 1 . 28 p . 88 ; Claims accuracy of about 7 decimal digits
32,041
private static double abramowitzStegunFormula26p5p22 ( final double a , final double b , final double yp ) { final double b2m1 = ( 2.0 * b ) - 1.0 ; final double a2m1 = ( 2.0 * a ) - 1.0 ; final double lambda = ( ( yp * yp ) - 3.0 ) / 6.0 ; final double htmp = ( 1.0 / a2m1 ) + ( 1.0 / b2m1 ) ; final double h = 2.0 / htmp ; final double term1 = ( yp * ( Math . sqrt ( h + lambda ) ) ) / h ; final double term2 = ( 1.0 / b2m1 ) - ( 1.0 / a2m1 ) ; final double term3 = ( lambda + ( 5.0 / 6.0 ) ) - ( 2.0 / ( 3.0 * h ) ) ; final double w = term1 - ( term2 * term3 ) ; final double xp = a / ( a + ( b * ( Math . exp ( 2.0 * w ) ) ) ) ; return xp ; }
that the formula was typed in correctly .
32,042
public static < T > ReservoirItemsSketch < T > newInstance ( final int k , final ResizeFactor rf ) { return new ReservoirItemsSketch < > ( k , rf ) ; }
Construct a mergeable sampling sketch with up to k samples using a specified resize factor .
32,043
@ SuppressWarnings ( "unchecked" ) public T [ ] getSamples ( ) { if ( itemsSeen_ == 0 ) { return null ; } final Class < ? > clazz = data_ . get ( 0 ) . getClass ( ) ; return data_ . toArray ( ( T [ ] ) Array . newInstance ( clazz , 0 ) ) ; }
Returns a copy of the items in the reservoir or null if empty . The returned array length may be smaller than the reservoir capacity .
32,044
@ SuppressWarnings ( "unchecked" ) ReservoirItemsSketch < T > copy ( ) { return new ReservoirItemsSketch < > ( reservoirSize_ , currItemsAlloc_ , itemsSeen_ , rf_ , ( ArrayList < T > ) data_ . clone ( ) ) ; }
Used during union operations to ensure we do not overwrite an existing reservoir . Creates a shallow copy of the reservoir .
32,045
public CompactSketch intersect ( final Sketch a , final Sketch b ) { return intersect ( a , b , true , null ) ; }
Perform intersect set operation on the two given sketch arguments and return the result as an ordered CompactSketch on the heap .
32,046
static DirectCouponList newInstance ( final int lgConfigK , final TgtHllType tgtHllType , final WritableMemory dstMem ) { insertPreInts ( dstMem , LIST_PREINTS ) ; insertSerVer ( dstMem ) ; insertFamilyId ( dstMem ) ; insertLgK ( dstMem , lgConfigK ) ; insertLgArr ( dstMem , LG_INIT_LIST_SIZE ) ; insertFlags ( dstMem , EMPTY_FLAG_MASK ) ; insertListCount ( dstMem , 0 ) ; insertModes ( dstMem , tgtHllType , CurMode . LIST ) ; return new DirectCouponList ( lgConfigK , tgtHllType , CurMode . LIST , dstMem ) ; }
Standard factory for new DirectCouponList . This initializes the given WritableMemory .
32,047
static final int checkMaxLgArrLongs ( final Memory dstMem ) { final int preBytes = CONST_PREAMBLE_LONGS << 3 ; final long cap = dstMem . getCapacity ( ) ; final int maxLgArrLongs = Integer . numberOfTrailingZeros ( floorPowerOf2 ( ( int ) ( cap - preBytes ) ) >>> 3 ) ; if ( maxLgArrLongs < MIN_LG_ARR_LONGS ) { throw new SketchesArgumentException ( "dstMem not large enough for minimum sized hash table: " + cap ) ; } return maxLgArrLongs ; }
Returns the correct maximum lgArrLongs given the capacity of the Memory . Checks that the capacity is large enough for the minimum sized hash table .
32,048
static IntersectionImpl initNewHeapInstance ( final long seed ) { final IntersectionImpl impl = new IntersectionImpl ( null , seed , false ) ; impl . lgArrLongs_ = 0 ; impl . curCount_ = - 1 ; impl . thetaLong_ = Long . MAX_VALUE ; impl . empty_ = false ; impl . hashTable_ = null ; return impl ; }
Construct a new Intersection target on the java heap .
32,049
static IntersectionImpl initNewDirectInstance ( final long seed , final WritableMemory dstMem ) { final IntersectionImpl impl = new IntersectionImpl ( dstMem , seed , true ) ; insertPreLongs ( dstMem , CONST_PREAMBLE_LONGS ) ; insertSerVer ( dstMem , SER_VER ) ; insertFamilyID ( dstMem , Family . INTERSECTION . getID ( ) ) ; insertLgArrLongs ( dstMem , MIN_LG_ARR_LONGS ) ; insertFlags ( dstMem , 0 ) ; insertCurCount ( dstMem , - 1 ) ; insertP ( dstMem , ( float ) 1.0 ) ; insertThetaLong ( dstMem , Long . MAX_VALUE ) ; impl . lgArrLongs_ = MIN_LG_ARR_LONGS ; impl . curCount_ = - 1 ; impl . thetaLong_ = Long . MAX_VALUE ; impl . empty_ = false ; impl . maxLgArrLongs_ = checkMaxLgArrLongs ( dstMem ) ; return impl ; }
Construct a new Intersection target direct to the given destination Memory . Called by SetOperation . Builder .
32,050
static IntersectionImplR heapifyInstance ( final Memory srcMem , final long seed ) { final IntersectionImpl impl = new IntersectionImpl ( null , seed , false ) ; final int preLongsMem = srcMem . getByte ( PREAMBLE_LONGS_BYTE ) & 0X3F ; final int serVer = srcMem . getByte ( SER_VER_BYTE ) & 0XFF ; final int famID = srcMem . getByte ( FAMILY_BYTE ) & 0XFF ; final int lgArrLongs = srcMem . getByte ( LG_ARR_LONGS_BYTE ) & 0XFF ; final int flags = srcMem . getByte ( FLAGS_BYTE ) & 0XFF ; final int curCount = srcMem . getInt ( RETAINED_ENTRIES_INT ) ; final long thetaLong = srcMem . getLong ( THETA_LONG ) ; final boolean empty = ( flags & EMPTY_FLAG_MASK ) > 0 ; if ( preLongsMem != CONST_PREAMBLE_LONGS ) { throw new SketchesArgumentException ( "Memory PreambleLongs must equal " + CONST_PREAMBLE_LONGS + ": " + preLongsMem ) ; } if ( serVer != SER_VER ) { throw new SketchesArgumentException ( "Serialization Version must equal " + SER_VER ) ; } Family . INTERSECTION . checkFamilyID ( famID ) ; if ( empty ) { if ( curCount != 0 ) { throw new SketchesArgumentException ( "srcMem empty state inconsistent with curCount: " + empty + "," + curCount ) ; } } impl . lgArrLongs_ = lgArrLongs ; impl . curCount_ = curCount ; impl . thetaLong_ = thetaLong ; impl . empty_ = empty ; if ( ! empty ) { if ( curCount > 0 ) { impl . hashTable_ = new long [ 1 << lgArrLongs ] ; srcMem . getLongArray ( CONST_PREAMBLE_LONGS << 3 , impl . hashTable_ , 0 , 1 << lgArrLongs ) ; } } return impl ; }
Heapify an intersection target from a Memory image containing data .
32,051
@ SuppressWarnings ( { "unchecked" , "null" } ) public void update ( final Sketch < S > sketchIn ) { final boolean isFirstCall = isFirstCall_ ; isFirstCall_ = false ; if ( sketchIn == null ) { isEmpty_ = true ; sketch_ = null ; return ; } theta_ = min ( theta_ , sketchIn . getThetaLong ( ) ) ; isEmpty_ |= sketchIn . isEmpty ( ) ; if ( isEmpty_ || ( sketchIn . getRetainedEntries ( ) == 0 ) ) { sketch_ = null ; return ; } if ( isFirstCall ) { sketch_ = new QuickSelectSketch < > ( sketchIn . getRetainedEntries ( ) , ResizeFactor . X1 . lg ( ) , null ) ; final SketchIterator < S > it = sketchIn . iterator ( ) ; while ( it . next ( ) ) { final S summary = ( S ) it . getSummary ( ) . copy ( ) ; sketch_ . insert ( it . getKey ( ) , summary ) ; } } else { if ( sketch_ == null ) { return ; } final int matchSize = min ( sketch_ . getRetainedEntries ( ) , sketchIn . getRetainedEntries ( ) ) ; final long [ ] matchKeys = new long [ matchSize ] ; S [ ] matchSummaries = null ; int matchCount = 0 ; final SketchIterator < S > it = sketchIn . iterator ( ) ; while ( it . next ( ) ) { final S summary = sketch_ . find ( it . getKey ( ) ) ; if ( summary != null ) { matchKeys [ matchCount ] = it . getKey ( ) ; if ( matchSummaries == null ) { matchSummaries = ( S [ ] ) Array . newInstance ( summary . getClass ( ) , matchSize ) ; } matchSummaries [ matchCount ] = summarySetOps_ . intersection ( summary , it . getSummary ( ) ) ; matchCount ++ ; } } sketch_ = null ; if ( matchCount > 0 ) { sketch_ = new QuickSelectSketch < > ( matchCount , ResizeFactor . X1 . lg ( ) , null ) ; for ( int i = 0 ; i < matchCount ; i ++ ) { sketch_ . insert ( matchKeys [ i ] , matchSummaries [ i ] ) ; } } } if ( sketch_ != null ) { sketch_ . setThetaLong ( theta_ ) ; sketch_ . setNotEmpty ( ) ; } }
Updates the internal set by intersecting it with the given sketch
32,052
private static double contClassicLB ( final double numSamplesF , final double theta , final double numSDev ) { final double nHat = ( numSamplesF - 0.5 ) / theta ; final double b = numSDev * Math . sqrt ( ( 1.0 - theta ) / theta ) ; final double d = 0.5 * b * Math . sqrt ( ( b * b ) + ( 4.0 * nHat ) ) ; final double center = nHat + ( 0.5 * ( b * b ) ) ; return ( center - d ) ; }
our classic bounds but now with continuity correction
32,053
public static double getLowerBound ( final long numSamples , final double theta , final int numSDev , final boolean noDataSeen ) { if ( noDataSeen ) { return 0.0 ; } checkArgs ( numSamples , theta , numSDev ) ; final double lb = computeApproxBinoLB ( numSamples , theta , numSDev ) ; final double numSamplesF = numSamples ; final double est = numSamplesF / theta ; return ( Math . min ( est , Math . max ( numSamplesF , lb ) ) ) ; }
Returns the approximate lower bound value
32,054
public static double getUpperBound ( final long numSamples , final double theta , final int numSDev , final boolean noDataSeen ) { if ( noDataSeen ) { return 0.0 ; } checkArgs ( numSamples , theta , numSDev ) ; final double ub = computeApproxBinoUB ( numSamples , theta , numSDev ) ; final double numSamplesF = numSamples ; final double est = numSamplesF / theta ; return ( Math . max ( est , ub ) ) ; }
Returns the approximate upper bound value
32,055
static final void checkArgs ( final long numSamples , final double theta , final int numSDev ) { if ( ( numSDev | ( numSDev - 1 ) | ( 3 - numSDev ) | numSamples ) < 0 ) { throw new SketchesArgumentException ( "numSDev must only be 1,2, or 3 and numSamples must >= 0: numSDev=" + numSDev + ", numSamples=" + numSamples ) ; } if ( ( theta < 0.0 ) || ( theta > 1.0 ) ) { throw new SketchesArgumentException ( "0.0 < theta <= 1.0: " + theta ) ; } }
exposed only for test
32,056
public void update ( final ReservoirItemsSketch < T > sketchIn ) { if ( sketchIn == null ) { return ; } final ReservoirItemsSketch < T > ris = ( sketchIn . getK ( ) <= maxK_ ? sketchIn : sketchIn . downsampledCopy ( maxK_ ) ) ; final boolean isModifiable = ( sketchIn != ris ) ; if ( gadget_ == null ) { createNewGadget ( ris , isModifiable ) ; } else { twoWayMergeInternal ( ris , isModifiable ) ; } }
Union the given sketch . This method can be repeatedly called . If the given sketch is null it is interpreted as an empty sketch .
32,057
public void update ( final T datum ) { if ( datum == null ) { return ; } if ( gadget_ == null ) { gadget_ = ReservoirItemsSketch . newInstance ( maxK_ ) ; } gadget_ . update ( datum ) ; }
Present this union with a single item to be added to the union .
32,058
public byte [ ] toByteArray ( final ArrayOfItemsSerDe < T > serDe ) { if ( ( gadget_ == null ) || ( gadget_ . getNumSamples ( ) == 0 ) ) { return toByteArray ( serDe , null ) ; } else { return toByteArray ( serDe , gadget_ . getValueAtPosition ( 0 ) . getClass ( ) ) ; } }
Returns a byte array representation of this union
32,059
static double getRelErr ( final boolean upperBound , final boolean oooFlag , final int lgK , final int stdDev ) { final int idx = ( ( lgK - 4 ) * 3 ) + ( stdDev - 1 ) ; final int sw = ( oooFlag ? 2 : 0 ) | ( upperBound ? 1 : 0 ) ; double f = 0 ; switch ( sw ) { case 0 : { f = HIP_LB [ idx ] ; break ; } case 1 : { f = HIP_UB [ idx ] ; break ; } case 2 : { f = NON_HIP_LB [ idx ] ; break ; } case 3 : { f = NON_HIP_UB [ idx ] ; break ; } } return f ; }
Return Relative Error for UB or LB for HIP or Non - HIP as a function of numStdDev .
32,060
public double getEstimate ( ) { if ( ! hasHip ( mem ) ) { return getIconEstimate ( PreambleUtil . getLgK ( mem ) , getNumCoupons ( mem ) ) ; } return getHipAccum ( mem ) ; }
Returns the best estimate of the cardinality of the sketch .
32,061
static CompactSketch heapifyInstance ( final Memory srcMem , final long seed ) { final short memSeedHash = ( short ) extractSeedHash ( srcMem ) ; final short computedSeedHash = computeSeedHash ( seed ) ; checkSeedHashes ( memSeedHash , computedSeedHash ) ; final int preLongs = extractPreLongs ( srcMem ) ; final boolean empty = PreambleUtil . isEmpty ( srcMem ) ; int curCount = 0 ; long thetaLong = Long . MAX_VALUE ; long [ ] cache = new long [ 0 ] ; if ( preLongs == 1 ) { if ( ! empty ) { return new SingleItemSketch ( srcMem . getLong ( 8 ) , memSeedHash ) ; } } else { curCount = extractCurCount ( srcMem ) ; cache = new long [ curCount ] ; if ( preLongs == 2 ) { srcMem . getLongArray ( 16 , cache , 0 , curCount ) ; } else { srcMem . getLongArray ( 24 , cache , 0 , curCount ) ; thetaLong = extractThetaLong ( srcMem ) ; } } return new HeapCompactOrderedSketch ( cache , empty , memSeedHash , curCount , thetaLong ) ; }
Heapifies the given source Memory with seed
32,062
static CompactSketch compact ( final UpdateSketch sketch ) { final int curCount = sketch . getRetainedEntries ( true ) ; long thetaLong = sketch . getThetaLong ( ) ; boolean empty = sketch . isEmpty ( ) ; thetaLong = thetaOnCompact ( empty , curCount , thetaLong ) ; empty = emptyOnCompact ( curCount , thetaLong ) ; final short seedHash = sketch . getSeedHash ( ) ; final long [ ] cache = sketch . getCache ( ) ; final boolean ordered = true ; final long [ ] cacheOut = CompactSketch . compactCache ( cache , curCount , thetaLong , ordered ) ; if ( ( curCount == 1 ) && ( thetaLong == Long . MAX_VALUE ) ) { return new SingleItemSketch ( cacheOut [ 0 ] , seedHash ) ; } return new HeapCompactOrderedSketch ( cacheOut , empty , seedHash , curCount , thetaLong ) ; }
Converts the given UpdateSketch to this compact form .
32,063
public static double select ( final double [ ] arr , int lo , int hi , final int pivot ) { while ( hi > lo ) { final int j = partition ( arr , lo , hi ) ; if ( j == pivot ) { return arr [ pivot ] ; } if ( j > pivot ) { hi = j - 1 ; } else { lo = j + 1 ; } } return arr [ pivot ] ; }
Gets the 0 - based kth order statistic from the array . Warning! This changes the ordering of elements in the given array!
32,064
public static double selectIncludingZeros ( final double [ ] arr , final int pivot ) { final int arrSize = arr . length ; final int adj = pivot - 1 ; return select ( arr , 0 , arrSize - 1 , adj ) ; }
Gets the 1 - based kth order statistic from the array including any zero values in the array . Warning! This changes the ordering of elements in the given array!
32,065
public static double selectExcludingZeros ( final double [ ] arr , final int nonZeros , final int pivot ) { if ( pivot > nonZeros ) { return 0L ; } final int arrSize = arr . length ; final int zeros = arrSize - nonZeros ; final int adjK = ( pivot + zeros ) - 1 ; return select ( arr , 0 , arrSize - 1 , adjK ) ; }
Gets the 1 - based kth order statistic from the array excluding any zero values in the array . Warning! This changes the ordering of elements in the given array!
32,066
static final CouponHashSet heapifySet ( final Memory mem ) { final int lgConfigK = extractLgK ( mem ) ; final TgtHllType tgtHllType = extractTgtHllType ( mem ) ; final CurMode curMode = extractCurMode ( mem ) ; final int memArrStart = ( curMode == CurMode . LIST ) ? LIST_INT_ARR_START : HASH_SET_INT_ARR_START ; final CouponHashSet set = new CouponHashSet ( lgConfigK , tgtHllType ) ; set . putOutOfOrderFlag ( true ) ; final boolean memIsCompact = extractCompactFlag ( mem ) ; final int couponCount = extractHashSetCount ( mem ) ; int lgCouponArrInts = extractLgArr ( mem ) ; if ( lgCouponArrInts < LG_INIT_SET_SIZE ) { lgCouponArrInts = computeLgArr ( mem , couponCount , lgConfigK ) ; } if ( memIsCompact ) { for ( int i = 0 ; i < couponCount ; i ++ ) { set . couponUpdate ( extractInt ( mem , memArrStart + ( i << 2 ) ) ) ; } } else { set . couponCount = couponCount ; set . lgCouponArrInts = lgCouponArrInts ; final int couponArrInts = 1 << lgCouponArrInts ; set . couponIntArr = new int [ couponArrInts ] ; mem . getIntArray ( HASH_SET_INT_ARR_START , set . couponIntArr , 0 , couponArrInts ) ; } return set ; }
will also accept List but results in a Set
32,067
static HeapQuickSelectSketch heapifyInstance ( final Memory srcMem , final long seed ) { final int preambleLongs = extractPreLongs ( srcMem ) ; final int lgNomLongs = extractLgNomLongs ( srcMem ) ; final int lgArrLongs = extractLgArrLongs ( srcMem ) ; checkUnionQuickSelectFamily ( srcMem , preambleLongs , lgNomLongs ) ; checkMemIntegrity ( srcMem , seed , preambleLongs , lgNomLongs , lgArrLongs ) ; final float p = extractP ( srcMem ) ; final int lgRF = extractLgResizeFactor ( srcMem ) ; ResizeFactor myRF = ResizeFactor . getRF ( lgRF ) ; final int familyID = extractFamilyID ( srcMem ) ; final Family family = Family . idToFamily ( familyID ) ; if ( ( myRF == ResizeFactor . X1 ) && ( lgArrLongs != Util . startingSubMultiple ( lgNomLongs + 1 , myRF , MIN_LG_ARR_LONGS ) ) ) { myRF = ResizeFactor . X2 ; } final HeapQuickSelectSketch hqss = new HeapQuickSelectSketch ( lgNomLongs , seed , p , myRF , preambleLongs , family ) ; hqss . lgArrLongs_ = lgArrLongs ; hqss . hashTableThreshold_ = setHashTableThreshold ( lgNomLongs , lgArrLongs ) ; hqss . curCount_ = extractCurCount ( srcMem ) ; hqss . thetaLong_ = extractThetaLong ( srcMem ) ; hqss . empty_ = PreambleUtil . isEmpty ( srcMem ) ; hqss . cache_ = new long [ 1 << lgArrLongs ] ; srcMem . getLongArray ( preambleLongs << 3 , hqss . cache_ , 0 , 1 << lgArrLongs ) ; return hqss ; }
Heapify a sketch from a Memory UpdateSketch or Union object containing sketch data .
32,068
private final void quickSelectAndRebuild ( ) { final int arrLongs = 1 << lgArrLongs_ ; final int pivot = ( 1 << lgNomLongs_ ) + 1 ; thetaLong_ = selectExcludingZeros ( cache_ , curCount_ , pivot ) ; final long [ ] tgtArr = new long [ arrLongs ] ; curCount_ = HashOperations . hashArrayInsert ( cache_ , tgtArr , lgArrLongs_ , thetaLong_ ) ; cache_ = tgtArr ; }
array stays the same size . Changes theta and thus count
32,069
public T items ( final int i ) { loadArrays ( ) ; return ( sampleLists == null ? null : sampleLists . items [ i ] ) ; }
Returns a single item from the samples contained in the sketch . Does not perform bounds checking on the input . If this is the first getter call copies data arrays from the sketch .
32,070
public double weights ( final int i ) { loadArrays ( ) ; return ( sampleLists == null ? Double . NaN : sampleLists . weights [ i ] ) ; }
Returns a single weight from the samples contained in the sketch . Does not perform bounds checking on the input . If this is the first getter call copies data arrays from the sketch .
32,071
public SetOperationBuilder setNominalEntries ( final int nomEntries ) { bLgNomLongs = Integer . numberOfTrailingZeros ( ceilingPowerOf2 ( nomEntries ) ) ; if ( ( bLgNomLongs > MAX_LG_NOM_LONGS ) || ( bLgNomLongs < MIN_LG_NOM_LONGS ) ) { throw new SketchesArgumentException ( "Nominal Entries must be >= 16 and <= 67108864: " + nomEntries ) ; } return this ; }
Sets the Nominal Entries for this set operation . The minimum value is 16 and the maximum value is 67 108 864 which is 2^26 . Be aware that Unions as large as this maximum value have not been thoroughly tested or characterized for performance .
32,072
public SetOperation build ( final Family family , final WritableMemory dstMem ) { SetOperation setOp = null ; switch ( family ) { case UNION : { if ( dstMem == null ) { setOp = UnionImpl . initNewHeapInstance ( bLgNomLongs , bSeed , bP , bRF ) ; } else { setOp = UnionImpl . initNewDirectInstance ( bLgNomLongs , bSeed , bP , bRF , bMemReqSvr , dstMem ) ; } break ; } case INTERSECTION : { if ( dstMem == null ) { setOp = IntersectionImpl . initNewHeapInstance ( bSeed ) ; } else { setOp = IntersectionImpl . initNewDirectInstance ( bSeed , dstMem ) ; } break ; } case A_NOT_B : { if ( dstMem == null ) { setOp = new HeapAnotB ( bSeed ) ; } else { throw new SketchesArgumentException ( "AnotB is a stateless operation and cannot be persisted." ) ; } break ; } default : throw new SketchesArgumentException ( "Given Family cannot be built as a SetOperation: " + family . toString ( ) ) ; } return setOp ; }
Returns a SetOperation with the current configuration of this Builder the given Family and the given destination memory . Note that the destination memory cannot be used with AnotB .
32,073
static ReversePurgeLongHashMap getInstance ( final String string ) { final String [ ] tokens = string . split ( "," ) ; if ( tokens . length < 2 ) { throw new SketchesArgumentException ( "String not long enough to specify length and capacity." ) ; } final int numActive = Integer . parseInt ( tokens [ 0 ] ) ; final int length = Integer . parseInt ( tokens [ 1 ] ) ; final ReversePurgeLongHashMap table = new ReversePurgeLongHashMap ( length ) ; int j = 2 ; for ( int i = 0 ; i < numActive ; i ++ ) { final long key = Long . parseLong ( tokens [ j ++ ] ) ; final long value = Long . parseLong ( tokens [ j ++ ] ) ; table . adjustOrPutValue ( key , value ) ; } return table ; }
Returns an instance of this class from the given String which must be a String representation of this class .
32,074
String serializeToString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "%d,%d," , numActive , keys . length ) ) ; for ( int i = 0 ; i < keys . length ; i ++ ) { if ( states [ i ] != 0 ) { sb . append ( String . format ( "%d,%d," , keys [ i ] , values [ i ] ) ) ; } } return sb . toString ( ) ; }
Returns a String representation of this hash map .
32,075
void keepOnlyPositiveCounts ( ) { int firstProbe = keys . length - 1 ; while ( states [ firstProbe ] > 0 ) { firstProbe -- ; } for ( int probe = firstProbe ; probe -- > 0 ; ) { if ( ( states [ probe ] > 0 ) && ( values [ probe ] <= 0 ) ) { hashDelete ( probe ) ; numActive -- ; } } for ( int probe = keys . length ; probe -- > firstProbe ; ) { if ( ( states [ probe ] > 0 ) && ( values [ probe ] <= 0 ) ) { hashDelete ( probe ) ; numActive -- ; } } }
Processes the map arrays and retains only keys with positive counts .
32,076
public static double getLowerBoundForBoverA ( final Sketch sketchA , final Sketch sketchB ) { final double thetaA = sketchA . getTheta ( ) ; final double thetaB = sketchB . getTheta ( ) ; checkThetas ( thetaA , thetaB ) ; final int countB = sketchB . getRetainedEntries ( true ) ; final int countA = ( thetaB == thetaA ) ? sketchA . getRetainedEntries ( true ) : sketchA . getCountLessThanTheta ( thetaB ) ; if ( countA <= 0 ) { return 0 ; } return BoundsOnRatiosInSampledSets . getLowerBoundForBoverA ( countA , countB , thetaB ) ; }
Gets the approximate lower bound for B over A based on a 95% confidence interval
32,077
static < T > void blockyTandemMergeSort ( final T [ ] keyArr , final long [ ] valArr , final int arrLen , final int blkSize , final Comparator < ? super T > comparator ) { assert blkSize >= 1 ; if ( arrLen <= blkSize ) { return ; } int numblks = arrLen / blkSize ; if ( ( numblks * blkSize ) < arrLen ) { numblks += 1 ; } assert ( ( numblks * blkSize ) >= arrLen ) ; final T [ ] keyTmp = Arrays . copyOf ( keyArr , arrLen ) ; final long [ ] valTmp = Arrays . copyOf ( valArr , arrLen ) ; blockyTandemMergeSortRecursion ( keyTmp , valTmp , keyArr , valArr , 0 , numblks , blkSize , arrLen , comparator ) ; }
also used by ItemsAuxiliary
32,078
public static int decodeValue ( final short encodedSize ) { final int value = encodedSize & 0xFFFF ; if ( value > MAX_ENC_VALUE ) { throw new SketchesArgumentException ( "Maximum valid encoded value is " + Integer . toHexString ( MAX_ENC_VALUE ) + ", found: " + value ) ; } final int p = ( value >>> EXPONENT_SHIFT ) & EXPONENT_MASK ; final int i = value & INDEX_MASK ; return ( int ) ( ( 1 << p ) * ( ( i * INV_BINS_PER_OCTAVE ) + 1.0 ) ) ; }
Decodes the 16 - bit reservoir size value into an int .
32,079
public static ConcurrentLimitRule of ( int concurrentLimit , TimeUnit timeOutUnit , long timeOut ) { requireNonNull ( timeOutUnit , "time out unit can not be null" ) ; return new ConcurrentLimitRule ( concurrentLimit , timeOutUnit . toMillis ( timeOut ) ) ; }
Initialise a concurrent rate limit .
32,080
public static RequestLimitRule of ( Duration duration , long limit ) { checkDuration ( duration ) ; if ( limit < 0 ) { throw new IllegalArgumentException ( "limit must be greater than zero." ) ; } int durationSeconds = ( int ) duration . getSeconds ( ) ; return new RequestLimitRule ( durationSeconds , limit , durationSeconds ) ; }
Initialise a request rate limit . Imagine the whole duration window as being one large bucket with a single count .
32,081
public RequestLimitRule withName ( String name ) { return new RequestLimitRule ( this . durationSeconds , this . limit , this . precision , name , this . keys ) ; }
Applies a name to the rate limit that is useful for metrics .
32,082
public RequestLimitRule matchingKeys ( String ... keys ) { Set < String > keySet = keys . length > 0 ? new HashSet < > ( Arrays . asList ( keys ) ) : null ; return matchingKeys ( keySet ) ; }
Applies a key to the rate limit that defines to which keys the rule applies empty for any unmatched key .
32,083
public RequestLimitRule matchingKeys ( Set < String > keys ) { return new RequestLimitRule ( this . durationSeconds , this . limit , this . precision , this . name , keys ) ; }
Applies a key to the rate limit that defines to which keys the rule applies null for any unmatched key .
32,084
public void addScopeBindings ( Map < Class < ? extends Annotation > , Scope > bindings ) { if ( scopeCleaner . isRunning ( ) ) { scopeBindings . putAll ( bindings ) ; } }
allows late - binding of scopes to PreDestroyMonitor useful if more than one Injector contributes scope bindings
32,085
public void close ( ) throws Exception { if ( scopeCleaner . close ( ) ) { LOGGER . info ( "closing PreDestroyMonitor..." ) ; List < Map . Entry < Object , UnscopedCleanupAction > > actions = new ArrayList < > ( cleanupActions . entrySet ( ) ) ; if ( actions . size ( ) > 0 ) { LOGGER . warn ( "invoking predestroy action for {} unscoped instances" , actions . size ( ) ) ; actions . stream ( ) . map ( Map . Entry :: getValue ) . collect ( Collectors . groupingBy ( UnscopedCleanupAction :: getContext , Collectors . counting ( ) ) ) . forEach ( ( source , count ) -> { LOGGER . warn ( " including {} objects from source '{}'" , count , source ) ; } ) ; } actions . stream ( ) . sorted ( Map . Entry . comparingByValue ( ) ) . forEach ( action -> { Optional . ofNullable ( action . getKey ( ) ) . ifPresent ( obj -> action . getValue ( ) . call ( obj ) ) ; } ) ; actions . clear ( ) ; cleanupActions . clear ( ) ; scopeBindings . clear ( ) ; scopeBindings = Collections . emptyMap ( ) ; } else { LOGGER . warn ( "PreDestroyMonitor.close() invoked but instance is not running" ) ; } }
final cleanup of managed instances if any
32,086
public InjectorBuilder combineWith ( Module ... modules ) { List < Module > m = new ArrayList < > ( ) ; m . add ( module ) ; m . addAll ( Arrays . asList ( modules ) ) ; this . module = Modules . combine ( m ) ; return this ; }
Add additional bindings to the module tracked by the DSL
32,087
public < T > InjectorBuilder forEachElement ( ElementVisitor < T > visitor , Consumer < T > consumer ) { Elements . getElements ( module ) . forEach ( element -> Optional . ofNullable ( element . acceptVisitor ( visitor ) ) . ifPresent ( consumer ) ) ; return this ; }
Iterate through all elements of the current module and pass the output of the ElementVisitor to the provided consumer . null responses from the visitor are ignored .
32,088
public < T > InjectorBuilder forEachElement ( ElementVisitor < T > visitor ) { Elements . getElements ( module ) . forEach ( element -> element . acceptVisitor ( visitor ) ) ; return this ; }
Call the provided visitor for all elements of the current module .
32,089
public InjectorBuilder filter ( ElementVisitor < Boolean > predicate ) { List < Element > elements = new ArrayList < Element > ( ) ; for ( Element element : Elements . getElements ( Stage . TOOL , module ) ) { if ( element . acceptVisitor ( predicate ) ) { elements . add ( element ) ; } } this . module = Elements . getModule ( elements ) ; return this ; }
Filter out elements for which the provided visitor returns true .
32,090
public static Module combineAndOverride ( List < ? extends Module > modules ) { Iterator < ? extends Module > iter = modules . iterator ( ) ; Module current = Modules . EMPTY_MODULE ; if ( iter . hasNext ( ) ) { current = iter . next ( ) ; if ( iter . hasNext ( ) ) { current = Modules . override ( current ) . with ( iter . next ( ) ) ; } } return current ; }
Generate a single module that is produced by accumulating and overriding each module with the next .
32,091
public static Module fromClass ( final Class < ? > cls , final boolean override ) { List < Module > modules = new ArrayList < > ( ) ; for ( final Annotation annot : cls . getDeclaredAnnotations ( ) ) { final Class < ? extends Annotation > type = annot . annotationType ( ) ; Bootstrap bootstrap = type . getAnnotation ( Bootstrap . class ) ; if ( bootstrap != null ) { LOG . info ( "Adding Module {}" , bootstrap . module ( ) ) ; try { modules . add ( bootstrap . module ( ) . getConstructor ( type ) . newInstance ( annot ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } try { if ( override ) { return Modules . override ( combineAndOverride ( modules ) ) . with ( ( Module ) cls . newInstance ( ) ) ; } else { return Modules . combine ( Modules . combine ( modules ) , ( Module ) cls . newInstance ( ) ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Create a single module that derived from all bootstrap annotations on a class where that class itself is a module .
32,092
public < T > Governator setFeature ( GovernatorFeature < T > feature , T value ) { this . featureOverrides . put ( feature , value ) ; return this ; }
Set a feature
32,093
private LifecycleInjector run ( Module externalModule , final String [ ] args ) { return InjectorBuilder . fromModules ( modules ) . combineWith ( externalModule ) . map ( new ModuleTransformer ( ) { public Module transform ( Module module ) { List < Module > modulesToTransform = Collections . singletonList ( module ) ; for ( ModuleListTransformer transformer : transformers ) { modulesToTransform = transformer . transform ( Collections . unmodifiableList ( modulesToTransform ) ) ; } return Modules . combine ( modulesToTransform ) ; } } ) . overrideWith ( overrideModules ) . createInjector ( new LifecycleInjectorCreator ( ) . withArguments ( args ) . withFeatures ( featureOverrides ) . withProfiles ( profiles ) ) ; }
Create the injector and call any LifecycleListeners
32,094
public String toFile ( ) throws Exception { File file = File . createTempFile ( "GuiceDependencies_" , ".dot" ) ; toFile ( file ) ; return file . getCanonicalPath ( ) ; }
Writes the Dot graph to a new temp file .
32,095
public void toFile ( File file ) throws Exception { PrintWriter out = new PrintWriter ( file , "UTF-8" ) ; try { out . write ( graph ( ) ) ; } finally { Closeables . close ( out , true ) ; } }
Writes the Dot graph to a given file .
32,096
public String graph ( ) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; PrintWriter out = new PrintWriter ( baos ) ; Injector localInjector = Guice . createInjector ( new GraphvizModule ( ) ) ; GraphvizGrapher renderer = localInjector . getInstance ( GraphvizGrapher . class ) ; renderer . setOut ( out ) ; renderer . setRankdir ( "TB" ) ; if ( ! roots . isEmpty ( ) ) { renderer . graph ( injector , roots ) ; } renderer . graph ( injector ) ; return fixupGraph ( baos . toString ( "UTF-8" ) ) ; }
Returns a String containing the Dot graph definition .
32,097
public boolean isGuiceConstructorInjected ( Class < ? > c ) { for ( Constructor < ? > con : c . getDeclaredConstructors ( ) ) { if ( isInjectable ( con ) ) { return true ; } } return false ; }
Determine if a class is an implicit Guice component that can be instantiated by Guice and the life - cycle managed by Jersey .
32,098
public Map < Scope , ComponentScope > createScopeMap ( ) { Map < Scope , ComponentScope > result = new HashMap < Scope , ComponentScope > ( ) ; result . put ( Scopes . SINGLETON , ComponentScope . Singleton ) ; result . put ( Scopes . NO_SCOPE , ComponentScope . PerRequest ) ; result . put ( ServletScopes . REQUEST , ComponentScope . PerRequest ) ; return result ; }
Maps a Guice scope to a Jersey scope .
32,099
void addColumn ( String columnName ) { data . add ( new ArrayList < String > ( ) ) ; columnNames . add ( columnName ) ; }
Add a column