repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/hllmap/UniqueCountMap.java | UniqueCountMap.getMemoryUsageBytes | public long getMemoryUsageBytes() {
long total = 0;
for (int i = 0; i < maps_.length; i++) {
if (maps_[i] != null) {
total += maps_[i].getMemoryUsageBytes();
}
}
return total;
} | java | public long getMemoryUsageBytes() {
long total = 0;
for (int i = 0; i < maps_.length; i++) {
if (maps_[i] != null) {
total += maps_[i].getMemoryUsageBytes();
}
}
return total;
} | [
"public",
"long",
"getMemoryUsageBytes",
"(",
")",
"{",
"long",
"total",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"maps_",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"maps_",
"[",
"i",
"]",
"!=",
"null",
")",
"... | Returns total bytes used by all internal maps
@return total bytes used by all internal maps | [
"Returns",
"total",
"bytes",
"used",
"by",
"all",
"internal",
"maps"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hllmap/UniqueCountMap.java#L196-L204 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/hllmap/UniqueCountMap.java | UniqueCountMap.getKeyMemoryUsageBytes | 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;
} | java | 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;
} | [
"public",
"long",
"getKeyMemoryUsageBytes",
"(",
")",
"{",
"long",
"total",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"maps_",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"maps_",
"[",
"i",
"]",
"!=",
"null",
")",
... | Returns total bytes used for key storage
@return total bytes used for key storage | [
"Returns",
"total",
"bytes",
"used",
"for",
"key",
"storage"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hllmap/UniqueCountMap.java#L210-L218 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/hllmap/UniqueCountMap.java | UniqueCountMap.getActiveMaps | int getActiveMaps() {
int levels = 0;
final int iMapsLen = maps_.length;
for (int i = 0; i < iMapsLen; i++) {
if (maps_[i] != null) { levels++; }
}
return levels;
} | java | int getActiveMaps() {
int levels = 0;
final int iMapsLen = maps_.length;
for (int i = 0; i < iMapsLen; i++) {
if (maps_[i] != null) { levels++; }
}
return levels;
} | [
"int",
"getActiveMaps",
"(",
")",
"{",
"int",
"levels",
"=",
"0",
";",
"final",
"int",
"iMapsLen",
"=",
"maps_",
".",
"length",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"iMapsLen",
";",
"i",
"++",
")",
"{",
"if",
"(",
"maps_",
"[",... | 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.
@return the number of active levels so far | [
"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",
... | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hllmap/UniqueCountMap.java#L235-L242 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/ConcurrentHeapThetaBuffer.java | ConcurrentHeapThetaBuffer.propagateToSharedSketch | private boolean propagateToSharedSketch(final long hash) {
//noinspection StatementWithEmptyBody
while (localPropagationInProgress.get()) {
} //busy wait until previous propagation completed
localPropagationInProgress.set(true);
final boolean res = shared.propagate(localPropagationInProgress, null, hash);
//in this case the parent empty_ and curCount_ were not touched
thetaLong_ = shared.getVolatileTheta();
return res;
} | java | private boolean propagateToSharedSketch(final long hash) {
//noinspection StatementWithEmptyBody
while (localPropagationInProgress.get()) {
} //busy wait until previous propagation completed
localPropagationInProgress.set(true);
final boolean res = shared.propagate(localPropagationInProgress, null, hash);
//in this case the parent empty_ and curCount_ were not touched
thetaLong_ = shared.getVolatileTheta();
return res;
} | [
"private",
"boolean",
"propagateToSharedSketch",
"(",
"final",
"long",
"hash",
")",
"{",
"//noinspection StatementWithEmptyBody",
"while",
"(",
"localPropagationInProgress",
".",
"get",
"(",
")",
")",
"{",
"}",
"//busy wait until previous propagation completed",
"localPropa... | Propagates a single hash value to the shared sketch
@param hash to be propagated | [
"Propagates",
"a",
"single",
"hash",
"value",
"to",
"the",
"shared",
"sketch"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/ConcurrentHeapThetaBuffer.java#L162-L171 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/ConcurrentHeapThetaBuffer.java | ConcurrentHeapThetaBuffer.propagateToSharedSketch | private void propagateToSharedSketch() {
//noinspection StatementWithEmptyBody
while (localPropagationInProgress.get()) {
} //busy wait until previous propagation completed
final CompactSketch compactSketch = compact(propagateOrderedCompact, null);
localPropagationInProgress.set(true);
shared.propagate(localPropagationInProgress, compactSketch,
ConcurrentSharedThetaSketch.NOT_SINGLE_HASH);
super.reset();
thetaLong_ = shared.getVolatileTheta();
} | java | private void propagateToSharedSketch() {
//noinspection StatementWithEmptyBody
while (localPropagationInProgress.get()) {
} //busy wait until previous propagation completed
final CompactSketch compactSketch = compact(propagateOrderedCompact, null);
localPropagationInProgress.set(true);
shared.propagate(localPropagationInProgress, compactSketch,
ConcurrentSharedThetaSketch.NOT_SINGLE_HASH);
super.reset();
thetaLong_ = shared.getVolatileTheta();
} | [
"private",
"void",
"propagateToSharedSketch",
"(",
")",
"{",
"//noinspection StatementWithEmptyBody",
"while",
"(",
"localPropagationInProgress",
".",
"get",
"(",
")",
")",
"{",
"}",
"//busy wait until previous propagation completed",
"final",
"CompactSketch",
"compactSketch"... | Propagates the content of the buffer as a sketch to the shared sketch | [
"Propagates",
"the",
"content",
"of",
"the",
"buffer",
"as",
"a",
"sketch",
"to",
"the",
"shared",
"sketch"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/ConcurrentHeapThetaBuffer.java#L176-L187 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/DoublesSketchAccessor.java | DoublesSketchAccessor.countValidLevelsBelow | 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;
// shorter implementation, testing suggests a tiny bit slower
//final long mask = (1 << tgtLvl) - 1;
//return Long.bitCount(ds_.getBitPattern() & mask);
} | java | 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;
// shorter implementation, testing suggests a tiny bit slower
//final long mask = (1 << tgtLvl) - 1;
//return Long.bitCount(ds_.getBitPattern() & mask);
} | [
"private",
"int",
"countValidLevelsBelow",
"(",
"final",
"int",
"tgtLvl",
")",
"{",
"int",
"count",
"=",
"0",
";",
"long",
"bitPattern",
"=",
"ds_",
".",
"getBitPattern",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"(",
"i",
"<",
"tgtLvl",
... | Counts number of full levels in the sketch below tgtLvl. Useful for computing the level
offset in a compact sketch.
@param tgtLvl Target level in the sketch
@return Number of full levels in the sketch below tgtLvl | [
"Counts",
"number",
"of",
"full",
"levels",
"in",
"the",
"sketch",
"below",
"tgtLvl",
".",
"Useful",
"for",
"computing",
"the",
"level",
"offset",
"in",
"a",
"compact",
"sketch",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/DoublesSketchAccessor.java#L118-L131 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/Util.java | Util.checkFamilyID | 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());
}
} | java | 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());
}
} | [
"static",
"void",
"checkFamilyID",
"(",
"final",
"int",
"familyID",
")",
"{",
"final",
"Family",
"family",
"=",
"Family",
".",
"idToFamily",
"(",
"familyID",
")",
";",
"if",
"(",
"!",
"family",
".",
"equals",
"(",
"Family",
".",
"QUANTILES",
")",
")",
... | Checks the validity of the given family ID
@param familyID the given family ID | [
"Checks",
"the",
"validity",
"of",
"the",
"given",
"family",
"ID"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L225-L231 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/Util.java | Util.checkPreLongsFlagsCap | static boolean checkPreLongsFlagsCap(final int preambleLongs, final int flags, final long memCapBytes) {
final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state
final int minPre = Family.QUANTILES.getMinPreLongs(); //1
final int maxPre = Family.QUANTILES.getMaxPreLongs(); //2
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;
} | java | static boolean checkPreLongsFlagsCap(final int preambleLongs, final int flags, final long memCapBytes) {
final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state
final int minPre = Family.QUANTILES.getMinPreLongs(); //1
final int maxPre = Family.QUANTILES.getMaxPreLongs(); //2
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;
} | [
"static",
"boolean",
"checkPreLongsFlagsCap",
"(",
"final",
"int",
"preambleLongs",
",",
"final",
"int",
"flags",
",",
"final",
"long",
"memCapBytes",
")",
"{",
"final",
"boolean",
"empty",
"=",
"(",
"flags",
"&",
"EMPTY_FLAG_MASK",
")",
">",
"0",
";",
"//Pr... | Checks the consistency of the flag bits and the state of preambleLong and the memory
capacity and returns the empty state.
@param preambleLongs the size of preamble in longs
@param flags the flags field
@param memCapBytes the memory capacity
@return the value of the empty state | [
"Checks",
"the",
"consistency",
"of",
"the",
"flag",
"bits",
"and",
"the",
"state",
"of",
"preambleLong",
"and",
"the",
"memory",
"capacity",
"and",
"returns",
"the",
"empty",
"state",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L241-L256 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/Util.java | Util.checkHeapFlags | static void checkHeapFlags(final int flags) { //only used by checkPreLongsFlagsCap and test
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));
}
} | java | static void checkHeapFlags(final int flags) { //only used by checkPreLongsFlagsCap and test
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));
}
} | [
"static",
"void",
"checkHeapFlags",
"(",
"final",
"int",
"flags",
")",
"{",
"//only used by checkPreLongsFlagsCap and test",
"final",
"int",
"allowedFlags",
"=",
"READ_ONLY_FLAG_MASK",
"|",
"EMPTY_FLAG_MASK",
"|",
"COMPACT_FLAG_MASK",
"|",
"ORDERED_FLAG_MASK",
";",
"final... | Checks just the flags field of the preamble. Allowed flags are Read Only, Empty, Compact, and
ordered.
@param flags the flags field | [
"Checks",
"just",
"the",
"flags",
"field",
"of",
"the",
"preamble",
".",
"Allowed",
"flags",
"are",
"Read",
"Only",
"Empty",
"Compact",
"and",
"ordered",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L263-L271 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/Util.java | Util.checkIsCompactMemory | static boolean checkIsCompactMemory(final Memory srcMem) {
// only reading so downcast is ok
final int flags = extractFlags(srcMem);
final int compactFlags = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK;
return (flags & compactFlags) > 0;
} | java | static boolean checkIsCompactMemory(final Memory srcMem) {
// only reading so downcast is ok
final int flags = extractFlags(srcMem);
final int compactFlags = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK;
return (flags & compactFlags) > 0;
} | [
"static",
"boolean",
"checkIsCompactMemory",
"(",
"final",
"Memory",
"srcMem",
")",
"{",
"// only reading so downcast is ok",
"final",
"int",
"flags",
"=",
"extractFlags",
"(",
"srcMem",
")",
";",
"final",
"int",
"compactFlags",
"=",
"READ_ONLY_FLAG_MASK",
"|",
"COM... | 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.
@param srcMem the source Memory containing a sketch
@return true if flags indicate a compact sketch, otherwise false | [
"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... | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L280-L285 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/Util.java | Util.checkSplitPointsOrder | 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.");
}
} | java | 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.");
}
} | [
"static",
"final",
"void",
"checkSplitPointsOrder",
"(",
"final",
"double",
"[",
"]",
"values",
")",
"{",
"if",
"(",
"values",
"==",
"null",
")",
"{",
"throw",
"new",
"SketchesArgumentException",
"(",
"\"Values cannot be null.\"",
")",
";",
"}",
"final",
"int"... | Checks the sequential validity of the given array of double values.
They must be unique, monotonically increasing and not NaN.
@param values the given array of double values | [
"Checks",
"the",
"sequential",
"validity",
"of",
"the",
"given",
"array",
"of",
"double",
"values",
".",
"They",
"must",
"be",
"unique",
"monotonically",
"increasing",
"and",
"not",
"NaN",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L292-L302 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/Util.java | Util.computeRetainedItems | 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);
} | java | 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);
} | [
"static",
"int",
"computeRetainedItems",
"(",
"final",
"int",
"k",
",",
"final",
"long",
"n",
")",
"{",
"final",
"int",
"bbCnt",
"=",
"computeBaseBufferItems",
"(",
"k",
",",
"n",
")",
";",
"final",
"long",
"bitPattern",
"=",
"computeBitPattern",
"(",
"k",... | Returns the number of retained valid items in the sketch given k and n.
@param k the given configured k of the sketch
@param n the current number of items seen by the sketch
@return the number of retained items in the sketch given k and n. | [
"Returns",
"the",
"number",
"of",
"retained",
"valid",
"items",
"in",
"the",
"sketch",
"given",
"k",
"and",
"n",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L321-L326 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcCompression.java | CpcCompression.lowLevelCompressBytes | static int lowLevelCompressBytes(
final byte[] byteArray, // input
final int numBytesToEncode, // input, must be an int
final short[] encodingTable, // input
final int[] compressedWords) { // output
int nextWordIndex = 0;
long bitBuf = 0; // bits are packed into this first, then are flushed to compressedWords
int bufBits = 0; // number of bits currently in bitbuf; must be between 0 and 31
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;
//MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex);
if (bufBits >= 32) {
compressedWords[nextWordIndex++] = (int) bitBuf;
bitBuf >>>= 32;
bufBits -= 32;
}
}
//Pad the bitstream with 11 zero-bits so that the decompressor's 12-bit peek
// can't overrun its input.
bufBits += 11;
//MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex);
if (bufBits >= 32) {
compressedWords[nextWordIndex++] = (int) bitBuf;
bitBuf >>>= 32;
bufBits -= 32;
}
if (bufBits > 0) { // We are done encoding now, so we flush the bit buffer.
assert (bufBits < 32);
compressedWords[nextWordIndex++] = (int) bitBuf;
}
return nextWordIndex;
} | java | static int lowLevelCompressBytes(
final byte[] byteArray, // input
final int numBytesToEncode, // input, must be an int
final short[] encodingTable, // input
final int[] compressedWords) { // output
int nextWordIndex = 0;
long bitBuf = 0; // bits are packed into this first, then are flushed to compressedWords
int bufBits = 0; // number of bits currently in bitbuf; must be between 0 and 31
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;
//MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex);
if (bufBits >= 32) {
compressedWords[nextWordIndex++] = (int) bitBuf;
bitBuf >>>= 32;
bufBits -= 32;
}
}
//Pad the bitstream with 11 zero-bits so that the decompressor's 12-bit peek
// can't overrun its input.
bufBits += 11;
//MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex);
if (bufBits >= 32) {
compressedWords[nextWordIndex++] = (int) bitBuf;
bitBuf >>>= 32;
bufBits -= 32;
}
if (bufBits > 0) { // We are done encoding now, so we flush the bit buffer.
assert (bufBits < 32);
compressedWords[nextWordIndex++] = (int) bitBuf;
}
return nextWordIndex;
} | [
"static",
"int",
"lowLevelCompressBytes",
"(",
"final",
"byte",
"[",
"]",
"byteArray",
",",
"// input",
"final",
"int",
"numBytesToEncode",
",",
"// input, must be an int",
"final",
"short",
"[",
"]",
"encodingTable",
",",
"// input",
"final",
"int",
"[",
"]",
"... | It is the caller's responsibility to ensure that the compressedWords array is long enough. | [
"It",
"is",
"the",
"caller",
"s",
"responsibility",
"to",
"ensure",
"that",
"the",
"compressedWords",
"array",
"is",
"long",
"enough",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcCompression.java#L137-L177 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcCompression.java | CpcCompression.uncompressTheSurprisingValues | 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;
} | java | 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;
} | [
"private",
"static",
"int",
"[",
"]",
"uncompressTheSurprisingValues",
"(",
"final",
"CompressedState",
"source",
")",
"{",
"final",
"int",
"srcK",
"=",
"1",
"<<",
"source",
".",
"lgK",
";",
"final",
"int",
"numPairs",
"=",
"source",
".",
"numCsv",
";",
"a... | the length of this array is known to the source sketch. | [
"the",
"length",
"of",
"this",
"array",
"is",
"known",
"to",
"the",
"source",
"sketch",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcCompression.java#L510-L518 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcCompression.java | CpcCompression.trickyGetPairsFromWindow | 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);
// assert (colIndex < 8);
wByte ^= (1 << colIndex); // erase the 1
pairs[pairIndex++] = (rowIndex << 6) | colIndex;
}
}
assert (pairIndex == outputLength);
return (pairs);
} | java | 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);
// assert (colIndex < 8);
wByte ^= (1 << colIndex); // erase the 1
pairs[pairIndex++] = (rowIndex << 6) | colIndex;
}
}
assert (pairIndex == outputLength);
return (pairs);
} | [
"private",
"static",
"int",
"[",
"]",
"trickyGetPairsFromWindow",
"(",
"final",
"byte",
"[",
"]",
"window",
",",
"final",
"int",
"k",
",",
"final",
"int",
"numPairsToGet",
",",
"final",
"int",
"emptySpace",
")",
"{",
"final",
"int",
"outputLength",
"=",
"e... | will be filled in later by the caller. | [
"will",
"be",
"filled",
"in",
"later",
"by",
"the",
"caller",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcCompression.java#L540-L557 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcCompression.java | CpcCompression.compressHybridFlavor | 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; // because the window offset is zero
assert numPairs < Integer.MAX_VALUE;
final int numPairsFromArray = (int) numPairs;
assert (numPairsFromArray + srcNumPairs) == srcNumCoupons; //for test
final int[] allPairs
= trickyGetPairsFromWindow(srcSlidingWindow, srcK, numPairsFromArray, srcNumPairs);
PairTable.merge(srcPairArr, 0, srcNumPairs,
allPairs, srcNumPairs, numPairsFromArray,
allPairs, 0); // note the overlapping subarray trick
//FOR TESTING If needed
// for (int i = 0; i < (source.numCoupons - 1); i++) {
// assert (Integer.compareUnsigned(allPairs[i], allPairs[i + 1]) < 0); }
compressTheSurprisingValues(target, source, allPairs, (int) srcNumCoupons);
} | java | 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; // because the window offset is zero
assert numPairs < Integer.MAX_VALUE;
final int numPairsFromArray = (int) numPairs;
assert (numPairsFromArray + srcNumPairs) == srcNumCoupons; //for test
final int[] allPairs
= trickyGetPairsFromWindow(srcSlidingWindow, srcK, numPairsFromArray, srcNumPairs);
PairTable.merge(srcPairArr, 0, srcNumPairs,
allPairs, srcNumPairs, numPairsFromArray,
allPairs, 0); // note the overlapping subarray trick
//FOR TESTING If needed
// for (int i = 0; i < (source.numCoupons - 1); i++) {
// assert (Integer.compareUnsigned(allPairs[i], allPairs[i + 1]) < 0); }
compressTheSurprisingValues(target, source, allPairs, (int) srcNumCoupons);
} | [
"private",
"static",
"void",
"compressHybridFlavor",
"(",
"final",
"CompressedState",
"target",
",",
"final",
"CpcSketch",
"source",
")",
"{",
"final",
"int",
"srcK",
"=",
"1",
"<<",
"source",
".",
"lgK",
";",
"final",
"PairTable",
"srcPairTable",
"=",
"source... | of a Pinned sketch before compressing it. Hence the name Hybrid. | [
"of",
"a",
"Pinned",
"sketch",
"before",
"compressing",
"it",
".",
"Hence",
"the",
"name",
"Hybrid",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcCompression.java#L561-L589 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcCompression.java | CpcCompression.compressSlidingFlavor | 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);
// Here we apply a complicated transformation to the column indices, which
// changes the implied ordering of the pairs, so we must do it before sorting.
final int pseudoPhase = determinePseudoPhase(source.lgK, source.numCoupons); // NB
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);
// first rotate the columns into a canonical configuration:
// new = ((old - (offset+8)) + 64) mod 64
col = ((col + 56) - offset) & 63;
assert (col >= 0) && (col < 56);
// then apply the permutation
col = permutation[col];
pairs[i] = (row << 6) | col;
}
introspectiveInsertionSort(pairs, 0, numPairs - 1);
compressTheSurprisingValues(target, source, pairs, numPairs);
}
} | java | 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);
// Here we apply a complicated transformation to the column indices, which
// changes the implied ordering of the pairs, so we must do it before sorting.
final int pseudoPhase = determinePseudoPhase(source.lgK, source.numCoupons); // NB
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);
// first rotate the columns into a canonical configuration:
// new = ((old - (offset+8)) + 64) mod 64
col = ((col + 56) - offset) & 63;
assert (col >= 0) && (col < 56);
// then apply the permutation
col = permutation[col];
pairs[i] = (row << 6) | col;
}
introspectiveInsertionSort(pairs, 0, numPairs - 1);
compressTheSurprisingValues(target, source, pairs, numPairs);
}
} | [
"private",
"static",
"void",
"compressSlidingFlavor",
"(",
"final",
"CompressedState",
"target",
",",
"final",
"CpcSketch",
"source",
")",
"{",
"compressTheWindow",
"(",
"target",
",",
"source",
")",
";",
"final",
"PairTable",
"srcPairTable",
"=",
"source",
".",
... | Complicated by the existence of both a left fringe and a right fringe. | [
"Complicated",
"by",
"the",
"existence",
"of",
"both",
"a",
"left",
"fringe",
"and",
"a",
"right",
"fringe",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcCompression.java#L673-L709 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java | KllFloatsSketch.update | 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;
} | java | 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;
} | [
"public",
"void",
"update",
"(",
"final",
"float",
"value",
")",
"{",
"if",
"(",
"Float",
".",
"isNaN",
"(",
"value",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isEmpty",
"(",
")",
")",
"{",
"minValue_",
"=",
"value",
";",
"maxValue_",
"=",
"... | Updates this sketch with the given data item.
@param value an item from a stream of items. NaNs are ignored. | [
"Updates",
"this",
"sketch",
"with",
"the",
"given",
"data",
"item",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L328-L346 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java | KllFloatsSketch.merge | 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_);
}
} | java | 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_);
}
} | [
"public",
"void",
"merge",
"(",
"final",
"KllFloatsSketch",
"other",
")",
"{",
"if",
"(",
"(",
"other",
"==",
"null",
")",
"||",
"other",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"m_",
"!=",
"other",
".",
"m_",
")",
"{",... | Merges another sketch into this one.
@param other sketch to merge into this one | [
"Merges",
"another",
"sketch",
"into",
"this",
"one",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L352-L371 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java | KllFloatsSketch.getQuantile | 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);
} | java | 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);
} | [
"public",
"float",
"getQuantile",
"(",
"final",
"double",
"fraction",
")",
"{",
"if",
"(",
"isEmpty",
"(",
")",
")",
"{",
"return",
"Float",
".",
"NaN",
";",
"}",
"if",
"(",
"fraction",
"==",
"0.0",
")",
"{",
"return",
"minValue_",
";",
"}",
"if",
... | 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.
<p>We note that this method has a fairly large overhead (microseconds instead of nanoseconds)
so it should not be called multiple times to get different quantiles from the same
sketch. Instead use getQuantiles(), which pays the overhead only once.
<p>If the sketch is empty this returns NaN.
@param fraction the specified fractional position in the hypothetical sorted stream.
These are also called normalized ranks or fractional ranks.
If fraction = 0.0, the true minimum value of the stream is returned.
If fraction = 1.0, the true maximum value of the stream is returned.
@return the approximation to the value at the given 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",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L411-L420 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java | KllFloatsSketch.getKFromEpsilon | public static int getKFromEpsilon(final double epsilon, final boolean pmf) {
//Ensure that eps is >= than the lowest possible eps given MAX_K and pmf=false.
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));
} | java | public static int getKFromEpsilon(final double epsilon, final boolean pmf) {
//Ensure that eps is >= than the lowest possible eps given MAX_K and pmf=false.
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));
} | [
"public",
"static",
"int",
"getKFromEpsilon",
"(",
"final",
"double",
"epsilon",
",",
"final",
"boolean",
"pmf",
")",
"{",
"//Ensure that eps is >= than the lowest possible eps given MAX_K and pmf=false.",
"final",
"double",
"eps",
"=",
"max",
"(",
"epsilon",
",",
"4.76... | thousands of trials | [
"thousands",
"of",
"trials"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L653-L663 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java | KllFloatsSketch.toByteArray | 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;
// the last integer in levels_ is not serialized because it can be derived
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;
} | java | 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;
// the last integer in levels_ is not serialized because it can be derived
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;
} | [
"public",
"byte",
"[",
"]",
"toByteArray",
"(",
")",
"{",
"final",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"getSerializedSizeBytes",
"(",
")",
"]",
";",
"final",
"boolean",
"isSingleItem",
"=",
"n_",
"==",
"1",
";",
"bytes",
"[",
"PREAMBLE_... | Returns serialized sketch in a byte array form.
@return serialized sketch in a byte array form. | [
"Returns",
"serialized",
"sketch",
"in",
"a",
"byte",
"array",
"form",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L757-L793 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java | KllFloatsSketch.heapify | 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);
} | java | 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);
} | [
"public",
"static",
"KllFloatsSketch",
"heapify",
"(",
"final",
"Memory",
"mem",
")",
"{",
"final",
"int",
"preambleInts",
"=",
"mem",
".",
"getByte",
"(",
"PREAMBLE_INTS_BYTE",
")",
"&",
"0xff",
";",
"final",
"int",
"serialVersion",
"=",
"mem",
".",
"getByt... | 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.
@param mem a Memory image of a sketch.
<a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@return a heap-based sketch based on the given Memory | [
"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",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L802-L835 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java | KllFloatsSketch.checkK | 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);
}
} | java | 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);
}
} | [
"static",
"void",
"checkK",
"(",
"final",
"int",
"k",
")",
"{",
"if",
"(",
"(",
"k",
"<",
"MIN_K",
")",
"||",
"(",
"k",
">",
"MAX_K",
")",
")",
"{",
"throw",
"new",
"SketchesArgumentException",
"(",
"\"K must be >= \"",
"+",
"MIN_K",
"+",
"\" and <= \"... | Checks the validity of the given value k
@param k must be greater than 7 and less than 65536. | [
"Checks",
"the",
"validity",
"of",
"the",
"given",
"value",
"k"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L845-L850 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java | KllFloatsSketch.compressWhileUpdating | private void compressWhileUpdating() {
final int level = findLevelToCompact();
// It is important to do add the new top level right here. Be aware that this operation
// grows the buffer and shifts the data and also the boundaries of the data and grows the
// levels array and increments numLevels_
if (level == (numLevels_ - 1)) {
addEmptyTopLevelToCompletelyFullSketch();
}
final int rawBeg = levels_[level];
final int rawLim = levels_[level + 1];
// +2 is OK because we already added a new top level if necessary
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;
// level zero might not be sorted, so we must sort it if we wish to compact it
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; // adjust boundaries of the level above
if (oddPop) {
levels_[level] = levels_[level + 1] - 1; // the current level now contains one item
items_[levels_[level]] = items_[rawBeg]; // namely this leftover guy
} else {
levels_[level] = levels_[level + 1]; // the current level is now empty
}
// verify that we freed up halfAdjPop array slots just below the current level
assert levels_[level] == (rawBeg + halfAdjPop);
// finally, we need to shift up the data in the levels below
// so that the freed-up space can be used by level zero
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;
}
}
} | java | private void compressWhileUpdating() {
final int level = findLevelToCompact();
// It is important to do add the new top level right here. Be aware that this operation
// grows the buffer and shifts the data and also the boundaries of the data and grows the
// levels array and increments numLevels_
if (level == (numLevels_ - 1)) {
addEmptyTopLevelToCompletelyFullSketch();
}
final int rawBeg = levels_[level];
final int rawLim = levels_[level + 1];
// +2 is OK because we already added a new top level if necessary
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;
// level zero might not be sorted, so we must sort it if we wish to compact it
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; // adjust boundaries of the level above
if (oddPop) {
levels_[level] = levels_[level + 1] - 1; // the current level now contains one item
items_[levels_[level]] = items_[rawBeg]; // namely this leftover guy
} else {
levels_[level] = levels_[level + 1]; // the current level is now empty
}
// verify that we freed up halfAdjPop array slots just below the current level
assert levels_[level] == (rawBeg + halfAdjPop);
// finally, we need to shift up the data in the levels below
// so that the freed-up space can be used by level zero
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;
}
}
} | [
"private",
"void",
"compressWhileUpdating",
"(",
")",
"{",
"final",
"int",
"level",
"=",
"findLevelToCompact",
"(",
")",
";",
"// It is important to do add the new top level right here. Be aware that this operation",
"// grows the buffer and shifts the data and also the boundaries of t... | It cannot be used while merging, while reducing k, or anything else. | [
"It",
"cannot",
"be",
"used",
"while",
"merging",
"while",
"reducing",
"k",
"or",
"anything",
"else",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L924-L975 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/UpdateDoublesSketch.java | UpdateDoublesSketch.compact | public CompactDoublesSketch compact(final WritableMemory dstMem) {
if (dstMem == null) {
return HeapCompactDoublesSketch.createFromUpdateSketch(this);
}
return DirectCompactDoublesSketch.createFromUpdateSketch(this, dstMem);
} | java | public CompactDoublesSketch compact(final WritableMemory dstMem) {
if (dstMem == null) {
return HeapCompactDoublesSketch.createFromUpdateSketch(this);
}
return DirectCompactDoublesSketch.createFromUpdateSketch(this, dstMem);
} | [
"public",
"CompactDoublesSketch",
"compact",
"(",
"final",
"WritableMemory",
"dstMem",
")",
"{",
"if",
"(",
"dstMem",
"==",
"null",
")",
"{",
"return",
"HeapCompactDoublesSketch",
".",
"createFromUpdateSketch",
"(",
"this",
")",
";",
"}",
"return",
"DirectCompactD... | 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.
@param dstMem An optional target memory to hold the sketch.
@return A compact version of this sketch | [
"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",
"... | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/UpdateDoublesSketch.java#L55-L60 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.getInstance | public static <T> ItemsSketch<T> getInstance(final Comparator<? super T> comparator) {
return getInstance(PreambleUtil.DEFAULT_K, comparator);
} | java | public static <T> ItemsSketch<T> getInstance(final Comparator<? super T> comparator) {
return getInstance(PreambleUtil.DEFAULT_K, comparator);
} | [
"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.
@param <T> type of item
@param comparator to compare items
@return a GenericQuantileSketch | [
"Obtains",
"a",
"new",
"instance",
"of",
"an",
"ItemsSketch",
"using",
"the",
"DEFAULT_K",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L125-L127 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.getInstance | 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); //the min is important
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;
} | java | 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); //the min is important
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;
} | [
"public",
"static",
"<",
"T",
">",
"ItemsSketch",
"<",
"T",
">",
"getInstance",
"(",
"final",
"int",
"k",
",",
"final",
"Comparator",
"<",
"?",
"super",
"T",
">",
"comparator",
")",
"{",
"final",
"ItemsSketch",
"<",
"T",
">",
"qs",
"=",
"new",
"Items... | Obtains a new instance of an ItemsSketch.
@param <T> type of item
@param k Parameter that controls space usage of sketch and accuracy of estimates.
Must be greater than 2 and less than 65536 and a power of 2.
@param comparator to compare items
@return a GenericQuantileSketch | [
"Obtains",
"a",
"new",
"instance",
"of",
"an",
"ItemsSketch",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L137-L148 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.getInstance | 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); //checks k
if (empty) { return qs; }
//Not empty, must have valid preamble + min, max
final long n = extractN(srcMem);
//can't check memory capacity here, not enough information
final int extra = 2; //for min, max
final int numMemItems = Util.computeRetainedItems(k, n) + extra;
//set class members
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;
} | java | 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); //checks k
if (empty) { return qs; }
//Not empty, must have valid preamble + min, max
final long n = extractN(srcMem);
//can't check memory capacity here, not enough information
final int extra = 2; //for min, max
final int numMemItems = Util.computeRetainedItems(k, n) + extra;
//set class members
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;
} | [
"public",
"static",
"<",
"T",
">",
"ItemsSketch",
"<",
"T",
">",
"getInstance",
"(",
"final",
"Memory",
"srcMem",
",",
"final",
"Comparator",
"<",
"?",
"super",
"T",
">",
"comparator",
",",
"final",
"ArrayOfItemsSerDe",
"<",
"T",
">",
"serDe",
")",
"{",
... | Heapifies the given srcMem, which must be a Memory image of a ItemsSketch
@param <T> type of item
@param srcMem a Memory image of a sketch.
<a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@param comparator to compare items
@param serDe an instance of ArrayOfItemsSerDe
@return a ItemsSketch on the Java heap. | [
"Heapifies",
"the",
"given",
"srcMem",
"which",
"must",
"be",
"a",
"Memory",
"image",
"of",
"a",
"ItemsSketch"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L159-L205 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.copy | 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;
} | java | 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;
} | [
"static",
"<",
"T",
">",
"ItemsSketch",
"<",
"T",
">",
"copy",
"(",
"final",
"ItemsSketch",
"<",
"T",
">",
"sketch",
")",
"{",
"final",
"ItemsSketch",
"<",
"T",
">",
"qsCopy",
"=",
"ItemsSketch",
".",
"getInstance",
"(",
"sketch",
".",
"k_",
",",
"sk... | Returns a copy of the given sketch
@param <T> the data type
@param sketch the given sketch
@return a copy of the given sketch | [
"Returns",
"a",
"copy",
"of",
"the",
"given",
"sketch"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L213-L224 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.update | public void update(final T dataItem) {
// this method only uses the base buffer part of the combined buffer
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);
}
} | java | public void update(final T dataItem) {
// this method only uses the base buffer part of the combined buffer
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);
}
} | [
"public",
"void",
"update",
"(",
"final",
"T",
"dataItem",
")",
"{",
"// this method only uses the base buffer part of the combined buffer",
"if",
"(",
"dataItem",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"(",
"maxValue_",
"==",
"null",
")",
"||",
... | Updates this sketch with the given double data item
@param dataItem an item from a stream of items. NaNs are ignored. | [
"Updates",
"this",
"sketch",
"with",
"the",
"given",
"double",
"data",
"item"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L230-L245 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.getQuantileUpperBound | public T getQuantileUpperBound(final double fraction) {
return getQuantile(min(1.0, fraction + Util.getNormalizedRankError(k_, false)));
} | java | public T getQuantileUpperBound(final double fraction) {
return getQuantile(min(1.0, fraction + Util.getNormalizedRankError(k_, false)));
} | [
"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%.
@param fraction the given normalized rank as a fraction
@return the upper bound of the value interval in which the true quantile of the given rank
exists with a confidence of at least 99%. Returns NaN if the sketch is empty. | [
"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%",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L282-L284 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.getQuantileLowerBound | public T getQuantileLowerBound(final double fraction) {
return getQuantile(max(0, fraction - Util.getNormalizedRankError(k_, false)));
} | java | public T getQuantileLowerBound(final double fraction) {
return getQuantile(max(0, fraction - Util.getNormalizedRankError(k_, false)));
} | [
"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%.
@param fraction the given normalized rank as a fraction
@return the lower bound of the value interval in which the true quantile of the given rank
exists with a confidence of at least 99%. Returns NaN if the sketch is empty. | [
"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%",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L293-L295 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.reset | public void reset() {
n_ = 0;
combinedBufferItemCapacity_ = 2 * Math.min(DoublesSketch.MIN_K, k_); //the min is important
combinedBuffer_ = new Object[combinedBufferItemCapacity_];
baseBufferCount_ = 0;
bitPattern_ = 0;
minValue_ = null;
maxValue_ = null;
} | java | public void reset() {
n_ = 0;
combinedBufferItemCapacity_ = 2 * Math.min(DoublesSketch.MIN_K, k_); //the min is important
combinedBuffer_ = new Object[combinedBufferItemCapacity_];
baseBufferCount_ = 0;
bitPattern_ = 0;
minValue_ = null;
maxValue_ = null;
} | [
"public",
"void",
"reset",
"(",
")",
"{",
"n_",
"=",
"0",
";",
"combinedBufferItemCapacity_",
"=",
"2",
"*",
"Math",
".",
"min",
"(",
"DoublesSketch",
".",
"MIN_K",
",",
"k_",
")",
";",
"//the min is important",
"combinedBuffer_",
"=",
"new",
"Object",
"["... | Resets this sketch to a virgin state, but retains the original value of k. | [
"Resets",
"this",
"sketch",
"to",
"a",
"virgin",
"state",
"but",
"retains",
"the",
"original",
"value",
"of",
"k",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L568-L576 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.downSample | public ItemsSketch<T> downSample(final int newK) {
final ItemsSketch<T> newSketch = ItemsSketch.getInstance(newK, comparator_);
ItemsMergeImpl.downSamplingMergeInto(this, newSketch);
return newSketch;
} | java | public ItemsSketch<T> downSample(final int newK) {
final ItemsSketch<T> newSketch = ItemsSketch.getInstance(newK, comparator_);
ItemsMergeImpl.downSamplingMergeInto(this, newSketch);
return newSketch;
} | [
"public",
"ItemsSketch",
"<",
"T",
">",
"downSample",
"(",
"final",
"int",
"newK",
")",
"{",
"final",
"ItemsSketch",
"<",
"T",
">",
"newSketch",
"=",
"ItemsSketch",
".",
"getInstance",
"(",
"newK",
",",
"comparator_",
")",
";",
"ItemsMergeImpl",
".",
"down... | From an existing sketch, this creates a new sketch that can have a smaller value of K.
The original sketch is not modified.
@param newK the new value of K that must be smaller than current value of K.
It is required that this.getK() = newK * 2^(nonnegative integer).
@return the new sketch. | [
"From",
"an",
"existing",
"sketch",
"this",
"creates",
"a",
"new",
"sketch",
"that",
"can",
"have",
"a",
"smaller",
"value",
"of",
"K",
".",
"The",
"original",
"sketch",
"is",
"not",
"modified",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L642-L646 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.putMemory | 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);
} | java | 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);
} | [
"public",
"void",
"putMemory",
"(",
"final",
"WritableMemory",
"dstMem",
",",
"final",
"ArrayOfItemsSerDe",
"<",
"T",
">",
"serDe",
")",
"{",
"final",
"byte",
"[",
"]",
"byteArr",
"=",
"toByteArray",
"(",
"serDe",
")",
";",
"final",
"long",
"memCap",
"=",
... | Puts the current sketch into the given Memory if there is sufficient space.
Otherwise, throws an error.
@param dstMem the given memory.
@param serDe an instance of ArrayOfItemsSerDe | [
"Puts",
"the",
"current",
"sketch",
"into",
"the",
"given",
"Memory",
"if",
"there",
"is",
"sufficient",
"space",
".",
"Otherwise",
"throws",
"an",
"error",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L663-L671 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java | ItemsSketch.itemsArrayToCombinedBuffer | private void itemsArrayToCombinedBuffer(final T[] itemsArray) {
final int extra = 2; // space for min and max values
//Load min, max
minValue_ = itemsArray[0];
maxValue_ = itemsArray[1];
//Load base buffer
System.arraycopy(itemsArray, extra, combinedBuffer_, 0, baseBufferCount_);
//Load levels
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_;
}
}
}
} | java | private void itemsArrayToCombinedBuffer(final T[] itemsArray) {
final int extra = 2; // space for min and max values
//Load min, max
minValue_ = itemsArray[0];
maxValue_ = itemsArray[1];
//Load base buffer
System.arraycopy(itemsArray, extra, combinedBuffer_, 0, baseBufferCount_);
//Load levels
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_;
}
}
}
} | [
"private",
"void",
"itemsArrayToCombinedBuffer",
"(",
"final",
"T",
"[",
"]",
"itemsArray",
")",
"{",
"final",
"int",
"extra",
"=",
"2",
";",
"// space for min and max values",
"//Load min, max",
"minValue_",
"=",
"itemsArray",
"[",
"0",
"]",
";",
"maxValue_",
"... | 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.
@param itemsArray the given items array | [
"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",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsSketch.java#L720-L741 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/HeapAnotB.java | HeapAnotB.scanAllAsearchB | 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;
}
} | java | 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;
}
} | [
"private",
"void",
"scanAllAsearchB",
"(",
")",
"{",
"final",
"long",
"[",
"]",
"scanAArr",
"=",
"a_",
".",
"getCache",
"(",
")",
";",
"final",
"int",
"arrLongsIn",
"=",
"scanAArr",
".",
"length",
";",
"cache_",
"=",
"new",
"long",
"[",
"arrLongsIn",
"... | Sketch A is either unordered compact or hash table | [
"Sketch",
"A",
"is",
"either",
"unordered",
"compact",
"or",
"hash",
"table"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/HeapAnotB.java#L262-L273 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java | BoundsOnBinomialProportions.approximateLowerBoundOnP | public static double approximateLowerBoundOnP(final long n, final long k, final double numStdDevs) {
checkInputs(n, k);
if (n == 0) { return 0.0; } // the coin was never flipped, so we know nothing
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); // which is p
}
} | java | public static double approximateLowerBoundOnP(final long n, final long k, final double numStdDevs) {
checkInputs(n, k);
if (n == 0) { return 0.0; } // the coin was never flipped, so we know nothing
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); // which is p
}
} | [
"public",
"static",
"double",
"approximateLowerBoundOnP",
"(",
"final",
"long",
"n",
",",
"final",
"long",
"k",
",",
"final",
"double",
"numStdDevs",
")",
"{",
"checkInputs",
"(",
"n",
",",
"k",
")",
";",
"if",
"(",
"n",
"==",
"0",
")",
"{",
"return",
... | Computes lower bound of approximate Clopper-Pearson confidence interval for a binomial
proportion.
<p>Implementation Notes:<br>
The approximateLowerBoundOnP is defined with respect to the right tail of the binomial
distribution.</p>
<ul>
<li>We want to solve for the <i>p</i> for which sum<sub><i>j,k,n</i></sub>bino(<i>j;n,p</i>)
= delta.</li>
<li>We now restate that in terms of the left tail.</li>
<li>We want to solve for the p for which sum<sub><i>j,0,(k-1)</i></sub>bino(<i>j;n,p</i>)
= 1 - delta.</li>
<li>Define <i>x</i> = 1-<i>p</i>.</li>
<li>We want to solve for the <i>x</i> for which I<sub><i>x(n-k+1,k)</i></sub> = 1 - delta.</li>
<li>We specify 1-delta via numStdDevs through the right tail of the standard normal
distribution.</li>
<li>Smaller values of numStdDevs correspond to bigger values of 1-delta and hence to smaller
values of delta. In fact, usefully small values of delta correspond to negative values of
numStdDevs.</li>
<li>return <i>p</i> = 1-<i>x</i>.</li>
</ul>
@param n is the number of trials. Must be non-negative.
@param k is the number of successes. Must be non-negative, and cannot exceed n.
@param numStdDevs the number of standard deviations defining the confidence interval
@return the lower bound of the approximate Clopper-Pearson confidence interval for the
unknown success probability. | [
"Computes",
"lower",
"bound",
"of",
"approximate",
"Clopper",
"-",
"Pearson",
"confidence",
"interval",
"for",
"a",
"binomial",
"proportion",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java#L93-L103 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java | BoundsOnBinomialProportions.approximateUpperBoundOnP | public static double approximateUpperBoundOnP(final long n, final long k, final double numStdDevs) {
checkInputs(n, k);
if (n == 0) { return 1.0; } // the coin was never flipped, so we know nothing
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); // which is p
}
} | java | public static double approximateUpperBoundOnP(final long n, final long k, final double numStdDevs) {
checkInputs(n, k);
if (n == 0) { return 1.0; } // the coin was never flipped, so we know nothing
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); // which is p
}
} | [
"public",
"static",
"double",
"approximateUpperBoundOnP",
"(",
"final",
"long",
"n",
",",
"final",
"long",
"k",
",",
"final",
"double",
"numStdDevs",
")",
"{",
"checkInputs",
"(",
"n",
",",
"k",
")",
";",
"if",
"(",
"n",
"==",
"0",
")",
"{",
"return",
... | Computes upper bound of approximate Clopper-Pearson confidence interval for a binomial
proportion.
<p>Implementation Notes:<br>
The approximateUpperBoundOnP is defined with respect to the left tail of the binomial
distribution.</p>
<ul>
<li>We want to solve for the <i>p</i> for which sum<sub><i>j,0,k</i></sub>bino(<i>j;n,p</i>)
= delta.</li>
<li>Define <i>x</i> = 1-<i>p</i>.</li>
<li>We want to solve for the <i>x</i> for which I<sub><i>x(n-k,k+1)</i></sub> = delta.</li>
<li>We specify delta via numStdDevs through the right tail of the standard normal
distribution.</li>
<li>Bigger values of numStdDevs correspond to smaller values of delta.</li>
<li>return <i>p</i> = 1-<i>x</i>.</li>
</ul>
@param n is the number of trials. Must be non-negative.
@param k is the number of successes. Must be non-negative, and cannot exceed <i>n</i>.
@param numStdDevs the number of standard deviations defining the confidence interval
@return the upper bound of the approximate Clopper-Pearson confidence interval for the
unknown success probability. | [
"Computes",
"upper",
"bound",
"of",
"approximate",
"Clopper",
"-",
"Pearson",
"confidence",
"interval",
"for",
"a",
"binomial",
"proportion",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java#L128-L142 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java | BoundsOnBinomialProportions.erf_of_nonneg | private static double erf_of_nonneg(final double x) {
// The constants that appear below, formatted for easy checking against the book.
// a1 = 0.07052 30784
// a3 = 0.00927 05272
// a5 = 0.00027 65672
// a2 = 0.04228 20123
// a4 = 0.00015 20143
// a6 = 0.00004 30638
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; // x squared, x cubed, etc.
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; // raise the sum to the 16th power
final double sum4 = sum2 * sum2;
final double sum8 = sum4 * sum4;
final double sum16 = sum8 * sum8;
return (1.0 - (1.0 / sum16));
} | java | private static double erf_of_nonneg(final double x) {
// The constants that appear below, formatted for easy checking against the book.
// a1 = 0.07052 30784
// a3 = 0.00927 05272
// a5 = 0.00027 65672
// a2 = 0.04228 20123
// a4 = 0.00015 20143
// a6 = 0.00004 30638
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; // x squared, x cubed, etc.
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; // raise the sum to the 16th power
final double sum4 = sum2 * sum2;
final double sum8 = sum4 * sum4;
final double sum16 = sum8 * sum8;
return (1.0 - (1.0 / sum16));
} | [
"private",
"static",
"double",
"erf_of_nonneg",
"(",
"final",
"double",
"x",
")",
"{",
"// The constants that appear below, formatted for easy checking against the book.",
"// a1 = 0.07052 30784",
"// a3 = 0.00927 05272",
"// a5 = 0.00027 65672",
"// a2 = 0.04228 20123",
"/... | Abramowitz and Stegun formula 7.1.28, p. 88; Claims accuracy of about 7 decimal digits | [
"Abramowitz",
"and",
"Stegun",
"formula",
"7",
".",
"1",
".",
"28",
"p",
".",
"88",
";",
"Claims",
"accuracy",
"of",
"about",
"7",
"decimal",
"digits"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java#L183-L214 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java | BoundsOnBinomialProportions.abramowitzStegunFormula26p5p22 | 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;
} | java | 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;
} | [
"private",
"static",
"double",
"abramowitzStegunFormula26p5p22",
"(",
"final",
"double",
"a",
",",
"final",
"double",
"b",
",",
"final",
"double",
"yp",
")",
"{",
"final",
"double",
"b2m1",
"=",
"(",
"2.0",
"*",
"b",
")",
"-",
"1.0",
";",
"final",
"doubl... | that the formula was typed in correctly. | [
"that",
"the",
"formula",
"was",
"typed",
"in",
"correctly",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java#L233-L246 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirItemsSketch.java | ReservoirItemsSketch.newInstance | public static <T> ReservoirItemsSketch<T> newInstance(final int k, final ResizeFactor rf) {
return new ReservoirItemsSketch<>(k, rf);
} | java | public static <T> ReservoirItemsSketch<T> newInstance(final int k, final ResizeFactor rf) {
return new ReservoirItemsSketch<>(k, rf);
} | [
"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.
@param k Maximum size of sampling. Allocated size may be smaller until reservoir fills.
Unlike many sketches in this package, this value does <em>not</em> need to be a
power of 2.
@param rf <a href="{@docRoot}/resources/dictionary.html#resizeFactor">See Resize Factor</a>
@param <T> The type of object held in the reservoir.
@return A ReservoirLongsSketch initialized with maximum size k and resize factor rf. | [
"Construct",
"a",
"mergeable",
"sampling",
"sketch",
"with",
"up",
"to",
"k",
"samples",
"using",
"a",
"specified",
"resize",
"factor",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirItemsSketch.java#L168-L170 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirItemsSketch.java | ReservoirItemsSketch.getSamples | @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));
} | java | @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));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"T",
"[",
"]",
"getSamples",
"(",
")",
"{",
"if",
"(",
"itemsSeen_",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"final",
"Class",
"<",
"?",
">",
"clazz",
"=",
"data_",
".",
"get",
... | Returns a copy of the items in the reservoir, or null if empty. The returned array length
may be smaller than the reservoir capacity.
<p>In order to allocate an array of generic type T, uses the class of the first item in
the array. This method method may throw an <tt>ArrayAssignmentException</tt> if the
reservoir stores instances of a polymorphic base class.</p>
@return A copy of the reservoir array | [
"Returns",
"a",
"copy",
"of",
"the",
"items",
"in",
"the",
"reservoir",
"or",
"null",
"if",
"empty",
".",
"The",
"returned",
"array",
"length",
"may",
"be",
"smaller",
"than",
"the",
"reservoir",
"capacity",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirItemsSketch.java#L343-L351 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirItemsSketch.java | ReservoirItemsSketch.copy | @SuppressWarnings("unchecked")
ReservoirItemsSketch<T> copy() {
return new ReservoirItemsSketch<>(reservoirSize_, currItemsAlloc_,
itemsSeen_, rf_, (ArrayList<T>) data_.clone());
} | java | @SuppressWarnings("unchecked")
ReservoirItemsSketch<T> copy() {
return new ReservoirItemsSketch<>(reservoirSize_, currItemsAlloc_,
itemsSeen_, rf_, (ArrayList<T>) data_.clone());
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"ReservoirItemsSketch",
"<",
"T",
">",
"copy",
"(",
")",
"{",
"return",
"new",
"ReservoirItemsSketch",
"<>",
"(",
"reservoirSize_",
",",
"currItemsAlloc_",
",",
"itemsSeen_",
",",
"rf_",
",",
"(",
"ArrayList",
... | Used during union operations to ensure we do not overwrite an existing reservoir. Creates a
shallow copy of the reservoir.
@return A copy of the current sketch | [
"Used",
"during",
"union",
"operations",
"to",
"ensure",
"we",
"do",
"not",
"overwrite",
"an",
"existing",
"reservoir",
".",
"Creates",
"a",
"shallow",
"copy",
"of",
"the",
"reservoir",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirItemsSketch.java#L597-L601 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/Intersection.java | Intersection.intersect | public CompactSketch intersect(final Sketch a, final Sketch b) {
return intersect(a, b, true, null);
} | java | public CompactSketch intersect(final Sketch a, final Sketch b) {
return intersect(a, b, true, null);
} | [
"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.
@param a The first sketch argument
@param b The second sketch argument
@return an ordered CompactSketch on the heap | [
"Perform",
"intersect",
"set",
"operation",
"on",
"the",
"two",
"given",
"sketch",
"arguments",
"and",
"return",
"the",
"result",
"as",
"an",
"ordered",
"CompactSketch",
"on",
"the",
"heap",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/Intersection.java#L80-L82 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/hll/DirectCouponList.java | DirectCouponList.newInstance | 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); //empty and not compact
insertListCount(dstMem, 0);
insertModes(dstMem, tgtHllType, CurMode.LIST);
return new DirectCouponList(lgConfigK, tgtHllType, CurMode.LIST, dstMem);
} | java | 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); //empty and not compact
insertListCount(dstMem, 0);
insertModes(dstMem, tgtHllType, CurMode.LIST);
return new DirectCouponList(lgConfigK, tgtHllType, CurMode.LIST, dstMem);
} | [
"static",
"DirectCouponList",
"newInstance",
"(",
"final",
"int",
"lgConfigK",
",",
"final",
"TgtHllType",
"tgtHllType",
",",
"final",
"WritableMemory",
"dstMem",
")",
"{",
"insertPreInts",
"(",
"dstMem",
",",
"LIST_PREINTS",
")",
";",
"insertSerVer",
"(",
"dstMem... | Standard factory for new DirectCouponList.
This initializes the given WritableMemory.
@param lgConfigK the configured Lg K
@param tgtHllType the configured HLL target
@param dstMem the destination memory for the sketch.
@return a new DirectCouponList | [
"Standard",
"factory",
"for",
"new",
"DirectCouponList",
".",
"This",
"initializes",
"the",
"given",
"WritableMemory",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hll/DirectCouponList.java#L86-L97 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/IntersectionImplR.java | IntersectionImplR.checkMaxLgArrLongs | 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;
} | java | 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;
} | [
"static",
"final",
"int",
"checkMaxLgArrLongs",
"(",
"final",
"Memory",
"dstMem",
")",
"{",
"final",
"int",
"preBytes",
"=",
"CONST_PREAMBLE_LONGS",
"<<",
"3",
";",
"final",
"long",
"cap",
"=",
"dstMem",
".",
"getCapacity",
"(",
")",
";",
"final",
"int",
"... | Returns the correct maximum lgArrLongs given the capacity of the Memory. Checks that the
capacity is large enough for the minimum sized hash table.
@param dstMem the given Memory
@return the correct maximum lgArrLongs given the capacity of the Memory | [
"Returns",
"the",
"correct",
"maximum",
"lgArrLongs",
"given",
"the",
"capacity",
"of",
"the",
"Memory",
".",
"Checks",
"that",
"the",
"capacity",
"is",
"large",
"enough",
"for",
"the",
"minimum",
"sized",
"hash",
"table",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/IntersectionImplR.java#L277-L287 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/IntersectionImpl.java | IntersectionImpl.initNewHeapInstance | static IntersectionImpl initNewHeapInstance(final long seed) {
final IntersectionImpl impl = new IntersectionImpl(null, seed, false);
impl.lgArrLongs_ = 0;
impl.curCount_ = -1; //Universal Set is true
impl.thetaLong_ = Long.MAX_VALUE;
impl.empty_ = false; //A virgin intersection represents the Universal Set so empty is FALSE!
impl.hashTable_ = null;
return impl;
} | java | static IntersectionImpl initNewHeapInstance(final long seed) {
final IntersectionImpl impl = new IntersectionImpl(null, seed, false);
impl.lgArrLongs_ = 0;
impl.curCount_ = -1; //Universal Set is true
impl.thetaLong_ = Long.MAX_VALUE;
impl.empty_ = false; //A virgin intersection represents the Universal Set so empty is FALSE!
impl.hashTable_ = null;
return impl;
} | [
"static",
"IntersectionImpl",
"initNewHeapInstance",
"(",
"final",
"long",
"seed",
")",
"{",
"final",
"IntersectionImpl",
"impl",
"=",
"new",
"IntersectionImpl",
"(",
"null",
",",
"seed",
",",
"false",
")",
";",
"impl",
".",
"lgArrLongs_",
"=",
"0",
";",
"im... | Construct a new Intersection target on the java heap.
@param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Seed</a>
@return a new IntersectionImpl on the Java heap | [
"Construct",
"a",
"new",
"Intersection",
"target",
"on",
"the",
"java",
"heap",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/IntersectionImpl.java#L54-L62 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/IntersectionImpl.java | IntersectionImpl.initNewDirectInstance | static IntersectionImpl initNewDirectInstance(final long seed, final WritableMemory dstMem) {
final IntersectionImpl impl = new IntersectionImpl(dstMem, seed, true);
//Load Preamble
insertPreLongs(dstMem, CONST_PREAMBLE_LONGS); //RF not used = 0
insertSerVer(dstMem, SER_VER);
insertFamilyID(dstMem, Family.INTERSECTION.getID());
//Note: Intersection does not use lgNomLongs or k, per se.
//set lgArrLongs initially to minimum. Don't clear cache in mem
insertLgArrLongs(dstMem, MIN_LG_ARR_LONGS);
insertFlags(dstMem, 0); //bigEndian = readOnly = compact = ordered = empty = false;
//seedHash loaded and checked in private constructor
insertCurCount(dstMem, -1);
insertP(dstMem, (float) 1.0);
insertThetaLong(dstMem, Long.MAX_VALUE);
//Initialize
impl.lgArrLongs_ = MIN_LG_ARR_LONGS;
impl.curCount_ = -1; //set in mem below
impl.thetaLong_ = Long.MAX_VALUE;
impl.empty_ = false;
impl.maxLgArrLongs_ = checkMaxLgArrLongs(dstMem); //Only Off Heap
return impl;
} | java | static IntersectionImpl initNewDirectInstance(final long seed, final WritableMemory dstMem) {
final IntersectionImpl impl = new IntersectionImpl(dstMem, seed, true);
//Load Preamble
insertPreLongs(dstMem, CONST_PREAMBLE_LONGS); //RF not used = 0
insertSerVer(dstMem, SER_VER);
insertFamilyID(dstMem, Family.INTERSECTION.getID());
//Note: Intersection does not use lgNomLongs or k, per se.
//set lgArrLongs initially to minimum. Don't clear cache in mem
insertLgArrLongs(dstMem, MIN_LG_ARR_LONGS);
insertFlags(dstMem, 0); //bigEndian = readOnly = compact = ordered = empty = false;
//seedHash loaded and checked in private constructor
insertCurCount(dstMem, -1);
insertP(dstMem, (float) 1.0);
insertThetaLong(dstMem, Long.MAX_VALUE);
//Initialize
impl.lgArrLongs_ = MIN_LG_ARR_LONGS;
impl.curCount_ = -1; //set in mem below
impl.thetaLong_ = Long.MAX_VALUE;
impl.empty_ = false;
impl.maxLgArrLongs_ = checkMaxLgArrLongs(dstMem); //Only Off Heap
return impl;
} | [
"static",
"IntersectionImpl",
"initNewDirectInstance",
"(",
"final",
"long",
"seed",
",",
"final",
"WritableMemory",
"dstMem",
")",
"{",
"final",
"IntersectionImpl",
"impl",
"=",
"new",
"IntersectionImpl",
"(",
"dstMem",
",",
"seed",
",",
"true",
")",
";",
"//Lo... | Construct a new Intersection target direct to the given destination Memory.
Called by SetOperation.Builder.
@param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Seed</a>
@param dstMem destination Memory.
<a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@return a new IntersectionImpl that may be off-heap | [
"Construct",
"a",
"new",
"Intersection",
"target",
"direct",
"to",
"the",
"given",
"destination",
"Memory",
".",
"Called",
"by",
"SetOperation",
".",
"Builder",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/IntersectionImpl.java#L74-L98 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/IntersectionImpl.java | IntersectionImpl.heapifyInstance | static IntersectionImplR heapifyInstance(final Memory srcMem, final long seed) {
final IntersectionImpl impl = new IntersectionImpl(null, seed, false);
//Get Preamble
//Note: Intersection does not use lgNomLongs (or k), per se.
//seedHash loaded and checked in private constructor
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;
//Checks
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);
}
//empty = true AND curCount_ = 0: OK
}
//Initialize
impl.lgArrLongs_ = lgArrLongs;
impl.curCount_ = curCount;
impl.thetaLong_ = thetaLong;
impl.empty_ = empty;
if (!empty) {
if (curCount > 0) { //can't be virgin, empty, or curCount == 0
impl.hashTable_ = new long[1 << lgArrLongs];
srcMem.getLongArray(CONST_PREAMBLE_LONGS << 3, impl.hashTable_, 0, 1 << lgArrLongs);
}
}
return impl;
} | java | static IntersectionImplR heapifyInstance(final Memory srcMem, final long seed) {
final IntersectionImpl impl = new IntersectionImpl(null, seed, false);
//Get Preamble
//Note: Intersection does not use lgNomLongs (or k), per se.
//seedHash loaded and checked in private constructor
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;
//Checks
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);
}
//empty = true AND curCount_ = 0: OK
}
//Initialize
impl.lgArrLongs_ = lgArrLongs;
impl.curCount_ = curCount;
impl.thetaLong_ = thetaLong;
impl.empty_ = empty;
if (!empty) {
if (curCount > 0) { //can't be virgin, empty, or curCount == 0
impl.hashTable_ = new long[1 << lgArrLongs];
srcMem.getLongArray(CONST_PREAMBLE_LONGS << 3, impl.hashTable_, 0, 1 << lgArrLongs);
}
}
return impl;
} | [
"static",
"IntersectionImplR",
"heapifyInstance",
"(",
"final",
"Memory",
"srcMem",
",",
"final",
"long",
"seed",
")",
"{",
"final",
"IntersectionImpl",
"impl",
"=",
"new",
"IntersectionImpl",
"(",
"null",
",",
"seed",
",",
"false",
")",
";",
"//Get Preamble",
... | Heapify an intersection target from a Memory image containing data.
@param srcMem The source Memory object.
<a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@param seed <a href="{@docRoot}/resources/dictionary.html#seed">See seed</a>
@return a IntersectionImplR instance on the Java heap | [
"Heapify",
"an",
"intersection",
"target",
"from",
"a",
"Memory",
"image",
"containing",
"data",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/IntersectionImpl.java#L107-L155 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/tuple/Intersection.java | Intersection.update | @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;
}
// assumes that constructor of QuickSelectSketch bumps the requested size up to the nearest power of 2
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();
}
} | java | @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;
}
// assumes that constructor of QuickSelectSketch bumps the requested size up to the nearest power of 2
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();
}
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"null\"",
"}",
")",
"public",
"void",
"update",
"(",
"final",
"Sketch",
"<",
"S",
">",
"sketchIn",
")",
"{",
"final",
"boolean",
"isFirstCall",
"=",
"isFirstCall_",
";",
"isFirstCall_",
"=",
"false",... | Updates the internal set by intersecting it with the given sketch
@param sketchIn input sketch to intersect with the internal set | [
"Updates",
"the",
"internal",
"set",
"by",
"intersecting",
"it",
"with",
"the",
"given",
"sketch"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/tuple/Intersection.java#L45-L101 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BinomialBoundsN.java | BinomialBoundsN.contClassicLB | 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);
} | java | 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);
} | [
"private",
"static",
"double",
"contClassicLB",
"(",
"final",
"double",
"numSamplesF",
",",
"final",
"double",
"theta",
",",
"final",
"double",
"numSDev",
")",
"{",
"final",
"double",
"nHat",
"=",
"(",
"numSamplesF",
"-",
"0.5",
")",
"/",
"theta",
";",
"fi... | our "classic" bounds, but now with continuity correction | [
"our",
"classic",
"bounds",
"but",
"now",
"with",
"continuity",
"correction"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BinomialBoundsN.java#L32-L39 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BinomialBoundsN.java | BinomialBoundsN.getLowerBound | public static double getLowerBound(final long numSamples, final double theta, final int numSDev,
final boolean noDataSeen) {
//in earlier code numSamples was called numSamplesI
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)));
} | java | public static double getLowerBound(final long numSamples, final double theta, final int numSDev,
final boolean noDataSeen) {
//in earlier code numSamples was called numSamplesI
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)));
} | [
"public",
"static",
"double",
"getLowerBound",
"(",
"final",
"long",
"numSamples",
",",
"final",
"double",
"theta",
",",
"final",
"int",
"numSDev",
",",
"final",
"boolean",
"noDataSeen",
")",
"{",
"//in earlier code numSamples was called numSamplesI",
"if",
"(",
"no... | Returns the approximate lower bound value
@param numSamples the number of samples in the sample set
@param theta the sampling probability
@param numSDev the number of "standard deviations" from the mean for the tail bounds.
This must be an integer value of 1, 2 or 3.
@param noDataSeen this is normally false. However, in the case where you have zero samples
and a theta < 1.0, this flag enables the distinction between a virgin case when no actual
data has been seen and the case where the estimate may be zero but an upper error bound may
still exist.
@return the approximate upper bound value | [
"Returns",
"the",
"approximate",
"lower",
"bound",
"value"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BinomialBoundsN.java#L218-L227 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BinomialBoundsN.java | BinomialBoundsN.getUpperBound | public static double getUpperBound(final long numSamples, final double theta, final int numSDev,
final boolean noDataSeen) {
//in earlier code numSamples was called numSamplesI
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));
} | java | public static double getUpperBound(final long numSamples, final double theta, final int numSDev,
final boolean noDataSeen) {
//in earlier code numSamples was called numSamplesI
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));
} | [
"public",
"static",
"double",
"getUpperBound",
"(",
"final",
"long",
"numSamples",
",",
"final",
"double",
"theta",
",",
"final",
"int",
"numSDev",
",",
"final",
"boolean",
"noDataSeen",
")",
"{",
"//in earlier code numSamples was called numSamplesI",
"if",
"(",
"no... | Returns the approximate upper bound value
@param numSamples the number of samples in the sample set
@param theta the sampling probability
@param numSDev the number of "standard deviations" from the mean for the tail bounds.
This must be an integer value of 1, 2 or 3.
@param noDataSeen this is normally false. However, in the case where you have zero samples
and a theta < 1.0, this flag enables the distinction between a virgin case when no actual
data has been seen and the case where the estimate may be zero but an upper error bound may
still exist.
@return the approximate upper bound value | [
"Returns",
"the",
"approximate",
"upper",
"bound",
"value"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BinomialBoundsN.java#L241-L250 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BinomialBoundsN.java | BinomialBoundsN.checkArgs | 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);
}
} | java | 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);
}
} | [
"static",
"final",
"void",
"checkArgs",
"(",
"final",
"long",
"numSamples",
",",
"final",
"double",
"theta",
",",
"final",
"int",
"numSDev",
")",
"{",
"if",
"(",
"(",
"numSDev",
"|",
"(",
"numSDev",
"-",
"1",
")",
"|",
"(",
"3",
"-",
"numSDev",
")",
... | exposed only for test | [
"exposed",
"only",
"for",
"test"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BinomialBoundsN.java#L253-L262 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirItemsUnion.java | ReservoirItemsUnion.update | public void update(final ReservoirItemsSketch<T> sketchIn) {
if (sketchIn == null) {
return;
}
final ReservoirItemsSketch<T> ris =
(sketchIn.getK() <= maxK_ ? sketchIn : sketchIn.downsampledCopy(maxK_));
// can modify the sketch if we downsampled, otherwise may need to copy it
final boolean isModifiable = (sketchIn != ris);
if (gadget_ == null) {
createNewGadget(ris, isModifiable);
} else {
twoWayMergeInternal(ris, isModifiable);
}
} | java | public void update(final ReservoirItemsSketch<T> sketchIn) {
if (sketchIn == null) {
return;
}
final ReservoirItemsSketch<T> ris =
(sketchIn.getK() <= maxK_ ? sketchIn : sketchIn.downsampledCopy(maxK_));
// can modify the sketch if we downsampled, otherwise may need to copy it
final boolean isModifiable = (sketchIn != ris);
if (gadget_ == null) {
createNewGadget(ris, isModifiable);
} else {
twoWayMergeInternal(ris, isModifiable);
}
} | [
"public",
"void",
"update",
"(",
"final",
"ReservoirItemsSketch",
"<",
"T",
">",
"sketchIn",
")",
"{",
"if",
"(",
"sketchIn",
"==",
"null",
")",
"{",
"return",
";",
"}",
"final",
"ReservoirItemsSketch",
"<",
"T",
">",
"ris",
"=",
"(",
"sketchIn",
".",
... | Union the given sketch. This method can be repeatedly called. If the given sketch is null it is
interpreted as an empty sketch.
@param sketchIn The incoming sketch. | [
"Union",
"the",
"given",
"sketch",
".",
"This",
"method",
"can",
"be",
"repeatedly",
"called",
".",
"If",
"the",
"given",
"sketch",
"is",
"null",
"it",
"is",
"interpreted",
"as",
"an",
"empty",
"sketch",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirItemsUnion.java#L134-L149 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirItemsUnion.java | ReservoirItemsUnion.update | public void update(final T datum) {
if (datum == null) {
return;
}
if (gadget_ == null) {
gadget_ = ReservoirItemsSketch.newInstance(maxK_);
}
gadget_.update(datum);
} | java | public void update(final T datum) {
if (datum == null) {
return;
}
if (gadget_ == null) {
gadget_ = ReservoirItemsSketch.newInstance(maxK_);
}
gadget_.update(datum);
} | [
"public",
"void",
"update",
"(",
"final",
"T",
"datum",
")",
"{",
"if",
"(",
"datum",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"gadget_",
"==",
"null",
")",
"{",
"gadget_",
"=",
"ReservoirItemsSketch",
".",
"newInstance",
"(",
"maxK_",
... | Present this union with a single item to be added to the union.
@param datum The given datum of type T. | [
"Present",
"this",
"union",
"with",
"a",
"single",
"item",
"to",
"be",
"added",
"to",
"the",
"union",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirItemsUnion.java#L180-L189 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirItemsUnion.java | ReservoirItemsUnion.toByteArray | 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());
}
} | java | 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());
}
} | [
"public",
"byte",
"[",
"]",
"toByteArray",
"(",
"final",
"ArrayOfItemsSerDe",
"<",
"T",
">",
"serDe",
")",
"{",
"if",
"(",
"(",
"gadget_",
"==",
"null",
")",
"||",
"(",
"gadget_",
".",
"getNumSamples",
"(",
")",
"==",
"0",
")",
")",
"{",
"return",
... | Returns a byte array representation of this union
@param serDe An instance of ArrayOfItemsSerDe
@return a byte array representation of this union | [
"Returns",
"a",
"byte",
"array",
"representation",
"of",
"this",
"union"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirItemsUnion.java#L235-L241 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/hll/RelativeErrorTables.java | RelativeErrorTables.getRelErr | 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 : { //HIP, LB
f = HIP_LB[idx];
break;
}
case 1 : { //HIP, UB
f = HIP_UB[idx];
break;
}
case 2 : { //NON_HIP, LB
f = NON_HIP_LB[idx];
break;
}
case 3 : { //NON_HIP, UB
f = NON_HIP_UB[idx];
break;
}
}
return f;
} | java | 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 : { //HIP, LB
f = HIP_LB[idx];
break;
}
case 1 : { //HIP, UB
f = HIP_UB[idx];
break;
}
case 2 : { //NON_HIP, LB
f = NON_HIP_LB[idx];
break;
}
case 3 : { //NON_HIP, UB
f = NON_HIP_UB[idx];
break;
}
}
return f;
} | [
"static",
"double",
"getRelErr",
"(",
"final",
"boolean",
"upperBound",
",",
"final",
"boolean",
"oooFlag",
",",
"final",
"int",
"lgK",
",",
"final",
"int",
"stdDev",
")",
"{",
"final",
"int",
"idx",
"=",
"(",
"(",
"lgK",
"-",
"4",
")",
"*",
"3",
")"... | Return Relative Error for UB or LB for HIP or Non-HIP as a function of numStdDev.
@param upperBound true if for upper bound
@param oooFlag true if for Non-HIP
@param lgK must be between 4 and 12 inclusive
@param stdDev must be between 1 and 3 inclusive
@return Relative Error for UB or LB for HIP or Non-HIP as a function of numStdDev. | [
"Return",
"Relative",
"Error",
"for",
"UB",
"or",
"LB",
"for",
"HIP",
"or",
"Non",
"-",
"HIP",
"as",
"a",
"function",
"of",
"numStdDev",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hll/RelativeErrorTables.java#L22-L46 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcWrapper.java | CpcWrapper.getEstimate | public double getEstimate() {
if (!hasHip(mem)) {
return getIconEstimate(PreambleUtil.getLgK(mem), getNumCoupons(mem));
}
return getHipAccum(mem);
} | java | public double getEstimate() {
if (!hasHip(mem)) {
return getIconEstimate(PreambleUtil.getLgK(mem), getNumCoupons(mem));
}
return getHipAccum(mem);
} | [
"public",
"double",
"getEstimate",
"(",
")",
"{",
"if",
"(",
"!",
"hasHip",
"(",
"mem",
")",
")",
"{",
"return",
"getIconEstimate",
"(",
"PreambleUtil",
".",
"getLgK",
"(",
"mem",
")",
",",
"getNumCoupons",
"(",
"mem",
")",
")",
";",
"}",
"return",
"... | Returns the best estimate of the cardinality of the sketch.
@return the best estimate of the cardinality of the sketch. | [
"Returns",
"the",
"best",
"estimate",
"of",
"the",
"cardinality",
"of",
"the",
"sketch",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcWrapper.java#L55-L60 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/HeapCompactOrderedSketch.java | HeapCompactOrderedSketch.heapifyInstance | 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) { //singleItem
return new SingleItemSketch(srcMem.getLong(8), memSeedHash);
}
//else empty
} else { //preLongs > 1
curCount = extractCurCount(srcMem);
cache = new long[curCount];
if (preLongs == 2) {
srcMem.getLongArray(16, cache, 0, curCount);
} else { //preLongs == 3
srcMem.getLongArray(24, cache, 0, curCount);
thetaLong = extractThetaLong(srcMem);
}
}
return new HeapCompactOrderedSketch(cache, empty, memSeedHash, curCount, thetaLong);
} | java | 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) { //singleItem
return new SingleItemSketch(srcMem.getLong(8), memSeedHash);
}
//else empty
} else { //preLongs > 1
curCount = extractCurCount(srcMem);
cache = new long[curCount];
if (preLongs == 2) {
srcMem.getLongArray(16, cache, 0, curCount);
} else { //preLongs == 3
srcMem.getLongArray(24, cache, 0, curCount);
thetaLong = extractThetaLong(srcMem);
}
}
return new HeapCompactOrderedSketch(cache, empty, memSeedHash, curCount, thetaLong);
} | [
"static",
"CompactSketch",
"heapifyInstance",
"(",
"final",
"Memory",
"srcMem",
",",
"final",
"long",
"seed",
")",
"{",
"final",
"short",
"memSeedHash",
"=",
"(",
"short",
")",
"extractSeedHash",
"(",
"srcMem",
")",
";",
"final",
"short",
"computedSeedHash",
"... | Heapifies the given source Memory with seed
@param srcMem <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Update Hash Seed</a>.
@return a CompactSketch | [
"Heapifies",
"the",
"given",
"source",
"Memory",
"with",
"seed"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/HeapCompactOrderedSketch.java#L45-L72 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/HeapCompactOrderedSketch.java | HeapCompactOrderedSketch.compact | 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);
} | java | 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);
} | [
"static",
"CompactSketch",
"compact",
"(",
"final",
"UpdateSketch",
"sketch",
")",
"{",
"final",
"int",
"curCount",
"=",
"sketch",
".",
"getRetainedEntries",
"(",
"true",
")",
";",
"long",
"thetaLong",
"=",
"sketch",
".",
"getThetaLong",
"(",
")",
";",
"bool... | Converts the given UpdateSketch to this compact form.
@param sketch the given UpdateSketch
@return a CompactSketch | [
"Converts",
"the",
"given",
"UpdateSketch",
"to",
"this",
"compact",
"form",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/HeapCompactOrderedSketch.java#L79-L93 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/QuickSelect.java | QuickSelect.select | 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];
} | java | 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];
} | [
"public",
"static",
"double",
"select",
"(",
"final",
"double",
"[",
"]",
"arr",
",",
"int",
"lo",
",",
"int",
"hi",
",",
"final",
"int",
"pivot",
")",
"{",
"while",
"(",
"hi",
">",
"lo",
")",
"{",
"final",
"int",
"j",
"=",
"partition",
"(",
"arr... | Gets the 0-based kth order statistic from the array. Warning! This changes the ordering
of elements in the given array!
@param arr The array to be re-arranged.
@param lo The lowest 0-based index to be considered.
@param hi The highest 0-based index to be considered.
@param pivot The 0-based smallest value to pivot on.
@return The value of the smallest (n)th element where n is 0-based. | [
"Gets",
"the",
"0",
"-",
"based",
"kth",
"order",
"statistic",
"from",
"the",
"array",
".",
"Warning!",
"This",
"changes",
"the",
"ordering",
"of",
"elements",
"in",
"the",
"given",
"array!"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/QuickSelect.java#L136-L150 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/QuickSelect.java | QuickSelect.selectIncludingZeros | 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);
} | java | 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);
} | [
"public",
"static",
"double",
"selectIncludingZeros",
"(",
"final",
"double",
"[",
"]",
"arr",
",",
"final",
"int",
"pivot",
")",
"{",
"final",
"int",
"arrSize",
"=",
"arr",
".",
"length",
";",
"final",
"int",
"adj",
"=",
"pivot",
"-",
"1",
";",
"retur... | 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!
@param arr The hash array.
@param pivot The 1-based index of the value that is chosen as the pivot for the array.
After the operation all values below this 1-based index will be less than this value
and all values above this index will be greater. The 0-based index of the pivot will be
pivot-1.
@return The value of the smallest (N)th element including zeros, where N is 1-based. | [
"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!"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/QuickSelect.java#L163-L167 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/QuickSelect.java | QuickSelect.selectExcludingZeros | 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);
} | java | 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);
} | [
"public",
"static",
"double",
"selectExcludingZeros",
"(",
"final",
"double",
"[",
"]",
"arr",
",",
"final",
"int",
"nonZeros",
",",
"final",
"int",
"pivot",
")",
"{",
"if",
"(",
"pivot",
">",
"nonZeros",
")",
"{",
"return",
"0L",
";",
"}",
"final",
"i... | 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!
@param arr The hash array.
@param nonZeros The number of non-zero values in the array.
@param pivot The 1-based index of the value that is chosen as the pivot for the array.
After the operation all values below this 1-based index will be less than this value
and all values above this index will be greater. The 0-based index of the pivot will be
pivot+arr.length-nonZeros-1.
@return The value of the smallest (N)th element excluding zeros, where N is 1-based. | [
"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!"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/QuickSelect.java#L181-L189 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/hll/CouponHashSet.java | CouponHashSet.heapifySet | 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 { //updatable
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;
} | java | 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 { //updatable
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;
} | [
"static",
"final",
"CouponHashSet",
"heapifySet",
"(",
"final",
"Memory",
"mem",
")",
"{",
"final",
"int",
"lgConfigK",
"=",
"extractLgK",
"(",
"mem",
")",
";",
"final",
"TgtHllType",
"tgtHllType",
"=",
"extractTgtHllType",
"(",
"mem",
")",
";",
"final",
"Cu... | will also accept List, but results in a Set | [
"will",
"also",
"accept",
"List",
"but",
"results",
"in",
"a",
"Set"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hll/CouponHashSet.java#L61-L87 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/HeapQuickSelectSketch.java | HeapQuickSelectSketch.heapifyInstance | static HeapQuickSelectSketch heapifyInstance(final Memory srcMem, final long seed) {
final int preambleLongs = extractPreLongs(srcMem); //byte 0
final int lgNomLongs = extractLgNomLongs(srcMem); //byte 3
final int lgArrLongs = extractLgArrLongs(srcMem); //byte 4
checkUnionQuickSelectFamily(srcMem, preambleLongs, lgNomLongs);
checkMemIntegrity(srcMem, seed, preambleLongs, lgNomLongs, lgArrLongs);
final float p = extractP(srcMem); //bytes 12-15
final int lgRF = extractLgResizeFactor(srcMem); //byte 0
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); //read in as hash table
return hqss;
} | java | static HeapQuickSelectSketch heapifyInstance(final Memory srcMem, final long seed) {
final int preambleLongs = extractPreLongs(srcMem); //byte 0
final int lgNomLongs = extractLgNomLongs(srcMem); //byte 3
final int lgArrLongs = extractLgArrLongs(srcMem); //byte 4
checkUnionQuickSelectFamily(srcMem, preambleLongs, lgNomLongs);
checkMemIntegrity(srcMem, seed, preambleLongs, lgNomLongs, lgArrLongs);
final float p = extractP(srcMem); //bytes 12-15
final int lgRF = extractLgResizeFactor(srcMem); //byte 0
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); //read in as hash table
return hqss;
} | [
"static",
"HeapQuickSelectSketch",
"heapifyInstance",
"(",
"final",
"Memory",
"srcMem",
",",
"final",
"long",
"seed",
")",
"{",
"final",
"int",
"preambleLongs",
"=",
"extractPreLongs",
"(",
"srcMem",
")",
";",
"//byte 0",
"final",
"int",
"lgNomLongs",
"=",
"extr... | Heapify a sketch from a Memory UpdateSketch or Union object
containing sketch data.
@param srcMem The source Memory object.
<a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@param seed <a href="{@docRoot}/resources/dictionary.html#seed">See seed</a>
@return instance of this sketch | [
"Heapify",
"a",
"sketch",
"from",
"a",
"Memory",
"UpdateSketch",
"or",
"Union",
"object",
"containing",
"sketch",
"data",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/HeapQuickSelectSketch.java#L97-L126 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/HeapQuickSelectSketch.java | HeapQuickSelectSketch.quickSelectAndRebuild | private final void quickSelectAndRebuild() {
final int arrLongs = 1 << lgArrLongs_;
final int pivot = (1 << lgNomLongs_) + 1; // pivot for QS
thetaLong_ = selectExcludingZeros(cache_, curCount_, pivot); //messes up the cache_
// now we rebuild to clean up dirty data, update count, reconfigure as a hash table
final long[] tgtArr = new long[arrLongs];
curCount_ = HashOperations.hashArrayInsert(cache_, tgtArr, lgArrLongs_, thetaLong_);
cache_ = tgtArr;
//hashTableThreshold stays the same
} | java | private final void quickSelectAndRebuild() {
final int arrLongs = 1 << lgArrLongs_;
final int pivot = (1 << lgNomLongs_) + 1; // pivot for QS
thetaLong_ = selectExcludingZeros(cache_, curCount_, pivot); //messes up the cache_
// now we rebuild to clean up dirty data, update count, reconfigure as a hash table
final long[] tgtArr = new long[arrLongs];
curCount_ = HashOperations.hashArrayInsert(cache_, tgtArr, lgArrLongs_, thetaLong_);
cache_ = tgtArr;
//hashTableThreshold stays the same
} | [
"private",
"final",
"void",
"quickSelectAndRebuild",
"(",
")",
"{",
"final",
"int",
"arrLongs",
"=",
"1",
"<<",
"lgArrLongs_",
";",
"final",
"int",
"pivot",
"=",
"(",
"1",
"<<",
"lgNomLongs_",
")",
"+",
"1",
";",
"// pivot for QS",
"thetaLong_",
"=",
"sele... | array stays the same size. Changes theta and thus count | [
"array",
"stays",
"the",
"same",
"size",
".",
"Changes",
"theta",
"and",
"thus",
"count"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/HeapQuickSelectSketch.java#L277-L289 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/VarOptItemsSamples.java | VarOptItemsSamples.items | public T items(final int i) {
loadArrays();
return (sampleLists == null ? null : sampleLists.items[i]);
} | java | public T items(final int i) {
loadArrays();
return (sampleLists == null ? null : sampleLists.items[i]);
} | [
"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.
@param i An index into the list of samples
@return The sample at array position <tt>i</tt> | [
"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"... | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/VarOptItemsSamples.java#L227-L230 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/VarOptItemsSamples.java | VarOptItemsSamples.weights | public double weights(final int i) {
loadArrays();
return (sampleLists == null ? Double.NaN : sampleLists.weights[i]);
} | java | public double weights(final int i) {
loadArrays();
return (sampleLists == null ? Double.NaN : sampleLists.weights[i]);
} | [
"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.
@param i An index into the list of weights
@return The weight at array position <tt>i</tt> | [
"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",
"array... | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/VarOptItemsSamples.java#L248-L251 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/SetOperationBuilder.java | SetOperationBuilder.setNominalEntries | 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;
} | java | 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;
} | [
"public",
"SetOperationBuilder",
"setNominalEntries",
"(",
"final",
"int",
"nomEntries",
")",
"{",
"bLgNomLongs",
"=",
"Integer",
".",
"numberOfTrailingZeros",
"(",
"ceilingPowerOf2",
"(",
"nomEntries",
")",
")",
";",
"if",
"(",
"(",
"bLgNomLongs",
">",
"MAX_LG_NO... | 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.
@param nomEntries <a href="{@docRoot}/resources/dictionary.html#nomEntries">Nominal Entres</a>
This will become the ceiling power of 2 if it is not.
@return this SetOperationBuilder | [
"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",
... | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/SetOperationBuilder.java#L61-L68 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/SetOperationBuilder.java | SetOperationBuilder.build | 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;
} | java | 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;
} | [
"public",
"SetOperation",
"build",
"(",
"final",
"Family",
"family",
",",
"final",
"WritableMemory",
"dstMem",
")",
"{",
"SetOperation",
"setOp",
"=",
"null",
";",
"switch",
"(",
"family",
")",
"{",
"case",
"UNION",
":",
"{",
"if",
"(",
"dstMem",
"==",
"... | 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.
@param family the chosen SetOperation family
@param dstMem The destination Memory.
@return a SetOperation | [
"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",
"... | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/SetOperationBuilder.java#L173-L209 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/frequencies/ReversePurgeLongHashMap.java | ReversePurgeLongHashMap.getInstance | 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;
} | java | 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;
} | [
"static",
"ReversePurgeLongHashMap",
"getInstance",
"(",
"final",
"String",
"string",
")",
"{",
"final",
"String",
"[",
"]",
"tokens",
"=",
"string",
".",
"split",
"(",
"\",\"",
")",
";",
"if",
"(",
"tokens",
".",
"length",
"<",
"2",
")",
"{",
"throw",
... | Returns an instance of this class from the given String,
which must be a String representation of this class.
@param string a String representation of this class.
@return an instance of this class. | [
"Returns",
"an",
"instance",
"of",
"this",
"class",
"from",
"the",
"given",
"String",
"which",
"must",
"be",
"a",
"String",
"representation",
"of",
"this",
"class",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/frequencies/ReversePurgeLongHashMap.java#L59-L75 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/frequencies/ReversePurgeLongHashMap.java | ReversePurgeLongHashMap.serializeToString | 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();
} | java | 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();
} | [
"String",
"serializeToString",
"(",
")",
"{",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"String",
".",
"format",
"(",
"\"%d,%d,\"",
",",
"numActive",
",",
"keys",
".",
"length",
")",
")",
";",
... | Returns a String representation of this hash map.
@return a String representation of this hash map. | [
"Returns",
"a",
"String",
"representation",
"of",
"this",
"hash",
"map",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/frequencies/ReversePurgeLongHashMap.java#L84-L94 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/frequencies/ReversePurgeLongHashMap.java | ReversePurgeLongHashMap.keepOnlyPositiveCounts | void keepOnlyPositiveCounts() {
// Starting from the back, find the first empty cell, which marks a boundary between clusters.
int firstProbe = keys.length - 1;
while (states[firstProbe] > 0) {
firstProbe--;
}
//Work towards the front; delete any non-positive entries.
for (int probe = firstProbe; probe-- > 0; ) {
// When we find the next non-empty cell, we know we are at the high end of a cluster,
// which is tracked by firstProbe.
if ((states[probe] > 0) && (values[probe] <= 0)) {
hashDelete(probe); //does the work of deletion and moving higher items towards the front.
numActive--;
}
}
//now work on the first cluster that was skipped.
for (int probe = keys.length; probe-- > firstProbe;) {
if ((states[probe] > 0) && (values[probe] <= 0)) {
hashDelete(probe);
numActive--;
}
}
} | java | void keepOnlyPositiveCounts() {
// Starting from the back, find the first empty cell, which marks a boundary between clusters.
int firstProbe = keys.length - 1;
while (states[firstProbe] > 0) {
firstProbe--;
}
//Work towards the front; delete any non-positive entries.
for (int probe = firstProbe; probe-- > 0; ) {
// When we find the next non-empty cell, we know we are at the high end of a cluster,
// which is tracked by firstProbe.
if ((states[probe] > 0) && (values[probe] <= 0)) {
hashDelete(probe); //does the work of deletion and moving higher items towards the front.
numActive--;
}
}
//now work on the first cluster that was skipped.
for (int probe = keys.length; probe-- > firstProbe;) {
if ((states[probe] > 0) && (values[probe] <= 0)) {
hashDelete(probe);
numActive--;
}
}
} | [
"void",
"keepOnlyPositiveCounts",
"(",
")",
"{",
"// Starting from the back, find the first empty cell, which marks a boundary between clusters.",
"int",
"firstProbe",
"=",
"keys",
".",
"length",
"-",
"1",
";",
"while",
"(",
"states",
"[",
"firstProbe",
"]",
">",
"0",
"... | Processes the map arrays and retains only keys with positive counts. | [
"Processes",
"the",
"map",
"arrays",
"and",
"retains",
"only",
"keys",
"with",
"positive",
"counts",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/frequencies/ReversePurgeLongHashMap.java#L154-L177 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BoundsOnRatiosInThetaSketchedSets.java | BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA | 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);
} | java | 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);
} | [
"public",
"static",
"double",
"getLowerBoundForBoverA",
"(",
"final",
"Sketch",
"sketchA",
",",
"final",
"Sketch",
"sketchB",
")",
"{",
"final",
"double",
"thetaA",
"=",
"sketchA",
".",
"getTheta",
"(",
")",
";",
"final",
"double",
"thetaB",
"=",
"sketchB",
... | Gets the approximate lower bound for B over A based on a 95% confidence interval
@param sketchA the sketch A
@param sketchB the sketch B
@return the approximate lower bound for B over A | [
"Gets",
"the",
"approximate",
"lower",
"bound",
"for",
"B",
"over",
"A",
"based",
"on",
"a",
"95%",
"confidence",
"interval"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BoundsOnRatiosInThetaSketchedSets.java#L41-L53 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/ItemsMergeImpl.java | ItemsMergeImpl.blockyTandemMergeSort | 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);
// duplicate the input is preparation for the "ping-pong" copy reduction strategy.
final T[] keyTmp = Arrays.copyOf(keyArr, arrLen);
final long[] valTmp = Arrays.copyOf(valArr, arrLen);
blockyTandemMergeSortRecursion(keyTmp, valTmp,
keyArr, valArr,
0, numblks,
blkSize, arrLen, comparator);
} | java | 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);
// duplicate the input is preparation for the "ping-pong" copy reduction strategy.
final T[] keyTmp = Arrays.copyOf(keyArr, arrLen);
final long[] valTmp = Arrays.copyOf(valArr, arrLen);
blockyTandemMergeSortRecursion(keyTmp, valTmp,
keyArr, valArr,
0, numblks,
blkSize, arrLen, comparator);
} | [
"static",
"<",
"T",
">",
"void",
"blockyTandemMergeSort",
"(",
"final",
"T",
"[",
"]",
"keyArr",
",",
"final",
"long",
"[",
"]",
"valArr",
",",
"final",
"int",
"arrLen",
",",
"final",
"int",
"blkSize",
",",
"final",
"Comparator",
"<",
"?",
"super",
"T"... | also used by ItemsAuxiliary | [
"also",
"used",
"by",
"ItemsAuxiliary"
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/ItemsMergeImpl.java#L216-L232 | train |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirSize.java | ReservoirSize.decodeValue | 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));
} | java | 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));
} | [
"public",
"static",
"int",
"decodeValue",
"(",
"final",
"short",
"encodedSize",
")",
"{",
"final",
"int",
"value",
"=",
"encodedSize",
"&",
"0xFFFF",
";",
"if",
"(",
"value",
">",
"MAX_ENC_VALUE",
")",
"{",
"throw",
"new",
"SketchesArgumentException",
"(",
"... | Decodes the 16-bit reservoir size value into an int.
@param encodedSize Encoded 16-bit value
@return int represented by <tt>encodedSize</tt> | [
"Decodes",
"the",
"16",
"-",
"bit",
"reservoir",
"size",
"value",
"into",
"an",
"int",
"."
] | 900c8c9668a1e2f1d54d453e956caad54702e540 | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirSize.java#L95-L107 | train |
mokies/ratelimitj | ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java | ConcurrentLimitRule.of | 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));
} | java | 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));
} | [
"public",
"static",
"ConcurrentLimitRule",
"of",
"(",
"int",
"concurrentLimit",
",",
"TimeUnit",
"timeOutUnit",
",",
"long",
"timeOut",
")",
"{",
"requireNonNull",
"(",
"timeOutUnit",
",",
"\"time out unit can not be null\"",
")",
";",
"return",
"new",
"ConcurrentLimi... | Initialise a concurrent rate limit.
@param concurrentLimit The concurrent limit.
@param timeOutUnit The time unit.
@param timeOut A timeOut for the checkout baton.
@return A concurrent limit rule. | [
"Initialise",
"a",
"concurrent",
"rate",
"limit",
"."
] | eb15ec42055c46b2b3f6f84131d86f570e489c32 | https://github.com/mokies/ratelimitj/blob/eb15ec42055c46b2b3f6f84131d86f570e489c32/ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java#L35-L38 | train |
mokies/ratelimitj | ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java | RequestLimitRule.of | 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);
} | java | 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);
} | [
"public",
"static",
"RequestLimitRule",
"of",
"(",
"Duration",
"duration",
",",
"long",
"limit",
")",
"{",
"checkDuration",
"(",
"duration",
")",
";",
"if",
"(",
"limit",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"limit must be gre... | Initialise a request rate limit. Imagine the whole duration window as being one large bucket with a single count.
@param duration The time the limit will be applied over. The duration must be greater than 1 second.
@param limit A number representing the maximum operations that can be performed in the given duration.
@return A limit rule. | [
"Initialise",
"a",
"request",
"rate",
"limit",
".",
"Imagine",
"the",
"whole",
"duration",
"window",
"as",
"being",
"one",
"large",
"bucket",
"with",
"a",
"single",
"count",
"."
] | eb15ec42055c46b2b3f6f84131d86f570e489c32 | https://github.com/mokies/ratelimitj/blob/eb15ec42055c46b2b3f6f84131d86f570e489c32/ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java#L55-L62 | train |
mokies/ratelimitj | ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java | RequestLimitRule.withName | public RequestLimitRule withName(String name) {
return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, name, this.keys);
} | java | public RequestLimitRule withName(String name) {
return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, name, this.keys);
} | [
"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.
@param name Defines a descriptive name for the rule limit.
@return a limit rule | [
"Applies",
"a",
"name",
"to",
"the",
"rate",
"limit",
"that",
"is",
"useful",
"for",
"metrics",
"."
] | eb15ec42055c46b2b3f6f84131d86f570e489c32 | https://github.com/mokies/ratelimitj/blob/eb15ec42055c46b2b3f6f84131d86f570e489c32/ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java#L81-L83 | train |
mokies/ratelimitj | ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java | RequestLimitRule.matchingKeys | public RequestLimitRule matchingKeys(String... keys) {
Set<String> keySet = keys.length > 0 ? new HashSet<>(Arrays.asList(keys)) : null;
return matchingKeys(keySet);
} | java | public RequestLimitRule matchingKeys(String... keys) {
Set<String> keySet = keys.length > 0 ? new HashSet<>(Arrays.asList(keys)) : null;
return matchingKeys(keySet);
} | [
"public",
"RequestLimitRule",
"matchingKeys",
"(",
"String",
"...",
"keys",
")",
"{",
"Set",
"<",
"String",
">",
"keySet",
"=",
"keys",
".",
"length",
">",
"0",
"?",
"new",
"HashSet",
"<>",
"(",
"Arrays",
".",
"asList",
"(",
"keys",
")",
")",
":",
"n... | Applies a key to the rate limit that defines to which keys, the rule applies, empty for any unmatched key.
@param keys Defines a set of keys to which the rule applies.
@return a limit rule | [
"Applies",
"a",
"key",
"to",
"the",
"rate",
"limit",
"that",
"defines",
"to",
"which",
"keys",
"the",
"rule",
"applies",
"empty",
"for",
"any",
"unmatched",
"key",
"."
] | eb15ec42055c46b2b3f6f84131d86f570e489c32 | https://github.com/mokies/ratelimitj/blob/eb15ec42055c46b2b3f6f84131d86f570e489c32/ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java#L91-L94 | train |
mokies/ratelimitj | ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java | RequestLimitRule.matchingKeys | public RequestLimitRule matchingKeys(Set<String> keys) {
return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, this.name, keys);
} | java | public RequestLimitRule matchingKeys(Set<String> keys) {
return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, this.name, keys);
} | [
"public",
"RequestLimitRule",
"matchingKeys",
"(",
"Set",
"<",
"String",
">",
"keys",
")",
"{",
"return",
"new",
"RequestLimitRule",
"(",
"this",
".",
"durationSeconds",
",",
"this",
".",
"limit",
",",
"this",
".",
"precision",
",",
"this",
".",
"name",
",... | Applies a key to the rate limit that defines to which keys, the rule applies, null for any unmatched key.
@param keys Defines a set of keys to which the rule applies.
@return a limit rule | [
"Applies",
"a",
"key",
"to",
"the",
"rate",
"limit",
"that",
"defines",
"to",
"which",
"keys",
"the",
"rule",
"applies",
"null",
"for",
"any",
"unmatched",
"key",
"."
] | eb15ec42055c46b2b3f6f84131d86f570e489c32 | https://github.com/mokies/ratelimitj/blob/eb15ec42055c46b2b3f6f84131d86f570e489c32/ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java#L102-L104 | train |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/internal/PreDestroyMonitor.java | PreDestroyMonitor.addScopeBindings | public void addScopeBindings(Map<Class<? extends Annotation>, Scope> bindings) {
if (scopeCleaner.isRunning()) {
scopeBindings.putAll(bindings);
}
} | java | public void addScopeBindings(Map<Class<? extends Annotation>, Scope> bindings) {
if (scopeCleaner.isRunning()) {
scopeBindings.putAll(bindings);
}
} | [
"public",
"void",
"addScopeBindings",
"(",
"Map",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Scope",
">",
"bindings",
")",
"{",
"if",
"(",
"scopeCleaner",
".",
"isRunning",
"(",
")",
")",
"{",
"scopeBindings",
".",
"putAll",
"(",
"bindin... | allows late-binding of scopes to PreDestroyMonitor, useful if more than one
Injector contributes scope bindings
@param bindings additional annotation-to-scope bindings to add | [
"allows",
"late",
"-",
"binding",
"of",
"scopes",
"to",
"PreDestroyMonitor",
"useful",
"if",
"more",
"than",
"one",
"Injector",
"contributes",
"scope",
"bindings"
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-core/src/main/java/com/netflix/governator/internal/PreDestroyMonitor.java#L181-L185 | train |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/internal/PreDestroyMonitor.java | PreDestroyMonitor.close | @Override
public void close() throws Exception {
if (scopeCleaner.close()) { // executor thread to exit processing loop
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");
}
} | java | @Override
public void close() throws Exception {
if (scopeCleaner.close()) { // executor thread to exit processing loop
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");
}
} | [
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"scopeCleaner",
".",
"close",
"(",
")",
")",
"{",
"// executor thread to exit processing loop ",
"LOGGER",
".",
"info",
"(",
"\"closing PreDestroyMonitor...\"",
"... | final cleanup of managed instances if any | [
"final",
"cleanup",
"of",
"managed",
"instances",
"if",
"any"
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-core/src/main/java/com/netflix/governator/internal/PreDestroyMonitor.java#L190-L212 | train |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java | InjectorBuilder.combineWith | 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;
} | java | 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;
} | [
"public",
"InjectorBuilder",
"combineWith",
"(",
"Module",
"...",
"modules",
")",
"{",
"List",
"<",
"Module",
">",
"m",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"m",
".",
"add",
"(",
"module",
")",
";",
"m",
".",
"addAll",
"(",
"Arrays",
".",
... | Add additional bindings to the module tracked by the DSL
@param modules | [
"Add",
"additional",
"bindings",
"to",
"the",
"module",
"tracked",
"by",
"the",
"DSL"
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java#L96-L102 | train |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java | InjectorBuilder.forEachElement | public <T> InjectorBuilder forEachElement(ElementVisitor<T> visitor, Consumer<T> consumer) {
Elements
.getElements(module)
.forEach(element -> Optional.ofNullable(element.acceptVisitor(visitor)).ifPresent(consumer));
return this;
} | java | public <T> InjectorBuilder forEachElement(ElementVisitor<T> visitor, Consumer<T> consumer) {
Elements
.getElements(module)
.forEach(element -> Optional.ofNullable(element.acceptVisitor(visitor)).ifPresent(consumer));
return this;
} | [
"public",
"<",
"T",
">",
"InjectorBuilder",
"forEachElement",
"(",
"ElementVisitor",
"<",
"T",
">",
"visitor",
",",
"Consumer",
"<",
"T",
">",
"consumer",
")",
"{",
"Elements",
".",
"getElements",
"(",
"module",
")",
".",
"forEach",
"(",
"element",
"->",
... | 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.
This call will not modify any bindings
@param visitor | [
"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",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java#L123-L128 | train |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java | InjectorBuilder.forEachElement | public <T> InjectorBuilder forEachElement(ElementVisitor<T> visitor) {
Elements
.getElements(module)
.forEach(element -> element.acceptVisitor(visitor));
return this;
} | java | public <T> InjectorBuilder forEachElement(ElementVisitor<T> visitor) {
Elements
.getElements(module)
.forEach(element -> element.acceptVisitor(visitor));
return this;
} | [
"public",
"<",
"T",
">",
"InjectorBuilder",
"forEachElement",
"(",
"ElementVisitor",
"<",
"T",
">",
"visitor",
")",
"{",
"Elements",
".",
"getElements",
"(",
"module",
")",
".",
"forEach",
"(",
"element",
"->",
"element",
".",
"acceptVisitor",
"(",
"visitor"... | Call the provided visitor for all elements of the current module.
This call will not modify any bindings
@param visitor | [
"Call",
"the",
"provided",
"visitor",
"for",
"all",
"elements",
"of",
"the",
"current",
"module",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java#L136-L141 | train |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java | InjectorBuilder.filter | 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;
} | java | 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;
} | [
"public",
"InjectorBuilder",
"filter",
"(",
"ElementVisitor",
"<",
"Boolean",
">",
"predicate",
")",
"{",
"List",
"<",
"Element",
">",
"elements",
"=",
"new",
"ArrayList",
"<",
"Element",
">",
"(",
")",
";",
"for",
"(",
"Element",
"element",
":",
"Elements... | Filter out elements for which the provided visitor returns true.
@param predicate | [
"Filter",
"out",
"elements",
"for",
"which",
"the",
"provided",
"visitor",
"returns",
"true",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java#L173-L182 | train |
Netflix/governator | governator-legacy/src/main/java/com/netflix/governator/guice/ModulesEx.java | ModulesEx.combineAndOverride | 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;
} | java | 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;
} | [
"public",
"static",
"Module",
"combineAndOverride",
"(",
"List",
"<",
"?",
"extends",
"Module",
">",
"modules",
")",
"{",
"Iterator",
"<",
"?",
"extends",
"Module",
">",
"iter",
"=",
"modules",
".",
"iterator",
"(",
")",
";",
"Module",
"current",
"=",
"M... | Generate a single module that is produced by accumulating and overriding
each module with the next.
<pre>
{@code
Guice.createInjector(ModuleUtils.combineAndOverride(moduleA, moduleAOverrides, moduleB));
}
</pre>
@param modules
@return | [
"Generate",
"a",
"single",
"module",
"that",
"is",
"produced",
"by",
"accumulating",
"and",
"overriding",
"each",
"module",
"with",
"the",
"next",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/ModulesEx.java#L43-L54 | train |
Netflix/governator | governator-legacy/src/main/java/com/netflix/governator/guice/ModulesEx.java | ModulesEx.fromClass | public static Module fromClass(final Class<?> cls, final boolean override) {
List<Module> modules = new ArrayList<>();
// Iterate through all annotations of the main class, create a binding for the annotation
// and add the module to the list of modules to install
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);
}
} | java | public static Module fromClass(final Class<?> cls, final boolean override) {
List<Module> modules = new ArrayList<>();
// Iterate through all annotations of the main class, create a binding for the annotation
// and add the module to the list of modules to install
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);
}
} | [
"public",
"static",
"Module",
"fromClass",
"(",
"final",
"Class",
"<",
"?",
">",
"cls",
",",
"final",
"boolean",
"override",
")",
"{",
"List",
"<",
"Module",
">",
"modules",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"// Iterate through all annotations of... | Create a single module that derived from all bootstrap annotations
on a class, where that class itself is a module.
For example,
<pre>
{@code
public class MainApplicationModule extends AbstractModule {
@Override
public void configure() {
// Application specific bindings here
}
public static void main(String[] args) {
Guice.createInjector(ModulesEx.fromClass(MainApplicationModule.class));
}
}
}
</pre>
@author elandau | [
"Create",
"a",
"single",
"module",
"that",
"derived",
"from",
"all",
"bootstrap",
"annotations",
"on",
"a",
"class",
"where",
"that",
"class",
"itself",
"is",
"a",
"module",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/ModulesEx.java#L81-L109 | train |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/Governator.java | Governator.setFeature | public <T> Governator setFeature(GovernatorFeature<T> feature, T value) {
this.featureOverrides.put(feature, value);
return this;
} | java | public <T> Governator setFeature(GovernatorFeature<T> feature, T value) {
this.featureOverrides.put(feature, value);
return this;
} | [
"public",
"<",
"T",
">",
"Governator",
"setFeature",
"(",
"GovernatorFeature",
"<",
"T",
">",
"feature",
",",
"T",
"value",
")",
"{",
"this",
".",
"featureOverrides",
".",
"put",
"(",
"feature",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Set a feature
@param feature Feature to set
@return this | [
"Set",
"a",
"feature"
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-core/src/main/java/com/netflix/governator/Governator.java#L190-L193 | train |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/Governator.java | Governator.run | private LifecycleInjector run(Module externalModule, final String[] args) {
return InjectorBuilder
.fromModules(modules)
.combineWith(externalModule)
.map(new ModuleTransformer() {
@Override
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));
} | java | private LifecycleInjector run(Module externalModule, final String[] args) {
return InjectorBuilder
.fromModules(modules)
.combineWith(externalModule)
.map(new ModuleTransformer() {
@Override
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));
} | [
"private",
"LifecycleInjector",
"run",
"(",
"Module",
"externalModule",
",",
"final",
"String",
"[",
"]",
"args",
")",
"{",
"return",
"InjectorBuilder",
".",
"fromModules",
"(",
"modules",
")",
".",
"combineWith",
"(",
"externalModule",
")",
".",
"map",
"(",
... | Create the injector and call any LifecycleListeners
@param args - Runtime parameter (from main) injectable as {@literal @}Arguments String[]
@return the LifecycleInjector for this run | [
"Create",
"the",
"injector",
"and",
"call",
"any",
"LifecycleListeners"
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-core/src/main/java/com/netflix/governator/Governator.java#L288-L308 | train |
Netflix/governator | governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java | Grapher.toFile | public String toFile() throws Exception {
File file = File.createTempFile("GuiceDependencies_", ".dot");
toFile(file);
return file.getCanonicalPath();
} | java | public String toFile() throws Exception {
File file = File.createTempFile("GuiceDependencies_", ".dot");
toFile(file);
return file.getCanonicalPath();
} | [
"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.
@return the name of the newly created file | [
"Writes",
"the",
"Dot",
"graph",
"to",
"a",
"new",
"temp",
"file",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java#L120-L124 | train |
Netflix/governator | governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java | Grapher.toFile | public void toFile(File file) throws Exception {
PrintWriter out = new PrintWriter(file, "UTF-8");
try {
out.write(graph());
}
finally {
Closeables.close(out, true);
}
} | java | public void toFile(File file) throws Exception {
PrintWriter out = new PrintWriter(file, "UTF-8");
try {
out.write(graph());
}
finally {
Closeables.close(out, true);
}
} | [
"public",
"void",
"toFile",
"(",
"File",
"file",
")",
"throws",
"Exception",
"{",
"PrintWriter",
"out",
"=",
"new",
"PrintWriter",
"(",
"file",
",",
"\"UTF-8\"",
")",
";",
"try",
"{",
"out",
".",
"write",
"(",
"graph",
"(",
")",
")",
";",
"}",
"final... | Writes the "Dot" graph to a given file.
@param file file to write to | [
"Writes",
"the",
"Dot",
"graph",
"to",
"a",
"given",
"file",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java#L131-L139 | train |
Netflix/governator | governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java | Grapher.graph | 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"));
} | java | 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"));
} | [
"public",
"String",
"graph",
"(",
")",
"throws",
"Exception",
"{",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"PrintWriter",
"out",
"=",
"new",
"PrintWriter",
"(",
"baos",
")",
";",
"Injector",
"localInjector",
"=",
"G... | Returns a String containing the "Dot" graph definition.
@return the "Dot" graph definition | [
"Returns",
"a",
"String",
"containing",
"the",
"Dot",
"graph",
"definition",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java#L146-L158 | train |
Netflix/governator | governator-jersey/src/main/java/com/netflix/governator/guice/jersey/GovernatorComponentProviderFactory.java | GovernatorComponentProviderFactory.isGuiceConstructorInjected | public boolean isGuiceConstructorInjected(Class<?> c) {
for (Constructor<?> con : c.getDeclaredConstructors()) {
if (isInjectable(con)) {
return true;
}
}
return false;
} | java | public boolean isGuiceConstructorInjected(Class<?> c) {
for (Constructor<?> con : c.getDeclaredConstructors()) {
if (isInjectable(con)) {
return true;
}
}
return false;
} | [
"public",
"boolean",
"isGuiceConstructorInjected",
"(",
"Class",
"<",
"?",
">",
"c",
")",
"{",
"for",
"(",
"Constructor",
"<",
"?",
">",
"con",
":",
"c",
".",
"getDeclaredConstructors",
"(",
")",
")",
"{",
"if",
"(",
"isInjectable",
"(",
"con",
")",
")... | Determine if a class is an implicit Guice component that can be
instantiated by Guice and the life-cycle managed by Jersey.
@param c the class.
@return true if the class is an implicit Guice component. | [
"Determine",
"if",
"a",
"class",
"is",
"an",
"implicit",
"Guice",
"component",
"that",
"can",
"be",
"instantiated",
"by",
"Guice",
"and",
"the",
"life",
"-",
"cycle",
"managed",
"by",
"Jersey",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-jersey/src/main/java/com/netflix/governator/guice/jersey/GovernatorComponentProviderFactory.java#L163-L171 | train |
Netflix/governator | governator-jersey/src/main/java/com/netflix/governator/guice/jersey/GovernatorComponentProviderFactory.java | GovernatorComponentProviderFactory.createScopeMap | 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;
} | java | 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;
} | [
"public",
"Map",
"<",
"Scope",
",",
"ComponentScope",
">",
"createScopeMap",
"(",
")",
"{",
"Map",
"<",
"Scope",
",",
"ComponentScope",
">",
"result",
"=",
"new",
"HashMap",
"<",
"Scope",
",",
"ComponentScope",
">",
"(",
")",
";",
"result",
".",
"put",
... | Maps a Guice scope to a Jersey scope.
@return the map | [
"Maps",
"a",
"Guice",
"scope",
"to",
"a",
"Jersey",
"scope",
"."
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-jersey/src/main/java/com/netflix/governator/guice/jersey/GovernatorComponentProviderFactory.java#L206-L212 | train |
Netflix/governator | governator-legacy/src/main/java/com/netflix/governator/configuration/ColumnPrinter.java | ColumnPrinter.addColumn | void addColumn(String columnName)
{
data.add(new ArrayList<String>());
columnNames.add(columnName);
} | java | void addColumn(String columnName)
{
data.add(new ArrayList<String>());
columnNames.add(columnName);
} | [
"void",
"addColumn",
"(",
"String",
"columnName",
")",
"{",
"data",
".",
"add",
"(",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
")",
";",
"columnNames",
".",
"add",
"(",
"columnName",
")",
";",
"}"
] | Add a column
@param columnName name of the column | [
"Add",
"a",
"column"
] | c1f4bb1518e759c61f2e9cad8a896ec6beba0294 | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/configuration/ColumnPrinter.java#L48-L52 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.