description
stringlengths 11
2.86k
| focal_method
stringlengths 70
6.25k
| test_case
stringlengths 96
15.3k
|
---|---|---|
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyDirectBufferToNativeMemory() {
final byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
final ByteBuffer buf = ByteBuffer.allocateDirect(bytes.length);
buf.put(bytes).rewind();
assertEquals(8, buf.remaining());
final Pointer ptr = BufferUtils.copyToNativeMemory(buf);
assertNotNull(ptr);
assertArrayEquals(bytes, ptr.getByteArray(0, bytes.length));
assertAll("buffer's state",
() -> assertEquals(0, buf.position()),
() -> assertEquals(8, buf.limit())
);
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copySlicedDirectBufferToNativeMemory() {
final byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
final byte[] slicedBytes = new byte[] {2, 3, 4, 5};
final ByteBuffer buf = ByteBuffer.allocateDirect(bytes.length);
buf.put(bytes).rewind();
// slice 4 bytes
buf.position(2).limit(6);
assertEquals(4, buf.remaining());
final Pointer ptr = BufferUtils.copyToNativeMemory(buf);
assertNotNull(ptr);
assertArrayEquals(slicedBytes, ptr.getByteArray(0, slicedBytes.length));
assertAll("buffer's state",
() -> assertEquals(2, buf.position()),
() -> assertEquals(6, buf.limit())
);
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyNullFloatArrayToNativeMemory() {
final float[] values = null; // test case
final int offset = 0;
final int length = 0;
assertThrows(
IllegalArgumentException.class,
() -> BufferUtils.copyToNativeMemory(values, offset, length));
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyNegativeOffsetFloatArrayToNativeMemory() {
final float[] values = new float[] {0f, 1f, 2f, 3f};
final int offset = -1; // test case
final int length = values.length;
assertThrows(
ArrayIndexOutOfBoundsException.class,
() -> BufferUtils.copyToNativeMemory(values, offset, length));
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyNegativeLengthFloatArrayToNativeMemory() {
final float[] values = new float[] {0f, 1f, 2f, 3f};
final int offset = 0;
final int length = -1; // test case
assertThrows(
IllegalArgumentException.class,
() -> BufferUtils.copyToNativeMemory(values, offset, length));
} |
["('/**\\\\n * Throws {@link MenohException} if the <code>errorCode</code> of a native Menoh function is\\\\n * non-zero. This method must be called right after the invocation because it uses <code>\\\\n * menoh_get_last_error_message</code>.\\\\n *\\\\n * @param errorCode an error code returned from the Menoh function\\\\n */', '')", "('', '// ErrorCode.valueOf() throws MenohException if the error code is undefined\\n')"] | b'/**\n * Throws {@link MenohException} if the <code>errorCode</code> of a native Menoh function is\n * non-zero. This method must be called right after the invocation because it uses <code>\n * menoh_get_last_error_message</code>.\n *\n * @param errorCode an error code returned from the Menoh function\n */'static void checkError(int errorCode) throws MenohException {
if (errorCode != ErrorCode.SUCCESS.getId()) {
final String errorMessage = MenohNative.INSTANCE.menoh_get_last_error_message();
ErrorCode ec;
try {
ec = ErrorCode.valueOf(errorCode);
} catch (MenohException e) {
// ErrorCode.valueOf() throws MenohException if the error code is undefined
throw new MenohException(ErrorCode.UNDEFINED, String.format("%s (%d)", errorMessage, errorCode), e);
}
final String errorCodeName = ec.toString().toLowerCase(Locale.ENGLISH);
throw new MenohException(ec, String.format("%s (%s)", errorMessage, errorCodeName));
}
} | @Test
public void checkErrorSuccess() {
checkError(ErrorCode.SUCCESS.getId());
} |
["('/**\\\\n * Loads an ONNX model from the specified file.\\\\n */', '')"] | b'/**\n * Loads an ONNX model from the specified file.\n */'public static ModelData fromOnnxFile(String onnxModelPath) throws MenohException {
final PointerByReference handle = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_model_data_from_onnx(onnxModelPath, handle));
return new ModelData(handle.getValue());
} | @Test
public void makeFromNonExistentOnnxFile() {
MenohException e = assertThrows(
MenohException.class, () -> ModelData.fromOnnxFile("__NON_EXISTENT_FILENAME__"));
assertAll("non-existent onnx file",
() -> assertEquals(ErrorCode.INVALID_FILENAME, e.getErrorCode()),
() -> assertEquals(
"menoh invalid filename error: __NON_EXISTENT_FILENAME__ (invalid_filename)",
e.getMessage())
);
} |
["('/**\\\\n * Loads an ONNX model from the specified file.\\\\n */', '')"] | b'/**\n * Loads an ONNX model from the specified file.\n */'public static ModelData fromOnnxFile(String onnxModelPath) throws MenohException {
final PointerByReference handle = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_model_data_from_onnx(onnxModelPath, handle));
return new ModelData(handle.getValue());
} | @Test
public void makeFromInvalidOnnxFile() throws Exception {
final String path = getResourceFilePath("models/invalid_format.onnx");
MenohException e = assertThrows(MenohException.class, () -> ModelData.fromOnnxFile(path));
assertAll("invalid onnx file",
() -> assertEquals(ErrorCode.ONNX_PARSE_ERROR, e.getErrorCode()),
() -> assertEquals(
String.format("menoh onnx parse error: %s (onnx_parse_error)", path),
e.getMessage())
);
} |
["('/**\\\\n * Loads an ONNX model from the specified file.\\\\n */', '')"] | b'/**\n * Loads an ONNX model from the specified file.\n */'public static ModelData fromOnnxFile(String onnxModelPath) throws MenohException {
final PointerByReference handle = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_model_data_from_onnx(onnxModelPath, handle));
return new ModelData(handle.getValue());
} | @Test
public void makeFromUnsupportedOnnxOpsetVersionFile() throws Exception {
// Note: This file is a copy of and_op.onnx which is edited the last byte to 127 (0x7e)
final String path = getResourceFilePath("models/unsupported_onnx_opset_version.onnx");
MenohException e = assertThrows(MenohException.class, () -> ModelData.fromOnnxFile(path));
assertAll("invalid onnx file",
() -> assertEquals(ErrorCode.UNSUPPORTED_ONNX_OPSET_VERSION, e.getErrorCode()),
() -> assertEquals(
String.format(
"menoh unsupported onnx opset version error: %s has "
+ "onnx opset version %d > %d (unsupported_onnx_opset_version)",
path, 127, 7),
e.getMessage())
);
} |
["('/**\\\\n * Creates a {@link ModelBuilder}.\\\\n */', '')"] | b'/**\n * Creates a {@link ModelBuilder}.\n */'public static ModelBuilder builder(VariableProfileTable vpt) throws MenohException {
final PointerByReference ref = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_model_builder(vpt.nativeHandle(), ref));
return new ModelBuilder(ref.getValue());
} | @Test
public void buildModelIfBackendNotFound() throws Exception {
final String path = getResourceFilePath("models/and_op.onnx");
final int batchSize = 4;
final int inputDim = 2;
final String backendName = "__non_existent_backend__"; // test case
final String backendConfig = "";
try (
ModelData modelData = ModelData.fromOnnxFile(path);
VariableProfileTableBuilder vptBuilder = VariableProfileTable.builder()
.addInputProfile("input", DType.FLOAT, new int[] {batchSize, inputDim})
.addOutputProfile("output", DType.FLOAT);
VariableProfileTable vpt = vptBuilder.build(modelData);
ModelBuilder modelBuilder = Model.builder(vpt)
) {
modelBuilder.attachExternalBuffer("input", new float[] {0f, 0f, 0f, 1f, 1f, 0f, 1f, 1f});
MenohException e = assertThrows(
MenohException.class, () -> modelBuilder.build(modelData, backendName, backendConfig));
assertAll("backendName is invalid",
() -> assertEquals(ErrorCode.INVALID_BACKEND_NAME, e.getErrorCode()),
() -> assertEquals(
String.format("menoh invalid backend name error: %s (invalid_backend_name)", backendName),
e.getMessage())
);
}
} |
["('/**\\\\n * Creates a {@link VariableProfileTableBuilder}.\\\\n */', '')"] | b'/**\n * Creates a {@link VariableProfileTableBuilder}.\n */'public static VariableProfileTableBuilder builder() throws MenohException {
final PointerByReference ref = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_variable_profile_table_builder(ref));
return new VariableProfileTableBuilder(ref.getValue());
} | @Test
public void addValidInputProfile() {
try (VariableProfileTableBuilder builder = VariableProfileTable.builder()) {
builder.addInputProfile("foo", DType.FLOAT, new int[] {1, 1});
}
} |
["('/**\\\\n * Creates a {@link VariableProfileTableBuilder}.\\\\n */', '')"] | b'/**\n * Creates a {@link VariableProfileTableBuilder}.\n */'public static VariableProfileTableBuilder builder() throws MenohException {
final PointerByReference ref = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_variable_profile_table_builder(ref));
return new VariableProfileTableBuilder(ref.getValue());
} | @Test
public void addValidInputProfileWithInvalidDims() {
try (VariableProfileTableBuilder builder = VariableProfileTable.builder()) {
MenohException e = assertThrows(MenohException.class,
// test case: dims.length == 1
() -> builder.addInputProfile("foo", DType.FLOAT, new int[] {1, 1, 1, 1, 1}));
assertAll("invalid dim size",
() -> assertEquals(ErrorCode.UNDEFINED, e.getErrorCode()),
() -> assertTrue(e.getMessage().startsWith("foo has an invalid dims size: 5"),
String.format("%s doesn't start with \"foo has an invalid dims size: 5\"",
e.getMessage())));
}
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyEmptyDirectBufferToNativeMemory() {
final ByteBuffer buf = ByteBuffer.allocateDirect(0);
assertEquals(0, buf.remaining());
assertThrows(
IllegalArgumentException.class,
() -> BufferUtils.copyToNativeMemory(buf));
} |
["('/**\\\\n * Creates a {@link VariableProfileTableBuilder}.\\\\n */', '')"] | b'/**\n * Creates a {@link VariableProfileTableBuilder}.\n */'public static VariableProfileTableBuilder builder() throws MenohException {
final PointerByReference ref = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_variable_profile_table_builder(ref));
return new VariableProfileTableBuilder(ref.getValue());
} | @Test
public void addValidOutputProfile() {
try (VariableProfileTableBuilder builder = VariableProfileTable.builder()) {
builder.addOutputProfile("foo", DType.FLOAT);
}
} |
["('/**\\\\n * Creates a {@link VariableProfileTableBuilder}.\\\\n */', '')"] | b'/**\n * Creates a {@link VariableProfileTableBuilder}.\n */'public static VariableProfileTableBuilder builder() throws MenohException {
final PointerByReference ref = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_variable_profile_table_builder(ref));
return new VariableProfileTableBuilder(ref.getValue());
} | @Test
public void buildVariableProfileTableIfInputProfileNameNotFound() throws Exception {
final String path = getResourceFilePath("models/and_op.onnx");
final int batchSize = 1;
final int inputDim = 2;
final String inputProfileName = "__non_existent_variable__"; // test case
final String inputVariableNameInModel = "input";
final String outputProfileName = "output";
try (
ModelData modelData = ModelData.fromOnnxFile(path);
VariableProfileTableBuilder vptBuilder = VariableProfileTable.builder()
.addInputProfile(inputProfileName, DType.FLOAT, new int[] {batchSize, inputDim})
.addOutputProfile(outputProfileName, DType.FLOAT)
) {
MenohException e = assertThrows(MenohException.class, () -> vptBuilder.build(modelData));
assertAll("input profile name not found",
() -> assertEquals(ErrorCode.VARIABLE_NOT_FOUND, e.getErrorCode()),
() -> assertEquals(
String.format("menoh variable not found error: %s (variable_not_found)",
inputVariableNameInModel), // not `inputProfileName`
e.getMessage())
);
}
} |
["('/**\\\\n * Creates a {@link VariableProfileTableBuilder}.\\\\n */', '')"] | b'/**\n * Creates a {@link VariableProfileTableBuilder}.\n */'public static VariableProfileTableBuilder builder() throws MenohException {
final PointerByReference ref = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_variable_profile_table_builder(ref));
return new VariableProfileTableBuilder(ref.getValue());
} | @Test
public void buildVariableProfileTableIfInputProfileDimsMismatched() throws Exception {
final String path = getResourceFilePath("models/and_op.onnx");
final int batchSize = 1;
final int inputDim = 3; // test case
final String inputProfileName = "input";
final String outputProfileName = "output";
try (
ModelData modelData = ModelData.fromOnnxFile(path);
VariableProfileTableBuilder vptBuilder = VariableProfileTable.builder()
.addInputProfile(inputProfileName, DType.FLOAT, new int[] {batchSize, inputDim})
.addOutputProfile(outputProfileName, DType.FLOAT)
) {
MenohException e = assertThrows(MenohException.class, () -> vptBuilder.build(modelData));
assertAll("mismatched input dims",
() -> assertEquals(ErrorCode.DIMENSION_MISMATCH, e.getErrorCode()),
() -> assertEquals(
String.format(
"menoh dimension mismatch error: Gemm issuing \"%s\": input[1] and weight[1] "
+ "actual value: %d valid value: %d (dimension_mismatch)",
"140211424823896", // the name of output[0] in Gemm layer
3, 2),
e.getMessage())
);
}
} |
["('/**\\\\n * Creates a {@link VariableProfileTableBuilder}.\\\\n */', '')"] | b'/**\n * Creates a {@link VariableProfileTableBuilder}.\n */'public static VariableProfileTableBuilder builder() throws MenohException {
final PointerByReference ref = new PointerByReference();
checkError(MenohNative.INSTANCE.menoh_make_variable_profile_table_builder(ref));
return new VariableProfileTableBuilder(ref.getValue());
} | @Test
public void buildVariableProfileTableIfOutputProfileNameNotFound() throws Exception {
final String path = getResourceFilePath("models/and_op.onnx");
final int batchSize = 1;
final int inputDim = 2;
final String inputProfileName = "input";
final String outputProfileName = "__non_existent_variable__"; // test case
try (
ModelData modelData = ModelData.fromOnnxFile(path);
VariableProfileTableBuilder vptBuilder = VariableProfileTable.builder()
.addInputProfile(inputProfileName, DType.FLOAT, new int[] {batchSize, inputDim})
.addOutputProfile(outputProfileName, DType.FLOAT)
) {
MenohException e = assertThrows(MenohException.class, () -> vptBuilder.build(modelData));
assertAll("output profile name not found",
() -> assertEquals(ErrorCode.VARIABLE_NOT_FOUND, e.getErrorCode()),
() -> assertEquals(
String.format("menoh variable not found error: %s (variable_not_found)", outputProfileName),
e.getMessage())
);
}
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyArrayBackedBufferToNativeMemory() {
final byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
final ByteBuffer buf = ByteBuffer.wrap(bytes);
assertEquals(8, buf.remaining());
final Pointer ptr = BufferUtils.copyToNativeMemory(buf);
assertNotNull(ptr);
assertArrayEquals(bytes, ptr.getByteArray(0, bytes.length));
assertAll("buffer's state",
() -> assertEquals(0, buf.position()),
() -> assertEquals(8, buf.limit())
);
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copySlicedArrayBackedBufferToNativeMemory() {
final byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
final byte[] slicedBytes = new byte[] {2, 3, 4, 5};
final ByteBuffer buf = ByteBuffer.wrap(bytes, 1, 6).slice();
assertAll("non-zero array offset",
() -> assertEquals(1, buf.arrayOffset()),
() -> assertEquals(0, buf.position()),
() -> assertEquals(6, buf.limit())
);
// slice 4 bytes
buf.position(1).limit(5);
assertEquals(4, buf.remaining());
final Pointer ptr = BufferUtils.copyToNativeMemory(buf);
assertNotNull(ptr);
assertArrayEquals(slicedBytes, ptr.getByteArray(0, slicedBytes.length));
assertAll("buffer's state",
() -> assertEquals(1, buf.position()),
() -> assertEquals(5, buf.limit())
);
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyReadOnlyBufferToNativeMemory() {
final byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
final ByteBuffer buf = ByteBuffer.wrap(bytes).asReadOnlyBuffer();
assertEquals(8, buf.remaining());
final Pointer ptr = BufferUtils.copyToNativeMemory(buf);
assertNotNull(ptr);
assertArrayEquals(bytes, ptr.getByteArray(0, bytes.length));
assertAll("buffer's state",
() -> assertEquals(0, buf.position()),
() -> assertEquals(8, buf.limit())
);
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copySlicedReadOnlyBufferToNativeMemory() {
final byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
final byte[] slicedBytes = new byte[] {2, 3, 4, 5};
final ByteBuffer buf = ByteBuffer.wrap(bytes).asReadOnlyBuffer();
// slice 4 bytes
buf.position(2).limit(6);
assertEquals(4, buf.remaining());
final Pointer ptr = BufferUtils.copyToNativeMemory(buf);
assertNotNull(ptr);
assertArrayEquals(slicedBytes, ptr.getByteArray(0, slicedBytes.length));
assertAll("buffer's state",
() -> assertEquals(2, buf.position()),
() -> assertEquals(6, buf.limit())
);
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyFloatArrayToNativeMemory() {
final float[] values = new float[] {0f, 1f, 2f, 3f};
final ByteBuffer valuesBuf = ByteBuffer.allocate(values.length * 4).order(ByteOrder.nativeOrder());
valuesBuf.asFloatBuffer().put(values);
final int offset = 0;
final int length = values.length;
final Pointer ptr = BufferUtils.copyToNativeMemory(values, offset, length);
assertNotNull(ptr);
assertAll("copied values in native memory",
() -> assertArrayEquals(values, ptr.getFloatArray(0, length)),
// check the byte order
() -> assertArrayEquals(valuesBuf.array(), ptr.getByteArray(0, length * 4))
);
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copySlicedFloatArrayToNativeMemory() {
final float[] values = new float[] {0f, 1f, 2f, 3f};
final float[] slicedValues = new float[] {1f, 2f};
final ByteBuffer slicedValuesBuf = ByteBuffer.allocate(slicedValues.length * 4).order(ByteOrder.nativeOrder());
slicedValuesBuf.asFloatBuffer().put(slicedValues);
final int offset = 1;
final int length = slicedValues.length;
// slice 2 elements (8 bytes)
final Pointer ptr = BufferUtils.copyToNativeMemory(values, offset, length);
assertNotNull(ptr);
assertAll("copied values in native memory",
() -> assertArrayEquals(slicedValues, ptr.getFloatArray(0, length)),
// check the byte order
() -> assertArrayEquals(slicedValuesBuf.array(), ptr.getByteArray(0, length * 4))
);
} |
["('/**\\\\n * <p>Copies a buffer to a native memory.</p>\\\\n *\\\\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\\\\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\\\\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\\\\n *\\\\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\\\\n * the native byte order of your platform may differ from JVM.</p>\\\\n *\\\\n * @param buffer the non-empty byte buffer from which to copy\\\\n *\\\\n * @return the pointer to the allocated native memory\\\\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\\\\n */', '')", "('', '// return a pointer to the direct buffer without copying\\n')", "('', '// it is array-backed and not read-only\\n')", "('', '// use duplicated buffer to avoid changing `position`\\n')"] | b'/**\n * <p>Copies a buffer to a native memory.</p>\n *\n * <p>If the <code>buffer</code> is direct, it will be attached to the model directly without copying.\n * Otherwise, it copies the content of the buffer to a newly allocated memory in the native heap ranging\n * from <code>position()</code> to <code>(limit() - 1)</code> without changing its position.</p>\n *\n * <p>Note that the <code>order()</code> of the buffer should be {@link ByteOrder#nativeOrder()} because\n * the native byte order of your platform may differ from JVM.</p>\n *\n * @param buffer the non-empty byte buffer from which to copy\n *\n * @return the pointer to the allocated native memory\n * @throws IllegalArgumentException if <code>buffer</code> is null or empty\n */'static Pointer copyToNativeMemory(final ByteBuffer buffer) {
if (buffer == null || buffer.remaining() <= 0) {
throw new IllegalArgumentException("buffer must not be null or empty");
}
final int length = buffer.remaining();
if (buffer.isDirect()) {
final int offset = buffer.position();
// return a pointer to the direct buffer without copying
return Native.getDirectBufferPointer(buffer).share(offset, length);
} else {
final Memory mem = new Memory(length);
int index;
byte[] bytes;
if (buffer.hasArray()) { // it is array-backed and not read-only
index = buffer.arrayOffset() + buffer.position();
bytes = buffer.array();
} else {
index = 0;
// use duplicated buffer to avoid changing `position`
bytes = new byte[length];
buffer.duplicate().get(bytes);
}
mem.write(0, bytes, index, length);
return mem.share(0, length);
}
} | @Test
public void copyEmptyFloatArrayToNativeMemory() {
final float[] values = new float[] {}; // test case
final int offset = 0;
final int length = values.length;
assertThrows(
IllegalArgumentException.class,
() -> BufferUtils.copyToNativeMemory(values, offset, length));
} |
["('', '// Append meta data.\\n')"] | Uri getAuthorizationUri(URL baseOAuthUrl, String clientId) {
try {
final Uri.Builder builder = Uri.parse(new URL(baseOAuthUrl, ApiConstants.AUTHORIZE).toURI().toString())
.buildUpon()
.appendQueryParameter(ARG_RESPONSE_TYPE, "code")
.appendQueryParameter(ARG_CLIENT_ID, clientId)
.appendQueryParameter(ARG_REDIRECT_URI, redirectUri.toString())
.appendQueryParameter(ARG_SCOPE, scope);
if (showSignUp) {
builder.appendQueryParameter(ARG_LAYOUT, LAYOUT_SIGNUP);
}
appendIfNotNull(builder, ARG_ACCOUNT, account);
appendIfNotNull(builder, ARG_ACCOUNT_CURRENCY, accountCurrency);
appendIfNotNull(builder, ARG_REFERRAL, referralId);
// Append meta data.
appendIfNotNull(builder, META_NAME, metaName);
appendIfNotNull(builder, META_SEND_LIMIT_AMOUNT, sendLimitAmount);
appendIfNotNull(builder, META_SEND_LIMIT_CURRENCY, sendLimitCurrency);
appendIfNotNull(builder, META_SEND_LIMIT_PERIOD, sendLimitPeriod);
return builder.build();
} catch (URISyntaxException | MalformedURLException e) {
throw new IllegalArgumentException(e);
}
} | @Test
public void shouldBuildCorrectUri() throws Exception {
// Given
final String clientId = "clientId";
final Uri redirectUri = Uri.parse("coinbase://some-app");
final String scope = "user:read";
final String baseOauthUrl = "https://www.coinbase.com/authorize";
final URL url = new URL(baseOauthUrl);
final Uri wantedUri = Uri.parse(baseOauthUrl)
.buildUpon()
.path(ApiConstants.AUTHORIZE)
// Add from request
.appendQueryParameter(AuthorizationRequest.ARG_RESPONSE_TYPE, "code")
.appendQueryParameter(AuthorizationRequest.ARG_CLIENT_ID, clientId)
.appendQueryParameter(AuthorizationRequest.ARG_REDIRECT_URI, redirectUri.toString())
.appendQueryParameter(AuthorizationRequest.ARG_SCOPE, scope)
.build();
// When
final Uri authorizationUri = new AuthorizationRequest(redirectUri, scope)
.getAuthorizationUri(url, clientId);
// Then
assertThat(authorizationUri).isEqualTo(wantedUri);
} |
["('/**\\\\n * Creates an instance of {@link PaginationParams} to get next page items.\\\\n * <p>\\\\n * Keeps limit and order from original {@link PaginationParams}.\\\\n *\\\\n * @param pagination current page pagination params.\\\\n * @return {@link PaginationParams} to get next items page.\\\\n * @throws IllegalArgumentException when {@link PagedResponse.Pagination#getNextUri()}\\\\n * returns <code>null</code>, which means, the end of the items\\\\n * list is already reached.\\\\n */', '')"] | b'/**\n * Creates an instance of {@link PaginationParams} to get next page items.\n * <p>\n * Keeps limit and order from original {@link PaginationParams}.\n *\n * @param pagination current page pagination params.\n * @return {@link PaginationParams} to get next items page.\n * @throws IllegalArgumentException when {@link PagedResponse.Pagination#getNextUri()}\n * returns <code>null</code>, which means, the end of the items\n * list is already reached.\n */'@SuppressWarnings("checkstyle:MultipleStringLiterals")
public static PaginationParams nextPage(@NonNull PagedResponse.Pagination pagination) throws IllegalArgumentException {
if (pagination.getNextUri() == null) {
return null;
}
try {
String startingAfterId = getQueryParameter(pagination.getNextUri(), STARTING_AFTER_KEY);
return copyLimitAndOrder(fromStartingAfter(startingAfterId), pagination);
} catch (Exception e) {
throw new IllegalArgumentException("Malformed url", e);
}
} | @Test
public void noNextPageNull_ParamsNull() {
// Given
PagedResponse.Pagination pagination = new PagedResponse.Pagination();
// When
PaginationParams paginationParams = PaginationParams.nextPage(pagination);
// Then
assertThat(paginationParams).isNull();
} |
["('/**\\\\n * Creates an instance of {@link PaginationParams} to get previous page items.\\\\n * <p>\\\\n * Keeps limit and order from original {@link PaginationParams}.\\\\n *\\\\n * @param pagination current page pagination params.\\\\n * @return {@link PaginationParams} to get previous items page.\\\\n * @throws IllegalArgumentException when {@link PagedResponse.Pagination#getPreviousUri()}\\\\n * returns <code>null</code>, which means, the beginning of the\\\\n * items list is already reached.\\\\n */', '')"] | b'/**\n * Creates an instance of {@link PaginationParams} to get previous page items.\n * <p>\n * Keeps limit and order from original {@link PaginationParams}.\n *\n * @param pagination current page pagination params.\n * @return {@link PaginationParams} to get previous items page.\n * @throws IllegalArgumentException when {@link PagedResponse.Pagination#getPreviousUri()}\n * returns <code>null</code>, which means, the beginning of the\n * items list is already reached.\n */'@SuppressWarnings("checkstyle:MultipleStringLiterals")
public static PaginationParams previousPage(@NonNull PagedResponse.Pagination pagination) throws IllegalArgumentException {
if (pagination.getPreviousUri() == null) {
return null;
}
try {
String endingBeforeId = getQueryParameter(pagination.getPreviousUri(), ENDING_BEFORE_KEY);
return copyLimitAndOrder(fromEndingBefore(endingBeforeId), pagination);
} catch (Exception e) {
throw new IllegalArgumentException("Malformed url", e);
}
} | @Test
public void noPreviousPageNull_ParamsNull() {
// Given
PagedResponse.Pagination pagination = new PagedResponse.Pagination();
// When
PaginationParams paginationParams = PaginationParams.previousPage(pagination);
// Then
assertThat(paginationParams).isNull();
} |
["('/**\\\\n * Creates an instance of {@link PaginationParams} to get next page items.\\\\n * <p>\\\\n * Keeps limit and order from original {@link PaginationParams}.\\\\n *\\\\n * @param pagination current page pagination params.\\\\n * @return {@link PaginationParams} to get next items page.\\\\n * @throws IllegalArgumentException when {@link PagedResponse.Pagination#getNextUri()}\\\\n * returns <code>null</code>, which means, the end of the items\\\\n * list is already reached.\\\\n */', '')"] | b'/**\n * Creates an instance of {@link PaginationParams} to get next page items.\n * <p>\n * Keeps limit and order from original {@link PaginationParams}.\n *\n * @param pagination current page pagination params.\n * @return {@link PaginationParams} to get next items page.\n * @throws IllegalArgumentException when {@link PagedResponse.Pagination#getNextUri()}\n * returns <code>null</code>, which means, the end of the items\n * list is already reached.\n */'@SuppressWarnings("checkstyle:MultipleStringLiterals")
public static PaginationParams nextPage(@NonNull PagedResponse.Pagination pagination) throws IllegalArgumentException {
if (pagination.getNextUri() == null) {
return null;
}
try {
String startingAfterId = getQueryParameter(pagination.getNextUri(), STARTING_AFTER_KEY);
return copyLimitAndOrder(fromStartingAfter(startingAfterId), pagination);
} catch (Exception e) {
throw new IllegalArgumentException("Malformed url", e);
}
} | @Test(expected = IllegalArgumentException.class)
public void noNextPage_nextIdNotProvided_ExceptionThrown() {
// Given
PagedResponse.Pagination pagination = new PagedResponse.Pagination();
pagination.setNextUri("/path");
// When
PaginationParams.nextPage(pagination);
// Then
Assertions.fail("Should throw an " + IllegalArgumentException.class);
} |
["('/**\\\\n * Creates an instance of {@link PaginationParams} to get previous page items.\\\\n * <p>\\\\n * Keeps limit and order from original {@link PaginationParams}.\\\\n *\\\\n * @param pagination current page pagination params.\\\\n * @return {@link PaginationParams} to get previous items page.\\\\n * @throws IllegalArgumentException when {@link PagedResponse.Pagination#getPreviousUri()}\\\\n * returns <code>null</code>, which means, the beginning of the\\\\n * items list is already reached.\\\\n */', '')"] | b'/**\n * Creates an instance of {@link PaginationParams} to get previous page items.\n * <p>\n * Keeps limit and order from original {@link PaginationParams}.\n *\n * @param pagination current page pagination params.\n * @return {@link PaginationParams} to get previous items page.\n * @throws IllegalArgumentException when {@link PagedResponse.Pagination#getPreviousUri()}\n * returns <code>null</code>, which means, the beginning of the\n * items list is already reached.\n */'@SuppressWarnings("checkstyle:MultipleStringLiterals")
public static PaginationParams previousPage(@NonNull PagedResponse.Pagination pagination) throws IllegalArgumentException {
if (pagination.getPreviousUri() == null) {
return null;
}
try {
String endingBeforeId = getQueryParameter(pagination.getPreviousUri(), ENDING_BEFORE_KEY);
return copyLimitAndOrder(fromEndingBefore(endingBeforeId), pagination);
} catch (Exception e) {
throw new IllegalArgumentException("Malformed url", e);
}
} | @Test(expected = IllegalArgumentException.class)
public void noPreviousPage_previousIdNotProvided_ExceptionThrown() {
// Given
PagedResponse.Pagination pagination = new PagedResponse.Pagination();
pagination.setPreviousUri("/path");
// When
PaginationParams.previousPage(pagination);
// Then
Assertions.fail("Should throw an " + IllegalArgumentException.class);
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void testUsingDeploymentForService() throws Exception {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setImpl("foo.Impl");
deployment.setConfig("-");
deployment.setServiceType("foo.Interface");
deployment.setName("The Great and wonderful Oz");
deployment.setMultiplicity(10);
ServiceElement serviceElement = ServiceElementFactory.create(deployment, null);
Assert.assertEquals(10, serviceElement.getPlanned());
Assert.assertEquals(SorcerEnv.getActualName("The Great and wonderful Oz"),
serviceElement.getName());
Assert.assertEquals("foo.Impl", serviceElement.getComponentBundle().getClassName());
Assert.assertTrue(serviceElement.getExportBundles().length==1);
Assert.assertEquals("foo.Interface", serviceElement.getExportBundles()[0].getClassName());
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void setDeploymentWebsterUrl() throws IOException, ConfigurationException, URISyntaxException, ResolverException {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir() + "/TestIP.groovy");
deployment.setWebsterUrl("http://spongebob:8080");
ServiceElement serviceElement = ServiceElementFactory.create(deployment, new File(getConfigDir() + "/TestIP.groovy"));
Assert.assertTrue(serviceElement.getExportURLs().length > 1);
Assert.assertEquals(serviceElement.getExportURLs()[0].getHost(), "spongebob");
Assert.assertEquals(serviceElement.getExportURLs()[0].getPort(), 8080);
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void testFixedUsingConfiguration() throws URISyntaxException, ResolverException, ConfigurationException, IOException {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir()+"/fixedConfig.config");
ServiceElement service = ServiceElementFactory.create(deployment, new File(getConfigDir()+"/fixedConfig.config"));
Assert.assertTrue(service.getPlanned()==10);
Assert.assertTrue(service.getProvisionType() == ServiceElement.ProvisionType.FIXED);
Assert.assertTrue(service.getMaxPerMachine()==-1);
} |
Get the DataService data directory The @link DataServiceDATADIR system property is first consulted if that property is not setValue the default is either the TMPDIR SystemgetPropertyjavaiotmpdirsorceruserdata is used and the @link DataServiceDATADIR system property is setValue @return The DataService data directory | b'/**\n * Get the DataService data directory. The {@link DataService#DATA_DIR} system property is first\n * consulted, if that property is not setValue, the default is either the TMPDIR\n * System.getProperty("java.io.tmpdir")/sorcer/user/data is used and the {@link DataService#DATA_DIR}\n * system property is setValue.\n *\n * @return The DataService data directory.\n */'public static String getDataDir() {
String dataDir = System.getProperty(DATA_DIR);
if(dataDir==null) {
dataDir = getDefaultDataDir();
System.setProperty(DATA_DIR, dataDir);
}
return dataDir;
} | @Test
public void testGetDataDir() {
String tmpDir = System.getenv("TMPDIR")==null?System.getProperty("java.io.tmpdir"):System.getenv("TMPDIR");
String dataDirName = new File(String.format(String.format("%s%ssorcer-%s%sdata",
tmpDir,
File.separator,
System.getProperty("user.name"),
File.separator))).getAbsolutePath();
System.err.println("===> "+dataDirName);
assertTrue(dataDirName.equals(DataService.getDataDir()));
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void setDeploymentWebsterOperator() throws IOException, ConfigurationException, URISyntaxException, ResolverException {
NetSignature methodEN = new NetSignature("executeFoo",
ServiceProvider.class,
"Yogi");
methodEN.setDeployment(deploy(configuration(getConfigDir() + "/TestIP.groovy"),
webster("http://spongebob:8080")));
ServiceElement serviceElement = ServiceElementFactory.create(methodEN.getDeployment(),
new File(getConfigDir() + "/TestIP.groovy"));
Assert.assertTrue(serviceElement.getExportURLs().length>1);
Assert.assertEquals(serviceElement.getExportURLs()[0].getHost(), "spongebob");
Assert.assertEquals(serviceElement.getExportURLs()[0].getPort(), 8080);
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void setDeploymentWebsterFromConfig() throws IOException, ConfigurationException, URISyntaxException, ResolverException {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir() + "/testWebster.config");
ServiceElement serviceElement = ServiceElementFactory.create(deployment, new File(getConfigDir() + "/testWebster.config"));
Assert.assertTrue(serviceElement.getExportURLs().length > 1);
Assert.assertEquals(serviceElement.getExportURLs()[0].getHost(), "127.0.0.1");
Assert.assertEquals(serviceElement.getExportURLs()[0].getPort(), 8080);
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void testIPAddresses() throws Exception {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setIps("10.0.1.9", "canebay.local");
deployment.setExcludeIps("10.0.1.7", "stingray.foo.local.net");
deployment.setConfig("-");
ServiceElement serviceElement = ServiceElementFactory.create(deployment, null);
SystemRequirements systemRequirements = serviceElement.getServiceLevelAgreements().getSystemRequirements();
Assert.assertEquals(4, systemRequirements.getSystemComponents().length);
verify(get("10.0.1.9", false, systemRequirements.getSystemComponents()), false);
verify(get("canebay.local", true, systemRequirements.getSystemComponents()), false);
verify(get("10.0.1.7", false, systemRequirements.getSystemComponents()), true);
verify(get("stingray.foo.local.net", true, systemRequirements.getSystemComponents()), true);
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void testIPAddressestisingConfiguration() throws IOException, ConfigurationException, URISyntaxException, ResolverException {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir() + "/testIP.config");
verifyServiceElement(ServiceElementFactory.create(deployment, new File(getConfigDir() + "/testIP.config")));
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void testIPAddressesUsingGroovyConfiguration() throws IOException, ConfigurationException, URISyntaxException, ResolverException {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir()+"/TestIP.groovy");
verifyServiceElement(ServiceElementFactory.create(deployment, new File(getConfigDir()+"/TestIP.groovy")));
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void testPlannedUsingGroovyConfiguration() throws URISyntaxException, ResolverException, ConfigurationException, IOException {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir()+"/PlannedConfig.groovy");
ServiceElement service = ServiceElementFactory.create(deployment, new File(getConfigDir()+"/PlannedConfig.groovy"));
Assert.assertTrue(service.getPlanned()==10);
Assert.assertTrue(service.getMaxPerMachine()==1);
Assert.assertTrue(service.getProvisionType() == ServiceElement.ProvisionType.DYNAMIC);
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void testFixedUsingGroovyConfiguration() throws URISyntaxException, ResolverException, ConfigurationException, IOException {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir()+"/FixedConfig.groovy");
ServiceElement service = ServiceElementFactory.create(deployment, new File(getConfigDir()+"/FixedConfig.groovy"));
Assert.assertTrue(service.getPlanned()==10);
Assert.assertTrue(service.getProvisionType() == ServiceElement.ProvisionType.FIXED);
} |
["('/**\\\\n * Create a {@link ServiceElement}.\\\\n *\\\\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\\\\n *\\\\n * @return A {@code ServiceElement}\\\\n *\\\\n * @throws ConfigurationException if there are problem reading the configuration\\\\n */', '')"] | b'/**\n * Create a {@link ServiceElement}.\n *\n * @param signature The {@link ServiceSignature}, must not be {@code null}.\n *\n * @return A {@code ServiceElement}\n *\n * @throws ConfigurationException if there are problem reading the configuration\n */'public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException,
ConfigurationException,
ResolverException,
URISyntaxException {
return create(signature.getDeployment(), configFile);
} | @Test
public void testPlannedUsingConfiguration() throws URISyntaxException, ResolverException, ConfigurationException, IOException {
ServiceDeployment deployment = new ServiceDeployment();
deployment.setConfig(getConfigDir()+"/plannedConfig.config");
ServiceElement service = ServiceElementFactory.create(deployment, new File(getConfigDir()+"/plannedConfig.config"));
Assert.assertTrue(service.getPlanned()==10);
Assert.assertTrue(service.getMaxPerMachine()==2);
Assert.assertTrue(service.getProvisionType() == ServiceElement.ProvisionType.DYNAMIC);
} |
["('/**\\\\n * Compute the set of literals common to all models of the formula.\\\\n * \\\\n * @param s\\\\n * a solver already feeded\\\\n * @return the set of literals common to all models of the formula contained\\\\n * in the solver, in dimacs format.\\\\n * @throws TimeoutException\\\\n */', '')", "('', '// i is in the backbone\\n')", "('', '// -i is in the backbone\\n')"] | b'/**\n * Compute the set of literals common to all models of the formula.\n * \n * @param s\n * a solver already feeded\n * @return the set of literals common to all models of the formula contained\n * in the solver, in dimacs format.\n * @throws TimeoutException\n */'public static IVecInt backbone(ISolver s) throws TimeoutException {
IVecInt backbone = new VecInt();
int nvars = s.nVars();
for (int i = 1; i <= nvars; i++) {
backbone.push(i);
if (s.isSatisfiable(backbone)) {
backbone.pop().push(-i);
if (s.isSatisfiable(backbone)) {
backbone.pop();
} else {
// i is in the backbone
backbone.pop().push(i);
}
} else {
// -i is in the backbone
backbone.pop().push(-i);
}
}
return backbone;
} | @Test
public void testBugUnitClauses() throws ContradictionException,
TimeoutException {
ISolver solver1 = SolverFactory.newDefault();
ISolver solver2 = SolverFactory.newDefault();
ISolver solver3 = SolverFactory.newDefault();
int[][] cnf1 = new int[][] { new int[] { 1 }, new int[] { 1, -2 },
new int[] { 1, -3 }, new int[] { -1, 2 } };
// A & (A v -B) & (A v -C) & (-A v B)
// (-A v B) & (A v -B) & (A v -C) & A | using a different order
int[][] cnf2 = new int[][] { new int[] { -1, 2 }, new int[] { 1, -2 },
new int[] { 1, -3 }, new int[] { 1 } };
// (-A v B) & (A v -B) & (A v -C) & A
// (-A v C) & (A v -C) & (A v -B) & A | swap B and C (2 <-> 3)
// (A v -B) & (-A v C) & (A v -C) & A | shift the first 3 clauses to the
// right
int[][] cnf3 = new int[][] { new int[] { 1, -2 }, new int[] { -1, 3 },
new int[] { 1, -3 }, new int[] { 1 } };
for (int[] is : cnf1) {
solver1.addClause(new VecInt(is));
}
for (int[] is : cnf2) {
solver2.addClause(new VecInt(is));
}
for (int[] is : cnf3) {
solver3.addClause(new VecInt(is));
}
IVecInt vecInt1 = RemiUtils.backbone(solver1);
assertEquals(vecInt1.size(), 2);
assertTrue(vecInt1.contains(1));
assertTrue(vecInt1.contains(2));
IVecInt vecInt2 = RemiUtils.backbone(solver2);
assertEquals(vecInt2.size(), 2);
assertTrue(vecInt2.contains(1));
assertTrue(vecInt2.contains(2));
IVecInt vecInt3 = RemiUtils.backbone(solver3);
assertEquals(vecInt3.size(), 2);
assertTrue(vecInt3.contains(1));
assertTrue(vecInt3.contains(3));
} |
["('/**\\\\n * Translate an optimization function into constraints and provides the\\\\n * binary literals in results. Works only when the value of the objective\\\\n * function is positive.\\\\n * \\\\n * @since 2.2\\\\n */', '')", "('', '// filling the buckets\\n')", "('', '// creating the adder\\n')"] | b'/**\n * Translate an optimization function into constraints and provides the\n * binary literals in results. Works only when the value of the objective\n * function is positive.\n * \n * @since 2.2\n */'public void optimisationFunction(IVecInt literals, IVec<BigInteger> coefs,
IVecInt result) throws ContradictionException {
IVec<IVecInt> buckets = new Vec<IVecInt>();
IVecInt bucket;
// filling the buckets
for (int i = 0; i < literals.size(); i++) {
int p = literals.get(i);
BigInteger a = coefs.get(i);
for (int j = 0; j < a.bitLength(); j++) {
bucket = createIfNull(buckets, j);
if (a.testBit(j)) {
bucket.push(p);
}
}
}
// creating the adder
int x, y, z;
int sum, carry;
for (int i = 0; i < buckets.size(); i++) {
bucket = buckets.get(i);
while (bucket.size() >= 3) {
x = bucket.get(0);
y = bucket.get(1);
z = bucket.get(2);
bucket.remove(x);
bucket.remove(y);
bucket.remove(z);
sum = nextFreeVarId(true);
carry = nextFreeVarId(true);
fullAdderSum(sum, x, y, z);
fullAdderCarry(carry, x, y, z);
additionalFullAdderConstraints(carry, sum, x, y, z);
bucket.push(sum);
createIfNull(buckets, i + 1).push(carry);
}
while (bucket.size() == 2) {
x = bucket.get(0);
y = bucket.get(1);
bucket.remove(x);
bucket.remove(y);
sum = nextFreeVarId(true);
carry = nextFreeVarId(true);
halfAdderSum(sum, x, y);
halfAdderCarry(carry, x, y);
bucket.push(sum);
createIfNull(buckets, i + 1).push(carry);
}
assert bucket.size() == 1;
result.push(bucket.last());
bucket.pop();
assert bucket.isEmpty();
}
} | @Test
public void testTwoValues() throws ContradictionException {
IVecInt literals = new VecInt().push(1).push(2);
IVec<BigInteger> coefs = new Vec<BigInteger>().push(
BigInteger.valueOf(3)).push(BigInteger.valueOf(6));
IVecInt result = new VecInt();
this.gator.optimisationFunction(literals, coefs, result);
System.out.println(result);
assertEquals(4, result.size());
} |
["('/**\\\\n * translate <code>y <=> (x1 => x2)</code>\\\\n * \\\\n * @param y\\\\n * @param x1\\\\n * the selector variable\\\\n * @param x2\\\\n * @return\\\\n * @throws ContradictionException\\\\n * @since 2.3.6\\\\n */', '')", "('', '// y <=> (x1 -> x2)\\n')", "('', '// y -> (x1 -> x2)\\n')", "('', '// y <- (x1 -> x2)\\n')", "('', '// not(x1 -> x2) or y\\n')", "('', '// x1 and not x2 or y\\n')", "('', '// (x1 or y) and (not x2 or y)\\n')"] | b'/**\n * translate <code>y <=> (x1 => x2)</code>\n * \n * @param y\n * @param x1\n * the selector variable\n * @param x2\n * @return\n * @throws ContradictionException\n * @since 2.3.6\n */'public IConstr[] it(int y, int x1, int x2) throws ContradictionException {
IConstr[] constrs = new IConstr[3];
IVecInt clause = new VecInt(5);
// y <=> (x1 -> x2)
// y -> (x1 -> x2)
clause.push(-y).push(-x1).push(x2);
constrs[0] = processClause(clause);
clause.clear();
// y <- (x1 -> x2)
// not(x1 -> x2) or y
// x1 and not x2 or y
// (x1 or y) and (not x2 or y)
clause.push(x1).push(y);
constrs[1] = processClause(clause);
clause.clear();
clause.push(-x2).push(y);
constrs[2] = processClause(clause);
return constrs;
} | @Test
public void testSATIfThen1() throws ContradictionException,
TimeoutException {
gator.it(1, 2, 3);
assertTrue(gator.isSatisfiable(new VecInt(new int[] { 1, 2, 3 })));
} |
["('/**\\\\n * translate <code>y <=> (x1 => x2)</code>\\\\n * \\\\n * @param y\\\\n * @param x1\\\\n * the selector variable\\\\n * @param x2\\\\n * @return\\\\n * @throws ContradictionException\\\\n * @since 2.3.6\\\\n */', '')", "('', '// y <=> (x1 -> x2)\\n')", "('', '// y -> (x1 -> x2)\\n')", "('', '// y <- (x1 -> x2)\\n')", "('', '// not(x1 -> x2) or y\\n')", "('', '// x1 and not x2 or y\\n')", "('', '// (x1 or y) and (not x2 or y)\\n')"] | b'/**\n * translate <code>y <=> (x1 => x2)</code>\n * \n * @param y\n * @param x1\n * the selector variable\n * @param x2\n * @return\n * @throws ContradictionException\n * @since 2.3.6\n */'public IConstr[] it(int y, int x1, int x2) throws ContradictionException {
IConstr[] constrs = new IConstr[3];
IVecInt clause = new VecInt(5);
// y <=> (x1 -> x2)
// y -> (x1 -> x2)
clause.push(-y).push(-x1).push(x2);
constrs[0] = processClause(clause);
clause.clear();
// y <- (x1 -> x2)
// not(x1 -> x2) or y
// x1 and not x2 or y
// (x1 or y) and (not x2 or y)
clause.push(x1).push(y);
constrs[1] = processClause(clause);
clause.clear();
clause.push(-x2).push(y);
constrs[2] = processClause(clause);
return constrs;
} | @Test
public void testSATIfThen2() throws ContradictionException,
TimeoutException {
gator.it(1, 2, 3);
assertFalse(gator.isSatisfiable(new VecInt(new int[] { 1, 2, -3 })));
} |
["('/**\\\\n * translate <code>y <=> (x1 => x2)</code>\\\\n * \\\\n * @param y\\\\n * @param x1\\\\n * the selector variable\\\\n * @param x2\\\\n * @return\\\\n * @throws ContradictionException\\\\n * @since 2.3.6\\\\n */', '')", "('', '// y <=> (x1 -> x2)\\n')", "('', '// y -> (x1 -> x2)\\n')", "('', '// y <- (x1 -> x2)\\n')", "('', '// not(x1 -> x2) or y\\n')", "('', '// x1 and not x2 or y\\n')", "('', '// (x1 or y) and (not x2 or y)\\n')"] | b'/**\n * translate <code>y <=> (x1 => x2)</code>\n * \n * @param y\n * @param x1\n * the selector variable\n * @param x2\n * @return\n * @throws ContradictionException\n * @since 2.3.6\n */'public IConstr[] it(int y, int x1, int x2) throws ContradictionException {
IConstr[] constrs = new IConstr[3];
IVecInt clause = new VecInt(5);
// y <=> (x1 -> x2)
// y -> (x1 -> x2)
clause.push(-y).push(-x1).push(x2);
constrs[0] = processClause(clause);
clause.clear();
// y <- (x1 -> x2)
// not(x1 -> x2) or y
// x1 and not x2 or y
// (x1 or y) and (not x2 or y)
clause.push(x1).push(y);
constrs[1] = processClause(clause);
clause.clear();
clause.push(-x2).push(y);
constrs[2] = processClause(clause);
return constrs;
} | @Test
public void testSATIfThen3() throws ContradictionException,
TimeoutException {
gator.it(1, 2, 3);
assertTrue(gator.isSatisfiable(new VecInt(new int[] { 1, -2, 3 })));
} |
["('/**\\\\n * translate <code>y <=> (x1 => x2)</code>\\\\n * \\\\n * @param y\\\\n * @param x1\\\\n * the selector variable\\\\n * @param x2\\\\n * @return\\\\n * @throws ContradictionException\\\\n * @since 2.3.6\\\\n */', '')", "('', '// y <=> (x1 -> x2)\\n')", "('', '// y -> (x1 -> x2)\\n')", "('', '// y <- (x1 -> x2)\\n')", "('', '// not(x1 -> x2) or y\\n')", "('', '// x1 and not x2 or y\\n')", "('', '// (x1 or y) and (not x2 or y)\\n')"] | b'/**\n * translate <code>y <=> (x1 => x2)</code>\n * \n * @param y\n * @param x1\n * the selector variable\n * @param x2\n * @return\n * @throws ContradictionException\n * @since 2.3.6\n */'public IConstr[] it(int y, int x1, int x2) throws ContradictionException {
IConstr[] constrs = new IConstr[3];
IVecInt clause = new VecInt(5);
// y <=> (x1 -> x2)
// y -> (x1 -> x2)
clause.push(-y).push(-x1).push(x2);
constrs[0] = processClause(clause);
clause.clear();
// y <- (x1 -> x2)
// not(x1 -> x2) or y
// x1 and not x2 or y
// (x1 or y) and (not x2 or y)
clause.push(x1).push(y);
constrs[1] = processClause(clause);
clause.clear();
clause.push(-x2).push(y);
constrs[2] = processClause(clause);
return constrs;
} | @Test
public void testSATIfThen() throws ContradictionException, TimeoutException {
gator.it(1, 2, 3);
assertTrue(gator.isSatisfiable(new VecInt(new int[] { 1, -2, -3 })));
} |
["('/**\\\\n * translate <code>y <=> (x1 => x2)</code>\\\\n * \\\\n * @param y\\\\n * @param x1\\\\n * the selector variable\\\\n * @param x2\\\\n * @return\\\\n * @throws ContradictionException\\\\n * @since 2.3.6\\\\n */', '')", "('', '// y <=> (x1 -> x2)\\n')", "('', '// y -> (x1 -> x2)\\n')", "('', '// y <- (x1 -> x2)\\n')", "('', '// not(x1 -> x2) or y\\n')", "('', '// x1 and not x2 or y\\n')", "('', '// (x1 or y) and (not x2 or y)\\n')"] | b'/**\n * translate <code>y <=> (x1 => x2)</code>\n * \n * @param y\n * @param x1\n * the selector variable\n * @param x2\n * @return\n * @throws ContradictionException\n * @since 2.3.6\n */'public IConstr[] it(int y, int x1, int x2) throws ContradictionException {
IConstr[] constrs = new IConstr[3];
IVecInt clause = new VecInt(5);
// y <=> (x1 -> x2)
// y -> (x1 -> x2)
clause.push(-y).push(-x1).push(x2);
constrs[0] = processClause(clause);
clause.clear();
// y <- (x1 -> x2)
// not(x1 -> x2) or y
// x1 and not x2 or y
// (x1 or y) and (not x2 or y)
clause.push(x1).push(y);
constrs[1] = processClause(clause);
clause.clear();
clause.push(-x2).push(y);
constrs[2] = processClause(clause);
return constrs;
} | @Test
public void testSATIfThen5() throws ContradictionException,
TimeoutException {
gator.it(1, 2, 3);
assertFalse(gator.isSatisfiable(new VecInt(new int[] { -1, 2, 3 })));
} |
["('/**\\\\n * translate <code>y <=> (x1 => x2)</code>\\\\n * \\\\n * @param y\\\\n * @param x1\\\\n * the selector variable\\\\n * @param x2\\\\n * @return\\\\n * @throws ContradictionException\\\\n * @since 2.3.6\\\\n */', '')", "('', '// y <=> (x1 -> x2)\\n')", "('', '// y -> (x1 -> x2)\\n')", "('', '// y <- (x1 -> x2)\\n')", "('', '// not(x1 -> x2) or y\\n')", "('', '// x1 and not x2 or y\\n')", "('', '// (x1 or y) and (not x2 or y)\\n')"] | b'/**\n * translate <code>y <=> (x1 => x2)</code>\n * \n * @param y\n * @param x1\n * the selector variable\n * @param x2\n * @return\n * @throws ContradictionException\n * @since 2.3.6\n */'public IConstr[] it(int y, int x1, int x2) throws ContradictionException {
IConstr[] constrs = new IConstr[3];
IVecInt clause = new VecInt(5);
// y <=> (x1 -> x2)
// y -> (x1 -> x2)
clause.push(-y).push(-x1).push(x2);
constrs[0] = processClause(clause);
clause.clear();
// y <- (x1 -> x2)
// not(x1 -> x2) or y
// x1 and not x2 or y
// (x1 or y) and (not x2 or y)
clause.push(x1).push(y);
constrs[1] = processClause(clause);
clause.clear();
clause.push(-x2).push(y);
constrs[2] = processClause(clause);
return constrs;
} | @Test
public void testSATIfThen6() throws ContradictionException,
TimeoutException {
gator.it(1, 2, 3);
assertTrue(gator.isSatisfiable(new VecInt(new int[] { -1, 2, -3 })));
} |
["('/**\\\\n * translate <code>y <=> (x1 => x2)</code>\\\\n * \\\\n * @param y\\\\n * @param x1\\\\n * the selector variable\\\\n * @param x2\\\\n * @return\\\\n * @throws ContradictionException\\\\n * @since 2.3.6\\\\n */', '')", "('', '// y <=> (x1 -> x2)\\n')", "('', '// y -> (x1 -> x2)\\n')", "('', '// y <- (x1 -> x2)\\n')", "('', '// not(x1 -> x2) or y\\n')", "('', '// x1 and not x2 or y\\n')", "('', '// (x1 or y) and (not x2 or y)\\n')"] | b'/**\n * translate <code>y <=> (x1 => x2)</code>\n * \n * @param y\n * @param x1\n * the selector variable\n * @param x2\n * @return\n * @throws ContradictionException\n * @since 2.3.6\n */'public IConstr[] it(int y, int x1, int x2) throws ContradictionException {
IConstr[] constrs = new IConstr[3];
IVecInt clause = new VecInt(5);
// y <=> (x1 -> x2)
// y -> (x1 -> x2)
clause.push(-y).push(-x1).push(x2);
constrs[0] = processClause(clause);
clause.clear();
// y <- (x1 -> x2)
// not(x1 -> x2) or y
// x1 and not x2 or y
// (x1 or y) and (not x2 or y)
clause.push(x1).push(y);
constrs[1] = processClause(clause);
clause.clear();
clause.push(-x2).push(y);
constrs[2] = processClause(clause);
return constrs;
} | @Test
public void testSATIfThen7() throws ContradictionException,
TimeoutException {
gator.it(1, 2, 3);
assertFalse(gator.isSatisfiable(new VecInt(new int[] { -1, -2, 3 })));
} |
["('/**\\\\n * translate <code>y <=> (x1 => x2)</code>\\\\n * \\\\n * @param y\\\\n * @param x1\\\\n * the selector variable\\\\n * @param x2\\\\n * @return\\\\n * @throws ContradictionException\\\\n * @since 2.3.6\\\\n */', '')", "('', '// y <=> (x1 -> x2)\\n')", "('', '// y -> (x1 -> x2)\\n')", "('', '// y <- (x1 -> x2)\\n')", "('', '// not(x1 -> x2) or y\\n')", "('', '// x1 and not x2 or y\\n')", "('', '// (x1 or y) and (not x2 or y)\\n')"] | b'/**\n * translate <code>y <=> (x1 => x2)</code>\n * \n * @param y\n * @param x1\n * the selector variable\n * @param x2\n * @return\n * @throws ContradictionException\n * @since 2.3.6\n */'public IConstr[] it(int y, int x1, int x2) throws ContradictionException {
IConstr[] constrs = new IConstr[3];
IVecInt clause = new VecInt(5);
// y <=> (x1 -> x2)
// y -> (x1 -> x2)
clause.push(-y).push(-x1).push(x2);
constrs[0] = processClause(clause);
clause.clear();
// y <- (x1 -> x2)
// not(x1 -> x2) or y
// x1 and not x2 or y
// (x1 or y) and (not x2 or y)
clause.push(x1).push(y);
constrs[1] = processClause(clause);
clause.clear();
clause.push(-x2).push(y);
constrs[2] = processClause(clause);
return constrs;
} | @Test
public void testSATIfThen8() throws ContradictionException,
TimeoutException {
gator.it(1, 2, 3);
assertFalse(gator.isSatisfiable(new VecInt(new int[] { -1, -2, -3 })));
} |
Get the date of the first day of the current year @return date | b'/**\n * Get the date of the first day of the current year\n *\n * @return date\n */'public static Date yearStart() {
final GregorianCalendar calendar = new GregorianCalendar(US);
calendar.set(DAY_OF_YEAR, 1);
return calendar.getTime();
} | @Test
public void yearStart() {
Date date = DateUtils.yearStart();
assertNotNull(date);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
assertEquals(1, calendar.get(DAY_OF_YEAR));
} |
Get the date of the last day of the current year @return date | b'/**\n * Get the date of the last day of the current year\n *\n * @return date\n */'public static Date yearEnd() {
final GregorianCalendar calendar = new GregorianCalendar(US);
calendar.add(YEAR, 1);
calendar.set(DAY_OF_YEAR, 1);
calendar.add(DAY_OF_YEAR, -1);
return calendar.getTime();
} | @Test
public void yearEnd() {
Date date = DateUtils.yearEnd();
assertNotNull(date);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
assertEquals(11, calendar.get(MONTH));
assertEquals(31, calendar.get(DAY_OF_MONTH));
} |
["('/**\\\\n\\\\t * Returns true if the double is a denormal.\\\\n\\\\t */', '')"] | b'/**\n\t * Returns true if the double is a denormal.\n\t */'public static boolean isDenormal(@Unsigned long v) {
return (v & EXPONENT_MASK) == 0L;
} | @Test
public void double_IsDenormal() {
@Unsigned long min_double64 = 0x00000000_00000001L;
CHECK(Doubles.isDenormal(min_double64));
@Unsigned long bits = 0x000FFFFF_FFFFFFFFL;
CHECK(Doubles.isDenormal(bits));
bits = 0x00100000_00000000L;
CHECK(!Doubles.isDenormal(bits));
} |
["('/**\\\\n\\\\t * We consider denormals not to be special.\\\\n\\\\t * Hence only Infinity and NaN are special.\\\\n\\\\t */', '')"] | b'/**\n\t * We consider denormals not to be special.\n\t * Hence only Infinity and NaN are special.\n\t */'public static boolean isSpecial(@Unsigned long value) {
return (value & EXPONENT_MASK) == EXPONENT_MASK;
} | @Test
public void double_IsSpecial() {
CHECK(Doubles.isSpecial(Double.POSITIVE_INFINITY));
CHECK(Doubles.isSpecial(-Double.POSITIVE_INFINITY));
CHECK(Doubles.isSpecial(Double.NaN));
@Unsigned long bits = 0xFFF12345_00000000L;
CHECK(Doubles.isSpecial(bits));
// Denormals are not special:
CHECK(!Doubles.isSpecial(5e-324));
CHECK(!Doubles.isSpecial(-5e-324));
// And some random numbers:
CHECK(!Doubles.isSpecial(0.0));
CHECK(!Doubles.isSpecial(-0.0));
CHECK(!Doubles.isSpecial(1.0));
CHECK(!Doubles.isSpecial(-1.0));
CHECK(!Doubles.isSpecial(1000000.0));
CHECK(!Doubles.isSpecial(-1000000.0));
CHECK(!Doubles.isSpecial(1e23));
CHECK(!Doubles.isSpecial(-1e23));
CHECK(!Doubles.isSpecial(1.7976931348623157e308));
CHECK(!Doubles.isSpecial(-1.7976931348623157e308));
} |
t Computes a decimal representation with a fixed number of digits after thet decimal point The last emitted digit is roundedt pt bExamplesbbrt codet toFixed312 1 31brt toFixed31415 3 3142brt toFixed123456789 4 12345679brt toFixed123 5 123000brt toFixed01 4 01000brt toFixed1e30 2 100000000000000001988462483865600brt toFixed01 30 0100000000000000005551115123126brt toFixed01 17 010000000000000001brt codet pt If coderequestedDigitscode equals 0 then the tail of the result depends ont the codeEMITTRAILINGDECIMALPOINTcode and codeEMITTRAILINGZEROAFTERPOINTcodet pt Examples for requestedDigits 0t let codeEMITTRAILINGDECIMALPOINTcode and codeEMITTRAILINGZEROAFTERPOINTcode bebrt tablet trtdfalse and false thentd td 12345 123 tdtrt trtd td 0678 1 tdtrt trtdtrue and false thentd td 12345 123 tdtrt trtd td 0678 1 tdtrt trtdtrue and true thentd td 12345 1230 tdtrt trtd td 0678 10 tdtrt tablet pt t @param requestedDigits the number of digits to the right of the decimal point the last emitted digit is roundedt @param formatOptionst @throws IllegalArgumentException if coderequestedDigits MAXFIXEDDIGITSBEFOREPOINTcode ort if codevalue 10MAXFIXEDDIGITSBEFOREPOINTcodet pt These two conditions imply that the result for nonspecial valuest never contains more thanbrt code1 MAXFIXEDDIGITSBEFOREPOINT 1 t MAXFIXEDDIGITSAFTERPOINTcodebrt characters one additional character for the sign and one for the decimal pointt DOUBLECONVERSIONASSERTMAXFIXEDDIGITSBEFOREPOINT 60 Find a sufficiently precise decimal representation of n | b'/**\n\t * Computes a decimal representation with a fixed number of digits after the\n\t * decimal point. The last emitted digit is rounded.\n\t * <p/>\n\t * <b>Examples:</b><br/>\n\t * <code>\n\t * toFixed(3.12, 1) -> "3.1"<br/>\n\t * toFixed(3.1415, 3) -> "3.142"<br/>\n\t * toFixed(1234.56789, 4) -> "1234.5679"<br/>\n\t * toFixed(1.23, 5) -> "1.23000"<br/>\n\t * toFixed(0.1, 4) -> "0.1000"<br/>\n\t * toFixed(1e30, 2) -> "1000000000000000019884624838656.00"<br/>\n\t * toFixed(0.1, 30) -> "0.100000000000000005551115123126"<br/>\n\t * toFixed(0.1, 17) -> "0.10000000000000001"<br/>\n\t * </code>\n\t * <p/>\n\t * If <code>requestedDigits</code> equals 0, then the tail of the result depends on\n\t * the <code>EMIT_TRAILING_DECIMAL_POINT</code> and <code>EMIT_TRAILING_ZERO_AFTER_POINT</code>.\n\t * <p/>\n\t * Examples, for requestedDigits == 0,\n\t * let <code>EMIT_TRAILING_DECIMAL_POINT</code> and <code>EMIT_TRAILING_ZERO_AFTER_POINT</code> be<br/>\n\t * <table>\n\t * <tr><td>false and false: then</td> <td> 123.45 -> 123 </td></tr>\n\t * <tr><td/> <td> 0.678 -> 1 </td></tr>\n\t * <tr><td>true and false: then</td> <td> 123.45 -> 123. </td></tr>\n\t * <tr><td/> <td> 0.678 -> 1. </td></tr>\n\t * <tr><td>true and true: then</td> <td> 123.45 -> 123.0 </td></tr>\n\t * <tr><td/> <td> 0.678 -> 1.0 </td></tr>\n\t * </table>\n\t * <p/>\n\t *\n\t * @param requestedDigits the number of digits to the right of the decimal point, the last emitted digit is rounded\n\t * @param formatOptions\n\t * @throws IllegalArgumentException if <code>requestedDigits > MAX_FIXED_DIGITS_BEFORE_POINT</code> or\n\t * if <code>value > 10^MAX_FIXED_DIGITS_BEFORE_POINT</code>\n\t * <p/>\n\t * These two conditions imply that the result for non-special values\n\t * never contains more than<br/>\n\t * <code>1 + MAX_FIXED_DIGITS_BEFORE_POINT + 1 +\n\t * MAX_FIXED_DIGITS_AFTER_POINT</code><br/>\n\t * characters (one additional character for the sign, and one for the decimal point).\n\t */'public static void toFixed(double value, int requestedDigits, FormatOptions formatOptions, CharBuffer resultBuilder) {
// DOUBLE_CONVERSION_ASSERT(MAX_FIXED_DIGITS_BEFORE_POINT == 60);
if (Doubles.isSpecial(value)) {
handleSpecialValues(value, formatOptions, resultBuilder);
return;
}
if (requestedDigits > MAX_FIXED_DIGITS_AFTER_POINT) {
throw new IllegalArgumentException("requestedDigits too large. max: " + MAX_FIXED_DIGITS_BEFORE_POINT +
"(MAX_FIXED_DIGITS_BEFORE_POINT) got: " + requestedDigits);
}
if (value > FIRST_NON_FIXED || value < -FIRST_NON_FIXED) {
throw new IllegalArgumentException("value >= 10^" + MAX_FIXED_DIGITS_BEFORE_POINT +
"(10^MAX_FIXED_DIGITS_BEFORE_POINT) got: " + value);
}
// Find a sufficiently precise decimal representation of n.
DecimalRepBuf decimalRep = new DecimalRepBuf(FIXED_REP_CAPACITY);
doubleToAscii(value, DtoaMode.FIXED, requestedDigits, decimalRep);
createDecimalRepresentation(decimalRep, value, requestedDigits, formatOptions, resultBuilder);
} | @Test
void toFixed() {
// TODO: conv = DoubleToStringConverter.ecmaScriptConverter();
testFixed("3.1", 3.12, 1);
testFixed("3.142", 3.1415, 3);
testFixed("1234.5679", 1234.56789, 4);
testFixed("1.23000", 1.23, 5);
testFixed("0.1000", 0.1, 4);
testFixed("1000000000000000019884624838656.00", 1e30, 2);
testFixed("0.100000000000000005551115123126", 0.1, 30);
testFixed("0.10000000000000001", 0.1, 17);
// TODO: conv = newConv(Flags.NO_FLAGS);
testFixed("123", 123.45, 0);
testFixed("1", 0.678, 0);
testFixed("123.", 123.45, 0, WITH_TRAILING);
testFixed("1.", 0.678, 0, WITH_TRAILING);
// from string-issues.lua:3
testFixed("20.00", 20.0, 2, padding(5, false, false)); // %5.2f
testFixed(" 0.05", 5.2e-2, 2, padding(5, false, false)); // %5.2f
testFixed("52.30", 52.3, 2, padding(5, false, false)); // %5.2f
// padding
testFixed(" 1.0", 1.0, 1, padding(9, false, false));
testFixed("1.0 ", 1.0, 1, padding(9, false, true));
testFixed("0000001.0", 1.0, 1, padding(9, true, false));
boolean zeroPad = true;
testFixed("1", 1.0, 0, padding(1, zeroPad, false));
testFixed("0", 0.1, 0, padding(1, zeroPad, false));
testFixed("01", 1.0, 0, padding(2, zeroPad, false));
testFixed("-1", -1.0, 0, padding(2, zeroPad, false));
testFixed("001", 1.0, 0, padding(3, zeroPad, false));
testFixed("-01", -1.0, 0, padding(3, zeroPad, false));
testFixed("123", 123.456, 0, padding(1, zeroPad, false));
testFixed("0", 1.23456e-05, 0, padding(1, zeroPad, false));
testFixed("100", 100.0, 0, padding(2, zeroPad, false));
testFixed("1000", 1000.0, 0, padding(2, zeroPad, false));
testFixed("000100", 100.0, 0, padding(6, zeroPad, false));
testFixed("001000", 1000.0, 0, padding(6, zeroPad, false));
testFixed("010000", 10000.0, 0, padding(6, zeroPad, false));
testFixed("100000", 100000.0, 0, padding(6, zeroPad, false));
testFixed("1000000", 1000000.0, 0, padding(6, zeroPad, false));
testFixed("00", 0.01, 0, padding(2, zeroPad, false));
testFixed("0.0", 0.01, 1, padding(2, false, false));
testFixed(" 0.010000", 0.01, 6, padding(20, false, false));
} |
t Computes a representation in exponential format with coderequestedDigitscodet after the decimal point The last emitted digit is roundedt pt Examples with bEMITPOSITIVEEXPONENTSIGNb deactivated andt exponentcharacter set to codeecodet pt codet toExponential312 1 31e0brt toExponential50 3 5000e0brt toExponential0001 2 100e3brt toExponential31415 4 31415e0brt toExponential31415 3 3142e0brt toExponential123456789000000 3 1235e14brt toExponential10000000000000000198846248386560 32 t 100000000000000001988462483865600e30brt toExponential1234 0 1e3brt codet t @param requestedDigits number of digits after the decimal pointlast digit roundedt @param formatOptionst @throws IllegalArgumentException if coderequestedDigits MAXEXPONENTIALDIGITScodet DOUBLECONVERSIONASSERTEXPONENTIALREPCAPACITY BASE10MAXIMALLENGTH | b'/**\n\t * Computes a representation in exponential format with <code>requestedDigits</code>\n\t * after the decimal point. The last emitted digit is rounded.\n\t * <p/>\n\t * Examples with <b>EMIT_POSITIVE_EXPONENT_SIGN</b> deactivated, and\n\t * exponent_character set to <code>\'e\'</code>.\n\t * <p/>\n\t * <code>\n\t * toExponential(3.12, 1) -> "3.1e0"<br/>\n\t * toExponential(5.0, 3) -> "5.000e0"<br/>\n\t * toExponential(0.001, 2) -> "1.00e-3"<br/>\n\t * toExponential(3.1415, 4) -> "3.1415e0"<br/>\n\t * toExponential(3.1415, 3) -> "3.142e0"<br/>\n\t * toExponential(123456789000000, 3) -> "1.235e14"<br/>\n\t * toExponential(1000000000000000019884624838656.0, 32) ->\n\t * "1.00000000000000001988462483865600e30"<br/>\n\t * toExponential(1234, 0) -> "1e3"<br/>\n\t * </code>\n\t *\n\t * @param requestedDigits number of digits after the decimal point(last digit rounded)\n\t * @param formatOptions\n\t * @throws IllegalArgumentException if <code>requestedDigits > MAX_EXPONENTIAL_DIGITS</code>\n\t */'public static void toExponential(double value, int requestedDigits, FormatOptions formatOptions, CharBuffer resultBuilder) {
if (Doubles.isSpecial(value)) {
handleSpecialValues(value, formatOptions, resultBuilder);
return;
}
if (requestedDigits < 0) {
throw new IllegalArgumentException(String.format("requestedDigits must be >= 0. got: %d", requestedDigits));
}
if (requestedDigits > MAX_EXPONENTIAL_DIGITS) {
throw new IllegalArgumentException(String.format("requestedDigits must be less than %d. got: %d", MAX_EXPONENTIAL_DIGITS, requestedDigits));
}
// DOUBLE_CONVERSION_ASSERT(EXPONENTIAL_REP_CAPACITY > BASE_10_MAXIMAL_LENGTH);
DecimalRepBuf decimalRep = new DecimalRepBuf(EXPONENTIAL_REP_CAPACITY);
doubleToAscii(value, DtoaMode.PRECISION, requestedDigits + 1, decimalRep);
assert decimalRep.length() <= requestedDigits + 1;
decimalRep.zeroExtend(requestedDigits + 1);
int exponent = decimalRep.getPointPosition() - 1;
createExponentialRepresentation(decimalRep, value, decimalRep.length(), exponent, formatOptions, resultBuilder);
} | @Test
void toExponential() {
testExp("3.1e+00", 3.12, 1);
testExp("5.000e+00", 5.0, 3);
testExp("1.00e-03", 0.001, 2);
testExp("3.1415e+00", 3.1415, 4);
testExp("3.142e+00", 3.1415, 3);
testExp("1.235e+14", 123456789000000.0, 3);
testExp("1.00000000000000001988462483865600e+30", 1000000000000000019884624838656.0, 32);
testExp("1e+03", 1234, 0);
testExp("0.000000e+00", 0.0, 6);
testExp("1.000000e+00", 1.0, 6);
testExp("0.e+00", 0.0, 0, formatOptTrailingPoint());
testExp("1.e+00", 1.0, 0, formatOptTrailingPoint());
// padding
testExp("01e+02", 100, 0, padding(6, true, false));
testExp("-1e+02", -100, 0, padding(6, true, false));
testExp("01e+03", 1000, 0, padding(6, true, false));
testExp("001e+02", 100, 0, padding(7, true, false));
} |
t Computes precision leading digits of the given value and returns themt either in exponential or decimal format depending ont PrecisionPolicymaxLeadingTrailingZeros given to thet constructort pt The last computed digit is roundedt pt Example with PrecisionPolicymaxLeadingZeros 6t pt codet toPrecision00000012345 2 00000012brt toPrecision000000012345 2 12e7brt codet pt Similarily the converter may add up tot PrecisionPolicymaxTrailingZeros in precision mode to avoidt returning an exponential representation A zero added by thet bEMITTRAILINGZEROAFTERPOINTb flag is counted for this limitt pt Examples for PrecisionPolicymaxTrailingZeros 1t pt codet toPrecision2300 2 230brt toPrecision2300 2 230 with EMITTRAILINGDECIMALPOINTbrt toPrecision2300 2 23e2 with EMITTRAILINGZEROAFTERPOINTbrt codet pt Examples for PrecisionPolicymaxTrailingZeros 3 and not EMITTRAILINGZEROAFTERPOINTt pt codet toPrecision1234500 6 123450brt toPrecision1234500 5 123450brt toPrecision1234500 4 123500brt toPrecision1234500 3 123000brt toPrecision1234500 2 12e5brt codet pt t @throws IllegalArgumentException when codeprecision MINPRECISIONDIGITScode ort codeprecision MAXPRECISIONDIGITScodet Find a sufficiently precise decimal representation of n Add one for the terminating null character The exponent if we print the number as xxxeyyy That is with the decimal point after the first digit Truncate trailing zeros that occur after the decimal point if exponential that is everything after the first digit Clamp precision to avoid the code below readding the zeros Fill buffer to contain precision digits Usually the buffer is already at the correct length but doubleToAscii is allowed to return less characters | b'/**\n\t * Computes \'precision\' leading digits of the given \'value\' and returns them\n\t * either in exponential or decimal format, depending on\n\t * PrecisionPolicy.max{Leading|Trailing}Zeros (given to the\n\t * constructor).\n\t * <p/>\n\t * The last computed digit is rounded.\n\t * </p>\n\t * Example with PrecisionPolicy.maxLeadingZeros = 6.\n\t * <p/>\n\t * <code>\n\t * toPrecision(0.0000012345, 2) -> "0.0000012"<br/>\n\t * toPrecision(0.00000012345, 2) -> "1.2e-7"<br/>\n\t * </code>\n\t * <p/>\n\t * Similarily the converter may add up to\n\t * PrecisionPolicy.maxTrailingZeros in precision mode to avoid\n\t * returning an exponential representation. A zero added by the\n\t * <b>EMIT_TRAILING_ZERO_AFTER_POINT</b> flag is counted for this limit.\n\t * <p/>\n\t * Examples for PrecisionPolicy.maxTrailingZeros = 1:\n\t * </p>\n\t * <code>\n\t * toPrecision(230.0, 2) -> "230"<br/>\n\t * toPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.<br/>\n\t * toPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.<br/>\n\t * </code>\n\t * <p/>\n\t * Examples for PrecisionPolicy.maxTrailingZeros = 3, and no\n\t * EMIT_TRAILING_ZERO_AFTER_POINT:\n\t * </p>\n\t * <code>\n\t * toPrecision(123450.0, 6) -> "123450"<br/>\n\t * toPrecision(123450.0, 5) -> "123450"<br/>\n\t * toPrecision(123450.0, 4) -> "123500"<br/>\n\t * toPrecision(123450.0, 3) -> "123000"<br/>\n\t * toPrecision(123450.0, 2) -> "1.2e5"<br/>\n\t * </code>\n\t * <p/>\n\t *\n\t * @throws IllegalArgumentException when <code>precision < MIN_PRECISION_DIGITS</code> or\n\t * <code>precision > MAX_PRECISION_DIGITS</code>\n\t */'public static void toPrecision(double value, int precision, FormatOptions formatOptions, CharBuffer resultBuilder) {
if (Doubles.isSpecial(value)) {
handleSpecialValues(value, formatOptions, resultBuilder);
return;
}
if (precision < MIN_PRECISION_DIGITS || precision > MAX_PRECISION_DIGITS) {
throw new IllegalArgumentException(String.format("argument precision must be in range (%d,%d)", MIN_PRECISION_DIGITS, MAX_PRECISION_DIGITS));
}
// Find a sufficiently precise decimal representation of n.
// Add one for the terminating null character.
DecimalRepBuf decimalRep = new DecimalRepBuf(PRECISION_REP_CAPACITY);
doubleToAscii(value, DtoaMode.PRECISION, precision, decimalRep);
assert decimalRep.length() <= precision;
// The exponent if we print the number as x.xxeyyy. That is with the
// decimal point after the first digit.
int decimalPoint = decimalRep.getPointPosition();
int exponent = decimalPoint - 1;
boolean asExponential = (-decimalPoint + 1 > MAX_LEADING_ZEROS) || (decimalPoint - precision > MAX_TRAILING_ZEROS);
if (!formatOptions.alternateForm()) {
// Truncate trailing zeros that occur after the decimal point (if exponential,
// that is everything after the first digit).
decimalRep.truncateZeros(asExponential);
// Clamp precision to avoid the code below re-adding the zeros.
precision = Math.min(precision, decimalRep.length());
}
if (asExponential) {
// Fill buffer to contain 'precision' digits.
// Usually the buffer is already at the correct length, but 'doubleToAscii'
// is allowed to return less characters.
decimalRep.zeroExtend(precision);
createExponentialRepresentation(decimalRep, value, precision, exponent, formatOptions, resultBuilder);
} else {
createDecimalRepresentation(decimalRep, value, Math.max(0, precision - decimalRep.getPointPosition()), formatOptions, resultBuilder);
}
} | @Test
void toPrecision() {
testPrec("0.00012", 0.00012345, 2);
testPrec("1.2e-05", 0.000012345, 2);
testPrec("2", 2.0, 2, DEFAULT);
testPrec("2.0", 2.0, 2, WITH_TRAILING);
// maxTrailingZeros = 3;
testPrec("123450", 123450.0, 6);
testPrec("1.2345e+05", 123450.0, 5);
testPrec("1.235e+05", 123450.0, 4);
testPrec("1.23e+05", 123450.0, 3);
testPrec("1.2e+05", 123450.0, 2);
testPrec("32300", 32.3 * 1000.0, 14);
int precision = 6;
testPrec(" 100000", 100000.0, precision, padding(20, false, false));
testPrec(" 1e+06", 1000000.0, precision, padding(20, false, false));
testPrec(" 1e+07", 10000000.0, precision, padding(20, false, false));
FormatOptions fo = new FormatOptions(SYMBOLS, true, false, true, 20, false, false);
testPrec(" +0.00000", 0.0, precision, fo);
testPrec(" +1.00000", 1.0, precision, fo);
testPrec(" -1.00000", -1.0, precision, fo);
} |
t Computes a representation in hexadecimal exponential format with coderequestedDigitscode after the decimalt point The last emitted digit is roundedt t @param value The value to formatt @param requestedDigits The number of digits after the decimal place or @code 1t @param formatOptions Additional options for this numbers formattingt @param resultBuilder The buffer to output tot | b"/**\n\t * Computes a representation in hexadecimal exponential format with <code>requestedDigits</code> after the decimal\n\t * point. The last emitted digit is rounded.\n\t *\n\t * @param value The value to format.\n\t * @param requestedDigits The number of digits after the decimal place, or {@code -1}.\n\t * @param formatOptions Additional options for this number's formatting.\n\t * @param resultBuilder The buffer to output to.\n\t */"public static void toHex(double value, int requestedDigits, FormatOptions formatOptions, CharBuffer resultBuilder) {
if (Doubles.isSpecial(value)) {
handleSpecialValues(value, formatOptions, resultBuilder);
return;
}
boolean negative = shouldEmitMinus(value);
double absValue = Math.abs(value);
ExponentPart significand = createHexSignificand(absValue, requestedDigits, formatOptions);
int exponentValue = absValue == 0 ? 0 : Doubles.exponent(absValue) + Doubles.PHYSICAL_SIGNIFICAND_SIZE;
ExponentPart exponent = createExponentPart(exponentValue, 1);
int valueWidth = significand.length() + exponent.length() + 3;
if (negative || formatOptions.explicitPlus() || formatOptions.spaceWhenPositive()) valueWidth++;
int padWidth = formatOptions.width() <= 0 ? 0 : formatOptions.width() - valueWidth;
if (padWidth > 0 && !formatOptions.leftAdjust() && !formatOptions.zeroPad()) {
addPadding(resultBuilder, ' ', padWidth);
}
appendSign(value, formatOptions, resultBuilder);
resultBuilder.append('0');
resultBuilder.append(formatOptions.symbols().hexSeparator());
if (padWidth > 0 && !formatOptions.leftAdjust() && formatOptions.zeroPad()) {
addPadding(resultBuilder, '0', padWidth);
}
resultBuilder.append(significand.buffer(), significand.start(), significand.length());
resultBuilder.append(formatOptions.symbols().hexExponent());
resultBuilder.append(exponent.buffer(), exponent.start(), exponent.length());
if (padWidth > 0 && formatOptions.leftAdjust()) addPadding(resultBuilder, ' ', padWidth);
} | @Test
void toHex() {
testHex("0x0p+0", 0.0, -1, DEFAULT);
testHex("0x1p+0", 1.0, -1, DEFAULT);
testHex("0x1.8p+1", 3.0, -1, DEFAULT);
testHex("0x1.8ae147ae147aep+3", 12.34, -1, DEFAULT);
testHex("0x2p+3", 12.34, 0, DEFAULT);
testHex("0x1.0ap+1", 0x1.0ap+1, -1, DEFAULT);
} |
["('/**\\\\n\\\\t * Provides a decimal representation of v.\\\\n\\\\t * The result should be interpreted as buffer * 10^(point - outLength).\\\\n\\\\t * <p>\\\\n\\\\t * Precondition:\\\\n\\\\t * * v must be a strictly positive finite double.\\\\n\\\\t * <p>\\\\n\\\\t * Returns true if it succeeds, otherwise the result can not be trusted.\\\\n\\\\t * If the function returns true and mode equals\\\\n\\\\t * - FAST_DTOA_PRECISION, then\\\\n\\\\t * the buffer contains requestedDigits digits.\\\\n\\\\t * the difference v - (buffer * 10^(point-outLength)) is closest to zero for\\\\n\\\\t * all possible representations of requestedDigits digits.\\\\n\\\\t * If there are two values that are equally close, then fastDtoa returns\\\\n\\\\t * false.\\\\n\\\\t * For both modes the buffer must be large enough to hold the result.\\\\n\\\\t */', '')", "('', '// initialized to 0\\n')"] | b'/**\n\t * Provides a decimal representation of v.\n\t * The result should be interpreted as buffer * 10^(point - outLength).\n\t * <p>\n\t * Precondition:\n\t * * v must be a strictly positive finite double.\n\t * <p>\n\t * Returns true if it succeeds, otherwise the result can not be trusted.\n\t * If the function returns true and mode equals\n\t * - FAST_DTOA_PRECISION, then\n\t * the buffer contains requestedDigits digits.\n\t * the difference v - (buffer * 10^(point-outLength)) is closest to zero for\n\t * all possible representations of requestedDigits digits.\n\t * If there are two values that are equally close, then fastDtoa returns\n\t * false.\n\t * For both modes the buffer must be large enough to hold the result.\n\t */'public static boolean fastDtoa(double v, int requestedDigits, DecimalRepBuf buf) {
assert v > 0.0;
assert !Doubles.isSpecial(v);
boolean result;
int[] decimalExponent = new int[1]; // initialized to 0
result = grisu3Counted(v, requestedDigits, buf, decimalExponent);
if (result) {
buf.setPointPosition(buf.length() + decimalExponent[0]);
} else {
buf.reset();
}
return result;
} | @Test
public void precisionVariousDoubles() {
DecimalRepBuf buffer = new DecimalRepBuf(BUFFER_SIZE);
boolean status;
status = FastDtoa.fastDtoa(1.0, 3, buffer);
CHECK(status);
CHECK_GE(3, buffer.length());
buffer.truncateAllZeros();
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
status = FastDtoa.fastDtoa(1.5, 10, buffer);
if (status) {
CHECK_GE(10, buffer.length());
buffer.truncateAllZeros();
CHECK_EQ("15", buffer);
CHECK_EQ(1, buffer.getPointPosition());
}
double min_double = 5e-324;
status = FastDtoa.fastDtoa(min_double, 5,
buffer);
CHECK(status);
CHECK_EQ("49407", buffer);
CHECK_EQ(-323, buffer.getPointPosition());
double max_double = 1.7976931348623157e308;
status = FastDtoa.fastDtoa(max_double, 7,
buffer);
CHECK(status);
CHECK_EQ("1797693", buffer);
CHECK_EQ(309, buffer.getPointPosition());
status = FastDtoa.fastDtoa(4294967272.0, 14,
buffer);
if (status) {
CHECK_GE(14, buffer.length());
buffer.truncateAllZeros();
CHECK_EQ("4294967272", buffer);
CHECK_EQ(10, buffer.getPointPosition());
}
status = FastDtoa.fastDtoa(4.1855804968213567e298, 17,
buffer);
CHECK(status);
CHECK_EQ("41855804968213567", buffer);
CHECK_EQ(299, buffer.getPointPosition());
status = FastDtoa.fastDtoa(5.5626846462680035e-309, 1,
buffer);
CHECK(status);
CHECK_EQ("6", buffer);
CHECK_EQ(-308, buffer.getPointPosition());
status = FastDtoa.fastDtoa(2147483648.0, 5,
buffer);
CHECK(status);
CHECK_EQ("21475", buffer);
CHECK_EQ(10, buffer.getPointPosition());
status = FastDtoa.fastDtoa(3.5844466002796428e+298, 10,
buffer);
CHECK(status);
CHECK_GE(10, buffer.length());
buffer.truncateAllZeros();
CHECK_EQ("35844466", buffer);
CHECK_EQ(299, buffer.getPointPosition());
long smallest_normal64 = 0x00100000_00000000L;
double v = Double.longBitsToDouble(smallest_normal64);
status = FastDtoa.fastDtoa(v, 17, buffer);
CHECK(status);
CHECK_EQ("22250738585072014", buffer);
CHECK_EQ(-307, buffer.getPointPosition());
long largest_denormal64 = 0x000FFFFF_FFFFFFFFL;
v = Double.longBitsToDouble(largest_denormal64);
status = FastDtoa.fastDtoa(v, 17, buffer);
CHECK(status);
CHECK_GE(20, buffer.length());
buffer.truncateAllZeros();
CHECK_EQ("22250738585072009", buffer);
CHECK_EQ(-307, buffer.getPointPosition());
v = 3.3161339052167390562200598e-237;
status = FastDtoa.fastDtoa(v, 18, buffer);
CHECK(status);
CHECK_EQ("331613390521673906", buffer);
CHECK_EQ(-236, buffer.getPointPosition());
v = 7.9885183916008099497815232e+191;
status = FastDtoa.fastDtoa(v, 4, buffer);
CHECK(status);
CHECK_EQ("7989", buffer);
CHECK_EQ(192, buffer.getPointPosition());
} |
["('/**\\\\n\\\\t * Provides a decimal representation of v.\\\\n\\\\t * The result should be interpreted as buffer * 10^(point - outLength).\\\\n\\\\t * <p>\\\\n\\\\t * Precondition:\\\\n\\\\t * * v must be a strictly positive finite double.\\\\n\\\\t * <p>\\\\n\\\\t * Returns true if it succeeds, otherwise the result can not be trusted.\\\\n\\\\t * If the function returns true and mode equals\\\\n\\\\t * - FAST_DTOA_PRECISION, then\\\\n\\\\t * the buffer contains requestedDigits digits.\\\\n\\\\t * the difference v - (buffer * 10^(point-outLength)) is closest to zero for\\\\n\\\\t * all possible representations of requestedDigits digits.\\\\n\\\\t * If there are two values that are equally close, then fastDtoa returns\\\\n\\\\t * false.\\\\n\\\\t * For both modes the buffer must be large enough to hold the result.\\\\n\\\\t */', '')", "('', '// initialized to 0\\n')"] | b'/**\n\t * Provides a decimal representation of v.\n\t * The result should be interpreted as buffer * 10^(point - outLength).\n\t * <p>\n\t * Precondition:\n\t * * v must be a strictly positive finite double.\n\t * <p>\n\t * Returns true if it succeeds, otherwise the result can not be trusted.\n\t * If the function returns true and mode equals\n\t * - FAST_DTOA_PRECISION, then\n\t * the buffer contains requestedDigits digits.\n\t * the difference v - (buffer * 10^(point-outLength)) is closest to zero for\n\t * all possible representations of requestedDigits digits.\n\t * If there are two values that are equally close, then fastDtoa returns\n\t * false.\n\t * For both modes the buffer must be large enough to hold the result.\n\t */'public static boolean fastDtoa(double v, int requestedDigits, DecimalRepBuf buf) {
assert v > 0.0;
assert !Doubles.isSpecial(v);
boolean result;
int[] decimalExponent = new int[1]; // initialized to 0
result = grisu3Counted(v, requestedDigits, buf, decimalExponent);
if (result) {
buf.setPointPosition(buf.length() + decimalExponent[0]);
} else {
buf.reset();
}
return result;
} | @Test
public void gayPrecision() throws Exception {
PrecisionState state = new PrecisionState();
DoubleTestHelper.eachPrecision(state, (st, v, numberDigits, representation, decimalPoint) -> {
boolean status;
st.total++;
st.underTest = String.format("Using {%g, %d, \"%s\", %d}", v, numberDigits, representation, decimalPoint);
if (numberDigits <= 15) st.total15++;
status = FastDtoa.fastDtoa(v, numberDigits, st.buffer);
CHECK_GE(numberDigits, st.buffer.length());
if (status) {
st.succeeded++;
if (numberDigits <= 15) st.succeeded15++;
st.buffer.truncateAllZeros();
assertThat(st.underTest, st.buffer.getPointPosition(), is(equalTo(decimalPoint)));
assertThat(st.underTest, stringOf(st.buffer), is(equalTo(representation)));
}
});
// The precomputed numbers contain many entries with many requested
// digits. These have a high failure rate and we therefore expect a lower
// success rate than for the shortest representation.
assertThat("85% should succeed", state.succeeded * 1.0 / state.total, is(greaterThan(0.85)));
// However with less than 15 digits almost the algorithm should almost always
// succeed.
assertThat(state.succeeded15 * 1.0 / state.total15, is(greaterThan(0.9999)));
System.out.println("gay-precision tests run :" + Integer.toString(state.total));
} |
["('', '// v = significand * 2^exponent (with significand a 53bit integer).\\n')", "('', '// If the exponent is larger than 20 (i.e. we may have a 73bit number) then we\\n')", '(\'\', "// don\'t know how to compute the representation. 2^73 ~= 9.5*10^21.\\n")', '(\'\', "// If necessary this limit could probably be increased, but we don\'t need\\n")', "('', '// more.\\n')", "('', '// At most DOUBLE_SIGNIFICAND_SIZE bits of the significand are non-zero.\\n')", "('', '// Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero\\n')", "('', '// bits: 0..11*..0xxx..53*..xx\\n')", "('', '// compile-time promise that exponent is positive\\n')", "('', '// The exponent must be > 11.\\n')", "('', '//\\n')", "('', '// We know that v = significand * 2^exponent.\\n')", "('', '// And the exponent > 11.\\n')", "('', '// We simplify the task by dividing v by 10^17.\\n')", "('', '// The quotient delivers the first digits, and the remainder fits into a 64\\n')", "('', '// bit number.\\n')", "('', '// Dividing by 10^17 is equivalent to dividing by 5^17*2^17.\\n')", "('', '// 5^17\\n')", "('', '// Let v = f * 2^e with f == significand and e == exponent.\\n')", "('', '// Then need q (quotient) and r (remainder) as follows:\\n')", "('', '// v = q * 10^17 + r\\n')", "('', '// f * 2^e = q * 10^17 + r\\n')", "('', '// f * 2^e = q * 5^17 * 2^17 + r\\n')", "('', '// If e > 17 then\\n')", "('', '// f * 2^(e-17) = q * 5^17 + r/2^17\\n')", "('', '// else\\n')", "('', '// f = q * 5^17 * 2^(17-e) + r/2^e\\n')", "('', '// We only allow exponents of up to 20 and therefore (17 - e) <= 3\\n')", "('', '// 0 <= exponent <= 11\\n')", "('', '// We have to cut the number.\\n')", "('', '// This configuration (with at most 20 digits) means that all digits must be\\n')", "('', '// 0.\\n')", "('', '// The string is empty and the decimalPoint thus has no importance. Mimick\\n')", '(\'\', "// Gay\'s dtoa and and set it to -fractionalCount.\\n")'] | public static boolean fastFixedDtoa(double v, int fractionalCount, DecimalRepBuf buf) {
final @Unsigned long kMaxUInt32 = 0xFFFF_FFFFL;
@Unsigned long significand = Doubles.significand(v);
int exponent = Doubles.exponent(v);
// v = significand * 2^exponent (with significand a 53bit integer).
// If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
// don't know how to compute the representation. 2^73 ~= 9.5*10^21.
// If necessary this limit could probably be increased, but we don't need
// more.
if (exponent > 20) return false;
if (fractionalCount > 20) return false;
buf.clearBuf();
// At most DOUBLE_SIGNIFICAND_SIZE bits of the significand are non-zero.
// Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
// bits: 0..11*..0xxx..53*..xx
if (exponent + DOUBLE_SIGNIFICAND_SIZE > 64) {
// compile-time promise that exponent is positive
@SuppressWarnings("cast.unsafe")
@SignedPositive int positiveExponent = (@SignedPositive int) exponent;
// The exponent must be > 11.
//
// We know that v = significand * 2^exponent.
// And the exponent > 11.
// We simplify the task by dividing v by 10^17.
// The quotient delivers the first digits, and the remainder fits into a 64
// bit number.
// Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
final @Unsigned long kFive17 = 0xB1_A2BC2EC5L; // 5^17
@Unsigned long divisor = kFive17;
@SignedPositive int divisorPower = 17;
@Unsigned long dividend = significand;
@Unsigned int quotient;
@Unsigned long remainder;
// Let v = f * 2^e with f == significand and e == exponent.
// Then need q (quotient) and r (remainder) as follows:
// v = q * 10^17 + r
// f * 2^e = q * 10^17 + r
// f * 2^e = q * 5^17 * 2^17 + r
// If e > 17 then
// f * 2^(e-17) = q * 5^17 + r/2^17
// else
// f = q * 5^17 * 2^(17-e) + r/2^e
if (exponent > divisorPower) {
// We only allow exponents of up to 20 and therefore (17 - e) <= 3
dividend <<= toUlongFromSigned(positiveExponent - divisorPower);
quotient = toUint(uDivide(dividend, divisor));
remainder = uRemainder(dividend, divisor) << divisorPower;
} else {
divisor <<= toUlongFromSigned(divisorPower - positiveExponent);
quotient = toUint(uDivide(dividend, divisor));
remainder = uRemainder(dividend, divisor) << exponent;
}
fillDigits32(quotient, buf);
fillDigits64FixedLength(remainder, buf);
buf.setPointPosition(buf.length());
} else if (exponent >= 0) {
// 0 <= exponent <= 11
significand = significand << exponent;
fillDigits64(significand, buf);
buf.setPointPosition(buf.length());
} else if (exponent > -DOUBLE_SIGNIFICAND_SIZE) {
// We have to cut the number.
@Unsigned long integrals = significand >>> -exponent;
@Unsigned long fractionals = significand - (integrals << -exponent);
if (!isAssignableToUint(integrals)) {
fillDigits64(integrals, buf);
} else {
fillDigits32(toUint(integrals), buf);
}
buf.setPointPosition(buf.length());
fillFractionals(fractionals, exponent, fractionalCount, buf);
} else if (exponent < -128) {
// This configuration (with at most 20 digits) means that all digits must be
// 0.
assert fractionalCount <= 20;
buf.clearBuf();
buf.setPointPosition(-fractionalCount);
} else {
buf.setPointPosition(0);
fillFractionals(significand, exponent, fractionalCount, buf);
}
buf.trimZeros();
if (buf.length() == 0) {
// The string is empty and the decimalPoint thus has no importance. Mimick
// Gay's dtoa and and set it to -fractionalCount.
buf.setPointPosition(-fractionalCount);
}
return true;
} | @Test
public void variousDoubles() {
DecimalRepBuf buffer = new DecimalRepBuf(kBufferSize);
CHECK(FixedDtoa.fastFixedDtoa(1.0, 1, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1.0, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1.0, 0, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
// FIXME Doesn't seem to convert in java
// CHECK(FixedDtoa.fastFixedDtoa(0xFFFFFFFF, 5, buffer));
// CHECK_EQ("4294967295", buffer);
// CHECK_EQ(10, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(4294967296.0, 5, buffer));
CHECK_EQ("4294967296", buffer);
CHECK_EQ(10, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1e21, 5, buffer));
CHECK_EQ("1", buffer);
// CHECK_EQ(22, buffer.getPointPosition());
CHECK_EQ(22, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(999999999999999868928.00, 2, buffer));
CHECK_EQ("999999999999999868928", buffer);
CHECK_EQ(21, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(6.9999999999999989514240000e+21, 5, buffer));
CHECK_EQ("6999999999999998951424", buffer);
CHECK_EQ(22, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1.5, 5, buffer));
CHECK_EQ("15", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1.55, 5, buffer));
CHECK_EQ("155", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1.55, 1, buffer));
CHECK_EQ("16", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1.00000001, 15, buffer));
CHECK_EQ("100000001", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.1, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(0, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.01, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.001, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-2, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0001, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-3, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00001, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-4, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000001, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-5, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000001, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-6, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000001, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-7, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000001, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-8, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000001, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-9, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000000001, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-10, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000001, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-11, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000001, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-12, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000000000001, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-13, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000001, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-14, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000000001, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-15, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000000000000001, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-16, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000001, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-17, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000000000001, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-18, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000000000000000001, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-19, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.10000000004, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(0, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.01000000004, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00100000004, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-2, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00010000004, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-3, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00001000004, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-4, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000100004, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-5, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000010004, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-6, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000001004, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-7, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000000104, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-8, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000001000004, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-9, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000100004, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-10, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000010004, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-11, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000001004, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-12, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000000104, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-13, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000001000004, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-14, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000100004, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-15, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000010004, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-16, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000001004, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-17, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000000104, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-18, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000000014, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-19, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.10000000006, 10, buffer));
CHECK_EQ("1000000001", buffer);
CHECK_EQ(0, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.01000000006, 10, buffer));
CHECK_EQ("100000001", buffer);
CHECK_EQ(-1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00100000006, 10, buffer));
CHECK_EQ("10000001", buffer);
CHECK_EQ(-2, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00010000006, 10, buffer));
CHECK_EQ("1000001", buffer);
CHECK_EQ(-3, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00001000006, 10, buffer));
CHECK_EQ("100001", buffer);
CHECK_EQ(-4, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000100006, 10, buffer));
CHECK_EQ("10001", buffer);
CHECK_EQ(-5, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000010006, 10, buffer));
CHECK_EQ("1001", buffer);
CHECK_EQ(-6, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000001006, 10, buffer));
CHECK_EQ("101", buffer);
CHECK_EQ(-7, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000000106, 10, buffer));
CHECK_EQ("11", buffer);
CHECK_EQ(-8, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000001000006, 15, buffer));
CHECK_EQ("100001", buffer);
CHECK_EQ(-9, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000100006, 15, buffer));
CHECK_EQ("10001", buffer);
CHECK_EQ(-10, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000010006, 15, buffer));
CHECK_EQ("1001", buffer);
CHECK_EQ(-11, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000001006, 15, buffer));
CHECK_EQ("101", buffer);
CHECK_EQ(-12, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000000000000106, 15, buffer));
CHECK_EQ("11", buffer);
CHECK_EQ(-13, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000001000006, 20, buffer));
CHECK_EQ("100001", buffer);
CHECK_EQ(-14, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000100006, 20, buffer));
CHECK_EQ("10001", buffer);
CHECK_EQ(-15, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000010006, 20, buffer));
CHECK_EQ("1001", buffer);
CHECK_EQ(-16, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000001006, 20, buffer));
CHECK_EQ("101", buffer);
CHECK_EQ(-17, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000000106, 20, buffer));
CHECK_EQ("11", buffer);
CHECK_EQ(-18, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000000000000000016, 20, buffer));
CHECK_EQ("2", buffer);
CHECK_EQ(-19, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.6, 0, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.96, 1, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.996, 2, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.9996, 3, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.99996, 4, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.999996, 5, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.9999996, 6, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.99999996, 7, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.999999996, 8, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.9999999996, 9, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.99999999996, 10, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.999999999996, 11, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.9999999999996, 12, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.99999999999996, 13, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.999999999999996, 14, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.9999999999999996, 15, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00999999999999996, 16, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000999999999999996, 17, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-2, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.0000999999999999996, 18, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-3, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.00000999999999999996, 19, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-4, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.000000999999999999996, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-5, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(323423.234234, 10, buffer));
CHECK_EQ("323423234234", buffer);
CHECK_EQ(6, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(12345678.901234, 4, buffer));
CHECK_EQ("123456789012", buffer);
CHECK_EQ(8, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(98765.432109, 5, buffer));
CHECK_EQ("9876543211", buffer);
CHECK_EQ(5, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(42, 20, buffer));
CHECK_EQ("42", buffer);
CHECK_EQ(2, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(0.5, 0, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(1, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1e-23, 10, buffer));
CHECK_EQ("", buffer);
CHECK_EQ(-10, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1e-123, 2, buffer));
CHECK_EQ("", buffer);
CHECK_EQ(-2, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1e-123, 0, buffer));
CHECK_EQ("", buffer);
CHECK_EQ(0, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1e-23, 20, buffer));
CHECK_EQ("", buffer);
CHECK_EQ(-20, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1e-21, 20, buffer));
CHECK_EQ("", buffer);
CHECK_EQ(-20, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1e-22, 20, buffer));
CHECK_EQ("", buffer);
CHECK_EQ(-20, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(6e-21, 20, buffer));
CHECK_EQ("1", buffer);
CHECK_EQ(-19, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(9.1193616301674545152000000e+19, 0,
buffer));
CHECK_EQ("91193616301674545152", buffer);
CHECK_EQ(20, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(4.8184662102767651659096515e-04, 19,
buffer));
CHECK_EQ("4818466210276765", buffer);
CHECK_EQ(-3, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1.9023164229540652612705182e-23, 8,
buffer));
CHECK_EQ("", buffer);
CHECK_EQ(-8, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(1000000000000000128.0, 0,
buffer));
CHECK_EQ("1000000000000000128", buffer);
CHECK_EQ(19, buffer.getPointPosition());
CHECK(FixedDtoa.fastFixedDtoa(2.10861548515811875e+15, 17, buffer));
CHECK_EQ("210861548515811875", buffer);
CHECK_EQ(16, buffer.getPointPosition());
} |
["('', '// v = significand * 2^exponent (with significand a 53bit integer).\\n')", "('', '// If the exponent is larger than 20 (i.e. we may have a 73bit number) then we\\n')", '(\'\', "// don\'t know how to compute the representation. 2^73 ~= 9.5*10^21.\\n")', '(\'\', "// If necessary this limit could probably be increased, but we don\'t need\\n")', "('', '// more.\\n')", "('', '// At most DOUBLE_SIGNIFICAND_SIZE bits of the significand are non-zero.\\n')", "('', '// Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero\\n')", "('', '// bits: 0..11*..0xxx..53*..xx\\n')", "('', '// compile-time promise that exponent is positive\\n')", "('', '// The exponent must be > 11.\\n')", "('', '//\\n')", "('', '// We know that v = significand * 2^exponent.\\n')", "('', '// And the exponent > 11.\\n')", "('', '// We simplify the task by dividing v by 10^17.\\n')", "('', '// The quotient delivers the first digits, and the remainder fits into a 64\\n')", "('', '// bit number.\\n')", "('', '// Dividing by 10^17 is equivalent to dividing by 5^17*2^17.\\n')", "('', '// 5^17\\n')", "('', '// Let v = f * 2^e with f == significand and e == exponent.\\n')", "('', '// Then need q (quotient) and r (remainder) as follows:\\n')", "('', '// v = q * 10^17 + r\\n')", "('', '// f * 2^e = q * 10^17 + r\\n')", "('', '// f * 2^e = q * 5^17 * 2^17 + r\\n')", "('', '// If e > 17 then\\n')", "('', '// f * 2^(e-17) = q * 5^17 + r/2^17\\n')", "('', '// else\\n')", "('', '// f = q * 5^17 * 2^(17-e) + r/2^e\\n')", "('', '// We only allow exponents of up to 20 and therefore (17 - e) <= 3\\n')", "('', '// 0 <= exponent <= 11\\n')", "('', '// We have to cut the number.\\n')", "('', '// This configuration (with at most 20 digits) means that all digits must be\\n')", "('', '// 0.\\n')", "('', '// The string is empty and the decimalPoint thus has no importance. Mimick\\n')", '(\'\', "// Gay\'s dtoa and and set it to -fractionalCount.\\n")'] | public static boolean fastFixedDtoa(double v, int fractionalCount, DecimalRepBuf buf) {
final @Unsigned long kMaxUInt32 = 0xFFFF_FFFFL;
@Unsigned long significand = Doubles.significand(v);
int exponent = Doubles.exponent(v);
// v = significand * 2^exponent (with significand a 53bit integer).
// If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
// don't know how to compute the representation. 2^73 ~= 9.5*10^21.
// If necessary this limit could probably be increased, but we don't need
// more.
if (exponent > 20) return false;
if (fractionalCount > 20) return false;
buf.clearBuf();
// At most DOUBLE_SIGNIFICAND_SIZE bits of the significand are non-zero.
// Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
// bits: 0..11*..0xxx..53*..xx
if (exponent + DOUBLE_SIGNIFICAND_SIZE > 64) {
// compile-time promise that exponent is positive
@SuppressWarnings("cast.unsafe")
@SignedPositive int positiveExponent = (@SignedPositive int) exponent;
// The exponent must be > 11.
//
// We know that v = significand * 2^exponent.
// And the exponent > 11.
// We simplify the task by dividing v by 10^17.
// The quotient delivers the first digits, and the remainder fits into a 64
// bit number.
// Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
final @Unsigned long kFive17 = 0xB1_A2BC2EC5L; // 5^17
@Unsigned long divisor = kFive17;
@SignedPositive int divisorPower = 17;
@Unsigned long dividend = significand;
@Unsigned int quotient;
@Unsigned long remainder;
// Let v = f * 2^e with f == significand and e == exponent.
// Then need q (quotient) and r (remainder) as follows:
// v = q * 10^17 + r
// f * 2^e = q * 10^17 + r
// f * 2^e = q * 5^17 * 2^17 + r
// If e > 17 then
// f * 2^(e-17) = q * 5^17 + r/2^17
// else
// f = q * 5^17 * 2^(17-e) + r/2^e
if (exponent > divisorPower) {
// We only allow exponents of up to 20 and therefore (17 - e) <= 3
dividend <<= toUlongFromSigned(positiveExponent - divisorPower);
quotient = toUint(uDivide(dividend, divisor));
remainder = uRemainder(dividend, divisor) << divisorPower;
} else {
divisor <<= toUlongFromSigned(divisorPower - positiveExponent);
quotient = toUint(uDivide(dividend, divisor));
remainder = uRemainder(dividend, divisor) << exponent;
}
fillDigits32(quotient, buf);
fillDigits64FixedLength(remainder, buf);
buf.setPointPosition(buf.length());
} else if (exponent >= 0) {
// 0 <= exponent <= 11
significand = significand << exponent;
fillDigits64(significand, buf);
buf.setPointPosition(buf.length());
} else if (exponent > -DOUBLE_SIGNIFICAND_SIZE) {
// We have to cut the number.
@Unsigned long integrals = significand >>> -exponent;
@Unsigned long fractionals = significand - (integrals << -exponent);
if (!isAssignableToUint(integrals)) {
fillDigits64(integrals, buf);
} else {
fillDigits32(toUint(integrals), buf);
}
buf.setPointPosition(buf.length());
fillFractionals(fractionals, exponent, fractionalCount, buf);
} else if (exponent < -128) {
// This configuration (with at most 20 digits) means that all digits must be
// 0.
assert fractionalCount <= 20;
buf.clearBuf();
buf.setPointPosition(-fractionalCount);
} else {
buf.setPointPosition(0);
fillFractionals(significand, exponent, fractionalCount, buf);
}
buf.trimZeros();
if (buf.length() == 0) {
// The string is empty and the decimalPoint thus has no importance. Mimick
// Gay's dtoa and and set it to -fractionalCount.
buf.setPointPosition(-fractionalCount);
}
return true;
} | @Test
public void gayFixed() throws Exception {
DtoaTest.DataTestState state = new DtoaTest.DataTestState();
DoubleTestHelper.eachFixed(state, (st, v, numberDigits, representation, decimalPoint) -> {
st.total++;
st.underTest = String.format("Using {%g, \"%s\", %d}", v, representation, decimalPoint);
boolean status = FixedDtoa.fastFixedDtoa(v, numberDigits, st.buffer);
assertThat(st.underTest, status, is(true));
assertThat(st.underTest, st.buffer.getPointPosition(), is(equalTo(decimalPoint)));
assertThat(st.underTest, st.buffer.getPointPosition(), is(equalTo(decimalPoint)));
assertThat(st.underTest, (st.buffer.length() - st.buffer.getPointPosition()), is(lessThanOrEqualTo(numberDigits)));
assertThat(st.underTest, stringOf(st.buffer), is(equalTo(representation)));
});
System.out.println("day-precision tests run :" + Integer.toString(state.total));
} |
values verified positive at beginning of method remainder quotient | @SuppressWarnings("return.type.incompatible") // values verified positive at beginning of method
@Unsigned int divideModuloIntBignum(Bignum other) {
requireState(val.signum() >= 0 && other.val.signum() >= 0, "values must be positive");
BigInteger[] rets = val.divideAndRemainder(other.val);
val = rets[1]; // remainder
return toUint(rets[0]); // quotient
} | @Test
public void divideModuloIntBignum() {
char[] buffer = new char[kBufferSize];
Bignum bignum = new Bignum();
Bignum other = new Bignum();
Bignum third = new Bignum();
bignum.assignUInt16((short) 10);
other.assignUInt16((short) 2);
CHECK_EQ(5, bignum.divideModuloIntBignum(other));
CHECK_EQ("0", bignum.toHexString());
bignum.assignUInt16((short) 10);
bignum.shiftLeft(500);
other.assignUInt16((short) 2);
other.shiftLeft(500);
CHECK_EQ(5, bignum.divideModuloIntBignum(other));
CHECK_EQ("0", bignum.toHexString());
bignum.assignUInt16((short) 11);
other.assignUInt16((short) 2);
CHECK_EQ(5, bignum.divideModuloIntBignum(other));
CHECK_EQ("1", bignum.toHexString());
bignum.assignUInt16((short) 10);
bignum.shiftLeft(500);
other.assignUInt16((short) 1);
bignum.addBignum(other);
other.assignUInt16((short) 2);
other.shiftLeft(500);
CHECK_EQ(5, bignum.divideModuloIntBignum(other));
CHECK_EQ("1", bignum.toHexString());
bignum.assignUInt16((short) 10);
bignum.shiftLeft(500);
other.assignBignum(bignum);
bignum.multiplyByUInt32(0x1234);
third.assignUInt16((short) 0xFFF);
bignum.addBignum(third);
CHECK_EQ(0x1234, bignum.divideModuloIntBignum(other));
CHECK_EQ("FFF", bignum.toHexString());
bignum.assignUInt16((short) 10);
assignHexString(other, "1234567890");
CHECK_EQ(0, bignum.divideModuloIntBignum(other));
CHECK_EQ("A", bignum.toHexString());
assignHexString(bignum, "12345678");
assignHexString(other, "3789012");
CHECK_EQ(5, bignum.divideModuloIntBignum(other));
CHECK_EQ("D9861E", bignum.toHexString());
assignHexString(bignum, "70000001");
assignHexString(other, "1FFFFFFF");
CHECK_EQ(3, bignum.divideModuloIntBignum(other));
CHECK_EQ("10000004", bignum.toHexString());
assignHexString(bignum, "28000000");
assignHexString(other, "12A05F20");
CHECK_EQ(2, bignum.divideModuloIntBignum(other));
CHECK_EQ("2BF41C0", bignum.toHexString());
bignum.assignUInt16((short) 10);
bignum.shiftLeft(500);
other.assignBignum(bignum);
bignum.multiplyByUInt32(0x1234);
third.assignUInt16((short) 0xFFF);
other.subtractBignum(third);
CHECK_EQ(0x1234, bignum.divideModuloIntBignum(other));
CHECK_EQ("1232DCC", bignum.toHexString());
CHECK_EQ(0, bignum.divideModuloIntBignum(other));
CHECK_EQ("1232DCC", bignum.toHexString());
} |
['("/**\\\\n * Creates Jetty\'s {@link ShutdownHandler}.\\\\n * \\\\n * @param environment the environment\\\\n * @return an instance of {@link ShutdownHandler} if\\\\n * {@link Environment#SERVER_SHUTDOWN_TOKEN_KEY} is\\\\n * available; otherwise <code>null</code>\\\\n */", \'\')'] | b"/**\n * Creates Jetty's {@link ShutdownHandler}.\n * \n * @param environment the environment\n * @return an instance of {@link ShutdownHandler} if\n * {@link Environment#SERVER_SHUTDOWN_TOKEN_KEY} is\n * available; otherwise <code>null</code>\n */"protected ShutdownHandler createShutdownHandler(Environment environment) {
String shutdownToken = environment.getServerShutdownToken();
if (shutdownToken == null || shutdownToken.isEmpty()) {
return null;
}
return new ShutdownHandler(shutdownToken, true, false);
} | @Test
public void createShutdownHandlerReturnsNullWithNoToken() throws Exception {
HandlerCollectionLoader hcl = new HandlerCollectionLoader();
ShutdownHandler shutdownHandler = hcl.createShutdownHandler(env);
assertThat(shutdownHandler).isNull();
} |
['("/**\\\\n * Creates Jetty\'s {@link ShutdownHandler}.\\\\n * \\\\n * @param environment the environment\\\\n * @return an instance of {@link ShutdownHandler} if\\\\n * {@link Environment#SERVER_SHUTDOWN_TOKEN_KEY} is\\\\n * available; otherwise <code>null</code>\\\\n */", \'\')'] | b"/**\n * Creates Jetty's {@link ShutdownHandler}.\n * \n * @param environment the environment\n * @return an instance of {@link ShutdownHandler} if\n * {@link Environment#SERVER_SHUTDOWN_TOKEN_KEY} is\n * available; otherwise <code>null</code>\n */"protected ShutdownHandler createShutdownHandler(Environment environment) {
String shutdownToken = environment.getServerShutdownToken();
if (shutdownToken == null || shutdownToken.isEmpty()) {
return null;
}
return new ShutdownHandler(shutdownToken, true, false);
} | @Test
public void createShutdownHandlerObserversShutdownTokenWhenPresent() throws Exception {
HandlerCollectionLoader hcl = new HandlerCollectionLoader();
String token = UUID.randomUUID().toString();
defaultEnv.put(Environment.SERVER_SHUTDOWN_TOKEN_KEY, token);
env = Environment.createEnvironment(defaultEnv);
ShutdownHandler shutdownHandler = hcl.createShutdownHandler(env);
assertThat(shutdownHandler).isNotNull();
assertThat(shutdownHandler.getShutdownToken()).isEqualTo(token);
} |
['("/*\\n\\t\\t\\t\\t * we don\'t know for sure why the thread was interrupted, so we\\n\\t\\t\\t\\t * need to obey; if interrupt was not relevant, the process will\\n\\t\\t\\t\\t * restart; we need to restore the interrupt status so that the\\n\\t\\t\\t\\t * called methods know that there was an interrupt\\n\\t\\t\\t\\t */", \'\')'] | @Override
public synchronized void load(ElkAxiomProcessor axiomInserter,
ElkAxiomProcessor axiomDeleter) throws ElkLoadingException {
if (finished_)
return;
if (!started_) {
parserThread_.start();
started_ = true;
}
ArrayList<ElkAxiom> nextBatch;
for (;;) {
if (isInterrupted())
break;
try {
nextBatch = axiomExchanger_.take();
} catch (InterruptedException e) {
/*
* we don't know for sure why the thread was interrupted, so we
* need to obey; if interrupt was not relevant, the process will
* restart; we need to restore the interrupt status so that the
* called methods know that there was an interrupt
*/
Thread.currentThread().interrupt();
break;
}
if (nextBatch == POISON_BATCH_) {
break;
}
for (int i = 0; i < nextBatch.size(); i++) {
ElkAxiom axiom = nextBatch.get(i);
axiomInserter.visit(axiom);
}
}
if (exception != null) {
throw exception;
}
} | @Test(expected = ElkLoadingException.class)
public void expectedLoadingExceptionOnSyntaxError()
throws ElkLoadingException {
String ontology = ""//
+ "Prefix( : = <http://example.org/> )"//
+ "Ontology((((()("//
+ "EquivalentClasses(:B :C)"//
+ "SubClassOf(:A ObjectSomeValuesFrom(:R :B))"//
+ "))";
load(ontology);
} |
['("/*\\n\\t\\t\\t\\t * we don\'t know for sure why the thread was interrupted, so we\\n\\t\\t\\t\\t * need to obey; if interrupt was not relevant, the process will\\n\\t\\t\\t\\t * restart; we need to restore the interrupt status so that the\\n\\t\\t\\t\\t * called methods know that there was an interrupt\\n\\t\\t\\t\\t */", \'\')'] | @Override
public synchronized void load(ElkAxiomProcessor axiomInserter,
ElkAxiomProcessor axiomDeleter) throws ElkLoadingException {
if (finished_)
return;
if (!started_) {
parserThread_.start();
started_ = true;
}
ArrayList<ElkAxiom> nextBatch;
for (;;) {
if (isInterrupted())
break;
try {
nextBatch = axiomExchanger_.take();
} catch (InterruptedException e) {
/*
* we don't know for sure why the thread was interrupted, so we
* need to obey; if interrupt was not relevant, the process will
* restart; we need to restore the interrupt status so that the
* called methods know that there was an interrupt
*/
Thread.currentThread().interrupt();
break;
}
if (nextBatch == POISON_BATCH_) {
break;
}
for (int i = 0; i < nextBatch.size(); i++) {
ElkAxiom axiom = nextBatch.get(i);
axiomInserter.visit(axiom);
}
}
if (exception != null) {
throw exception;
}
} | @Test(expected = ElkLoadingException.class)
public void expectedLoadingExceptionOnLexicalError() throws Exception {
String ontology = ""//
+ "Prefix( : = <http://example.org/> )"//
+ "Ontology-LEXICAL-ERROR("//
+ "EquivalentClasses(:B :C)"//
+ "SubClassOf(:A ObjectSomeValuesFrom(:R :B))"//
+ ")";
load(ontology);
} |
["('/**\\\\n\\\\t * @param prefix\\\\n\\\\t * the prefix of configuration options to be loaded\\\\n\\\\t * @param configClass\\\\n\\\\t * the class to be instantiated with the loaded options\\\\n\\\\t * @return the {@link BaseConfiguration} for the specified parameters\\\\n\\\\t * @throws ConfigurationException\\\\n\\\\t * if loading fails\\\\n\\\\t */', '')", '(\'\', "// try to find elk.properties. if doesn\'t exist, use the default\\n")', "('', '// parameter values for the given class\\n')", "('', '// copy parameters from the bundle\\n')"] | b'/**\n\t * @param prefix\n\t * the prefix of configuration options to be loaded\n\t * @param configClass\n\t * the class to be instantiated with the loaded options\n\t * @return the {@link BaseConfiguration} for the specified parameters\n\t * @throws ConfigurationException\n\t * if loading fails\n\t */'public BaseConfiguration getConfiguration(String prefix,
Class<? extends BaseConfiguration> configClass)
throws ConfigurationException {
// try to find elk.properties. if doesn't exist, use the default
// parameter values for the given class
ResourceBundle bundle = null;
BaseConfiguration config = instantiate(configClass);
try {
bundle = ResourceBundle.getBundle(STANDARD_RESOURCE_NAME,
Locale.getDefault(), configClass.getClassLoader());
} catch (MissingResourceException e) {
}
if (bundle == null) {
LOGGER_.debug("Loading default configuration parameters for "
+ configClass);
} else {
// copy parameters from the bundle
copyParameters(prefix, config, bundle);
}
copyParameters(prefix, config, System.getProperties());
return config;
} | @SuppressWarnings("static-method")
@Test
public void getDefaultConfiguration() {
BaseConfiguration defaultConfig = new ConfigurationFactory()
.getConfiguration("elk", BaseConfiguration.class);
assertEquals(3, defaultConfig.getParameterNames().size());
} |
["('/**\\\\n\\\\t * @param prefix\\\\n\\\\t * the prefix of configuration options to be loaded\\\\n\\\\t * @param configClass\\\\n\\\\t * the class to be instantiated with the loaded options\\\\n\\\\t * @return the {@link BaseConfiguration} for the specified parameters\\\\n\\\\t * @throws ConfigurationException\\\\n\\\\t * if loading fails\\\\n\\\\t */', '')", '(\'\', "// try to find elk.properties. if doesn\'t exist, use the default\\n")', "('', '// parameter values for the given class\\n')", "('', '// copy parameters from the bundle\\n')"] | b'/**\n\t * @param prefix\n\t * the prefix of configuration options to be loaded\n\t * @param configClass\n\t * the class to be instantiated with the loaded options\n\t * @return the {@link BaseConfiguration} for the specified parameters\n\t * @throws ConfigurationException\n\t * if loading fails\n\t */'public BaseConfiguration getConfiguration(String prefix,
Class<? extends BaseConfiguration> configClass)
throws ConfigurationException {
// try to find elk.properties. if doesn't exist, use the default
// parameter values for the given class
ResourceBundle bundle = null;
BaseConfiguration config = instantiate(configClass);
try {
bundle = ResourceBundle.getBundle(STANDARD_RESOURCE_NAME,
Locale.getDefault(), configClass.getClassLoader());
} catch (MissingResourceException e) {
}
if (bundle == null) {
LOGGER_.debug("Loading default configuration parameters for "
+ configClass);
} else {
// copy parameters from the bundle
copyParameters(prefix, config, bundle);
}
copyParameters(prefix, config, System.getProperties());
return config;
} | @SuppressWarnings("static-method")
@Test
public void getDefaultConfigurationWithPrefix() {
BaseConfiguration defaultConfig = new ConfigurationFactory()
.getConfiguration("elk.reasoner", BaseConfiguration.class);
assertEquals(2, defaultConfig.getParameterNames().size());
defaultConfig = new ConfigurationFactory().getConfiguration(
"elk.parser", BaseConfiguration.class);
assertEquals(1, defaultConfig.getParameterNames().size());
} |
["('/**\\\\n\\\\t * @param prefix\\\\n\\\\t * the prefix of configuration options to be loaded\\\\n\\\\t * @param configClass\\\\n\\\\t * the class to be instantiated with the loaded options\\\\n\\\\t * @return the {@link BaseConfiguration} for the specified parameters\\\\n\\\\t * @throws ConfigurationException\\\\n\\\\t * if loading fails\\\\n\\\\t */', '')", '(\'\', "// try to find elk.properties. if doesn\'t exist, use the default\\n")', "('', '// parameter values for the given class\\n')", "('', '// copy parameters from the bundle\\n')"] | b'/**\n\t * @param prefix\n\t * the prefix of configuration options to be loaded\n\t * @param configClass\n\t * the class to be instantiated with the loaded options\n\t * @return the {@link BaseConfiguration} for the specified parameters\n\t * @throws ConfigurationException\n\t * if loading fails\n\t */'public BaseConfiguration getConfiguration(String prefix,
Class<? extends BaseConfiguration> configClass)
throws ConfigurationException {
// try to find elk.properties. if doesn't exist, use the default
// parameter values for the given class
ResourceBundle bundle = null;
BaseConfiguration config = instantiate(configClass);
try {
bundle = ResourceBundle.getBundle(STANDARD_RESOURCE_NAME,
Locale.getDefault(), configClass.getClassLoader());
} catch (MissingResourceException e) {
}
if (bundle == null) {
LOGGER_.debug("Loading default configuration parameters for "
+ configClass);
} else {
// copy parameters from the bundle
copyParameters(prefix, config, bundle);
}
copyParameters(prefix, config, System.getProperties());
return config;
} | @Test
public void getConfigurationFromStream() throws ConfigurationException,
IOException {
InputStream stream = null;
try {
stream = this.getClass().getClassLoader()
.getResourceAsStream("elk.properties");
BaseConfiguration config = new ConfigurationFactory()
.getConfiguration(stream, "elk", BaseConfiguration.class);
assertEquals(3, config.getParameterNames().size());
} finally {
IOUtils.closeQuietly(stream);
}
} |
["('', '// Add a token for end of sentence\\n')"] | public String[] tokenize(String s) {
InputStream modelIn = null;
List<String> tokens = new ArrayList<String>();
try {
modelIn = new FileInputStream(sentenceModelFile);
SentenceModel model = new SentenceModel(modelIn);
SentenceDetector sentenceDetector = new SentenceDetectorME(model);
String sentences[] = sentenceDetector.sentDetect(s);
for (String sentence : sentences) {
List<String> toks =
Arrays.asList(tokenizeHelper(sentence));
tokens.addAll(toks);
// Add a token for end of sentence
tokens.add("<SENTENCE>");
}
}
catch (IOException e) {
System.out.println("Error with loading Sentence model...");
e.printStackTrace();
}
finally {
if (modelIn != null) {
try {
modelIn.close();
}
catch (IOException e) {
}
}
}
return tokens.toArray(new String[tokens.size()]);
} | @Test
public void testTokenization() {
String text = "This, is the first sentence. This: is the second sentence ";
String[] tokenizedText = tokenizer.tokenize(text);
System.out.println(Arrays.toString(tokenizedText));
} |
Creates a new codeFormattedEntityIdRowFiltercode instance The row key format must have an encoding of @link RowKeyEncodingFORMATTED and if there is a salt defined it must not be set to suppress key materialization If key materialization were suppressed then there would be no component fields to match against @param rowKeyFormat the row key format of the table this filter will be used on @param components the components to match on with @code nulls indicating a match on any value If fewer than the number of components defined in the row key format are supplied the rest will be filled in as @code null Fill in null for any components defined in the row key format that have not been passed in as components for the filter This effectively makes a prefix filter looking at only the components defined at the beginning of the EntityId | b'/**\n * Creates a new <code>FormattedEntityIdRowFilter</code> instance. The row key\n * format must have an encoding of {@link RowKeyEncoding#FORMATTED}, and if\n * there is a salt defined, it must not be set to suppress key\n * materialization. If key materialization were suppressed, then there would\n * be no component fields to match against.\n *\n * @param rowKeyFormat the row key format of the table this filter will be used on\n * @param components the components to match on, with {@code null}s indicating\n * a match on any value. If fewer than the number of components defined in\n * the row key format are supplied, the rest will be filled in as {@code\n * null}.\n */'public FormattedEntityIdRowFilter(RowKeyFormat2 rowKeyFormat, Object... components) {
Preconditions.checkNotNull(rowKeyFormat, "RowKeyFormat must be specified");
Preconditions.checkArgument(rowKeyFormat.getEncoding().equals(RowKeyEncoding.FORMATTED),
"FormattedEntityIdRowFilter only works with formatted entity IDs");
if (null != rowKeyFormat.getSalt()) {
Preconditions.checkArgument(!rowKeyFormat.getSalt().getSuppressKeyMaterialization(),
"FormattedEntityIdRowFilter only works with materialized keys");
}
Preconditions.checkNotNull(components, "At least one component must be specified");
Preconditions.checkArgument(components.length > 0, "At least one component must be specified");
Preconditions.checkArgument(components.length <= rowKeyFormat.getComponents().size(),
"More components given (%s) than are in the row key format specification (%s)",
components.length, rowKeyFormat.getComponents().size());
mRowKeyFormat = rowKeyFormat;
// Fill in 'null' for any components defined in the row key format that have
// not been passed in as components for the filter. This effectively makes
// a prefix filter, looking at only the components defined at the beginning
// of the EntityId.
if (components.length < rowKeyFormat.getComponents().size()) {
mComponents = new Object[rowKeyFormat.getComponents().size()];
for (int i = 0; i < components.length; i++) {
mComponents[i] = components[i];
}
} else {
mComponents = components;
}
} | @Test
public void testFormattedEntityIdRowFilter() throws Exception {
FormattedEntityIdRowFilter filter = createFilter(mRowKeyFormat, 100, null, "value");
runTest(mRowKeyFormat, filter, mFactory, INCLUDE, 100, 2000L, "value");
runTest(mRowKeyFormat, filter, mFactory, EXCLUDE, 100, null, null);
runTest(mRowKeyFormat, filter, mFactory, EXCLUDE, 0, null, null);
} |
["('/** {@inheritDoc} */', '')", "('', '// In the case that we have enough information to generate a prefix, we will\\n')", '(\'\', "// construct a PrefixFilter that is AND\'ed with the RowFilter. This way,\\n")', "('', '// when the scan passes the end of the prefix, it can end the filtering\\n')", "('', '// process quickly.\\n')", "('', '// Define a regular expression that effectively creates a mask for the row\\n')", "('', '// key based on the key format and the components passed in. Prefix hashes\\n')", "('', '// are skipped over, and null components match any value.\\n')", "('', '// ISO-8859-1 is used so that numerals map to valid characters\\n')", "('', '// see http://stackoverflow.com/a/1387184\\n')", "('', '// Use the embedded flag (?s) to turn on single-line mode; this makes the\\n')", '(\'\', "// \'.\' match on line terminators. The RegexStringComparator uses the DOTALL\\n")', "('', '// flag during construction, but it does not use that flag upon\\n')", "('', '// deserialization. This bug has been fixed in HBASE-5667, part of the 0.95\\n')", "('', '// release.\\n')", "('', '// ^ matches the beginning of the string\\n')", "('', '// If all of the components included in the hash have been specified,\\n')", "('', '// then match on the value of the hash\\n')", "('', '// Write the hashed bytes to the prefix buffer\\n')", '(\'\', "// match any character exactly \'hash size\' number of times\\n")', "('', '// Only add to the prefix buffer until we hit a null component. We do this\\n')", "('', '// here, because the prefix is going to expect to have 0x00 component\\n')", "('', '// terminators, which we put in during this loop but not in the loop above.\\n')", "('', '// null integers can be excluded entirely if there are just nulls at\\n')", "('', '// the end of the EntityId, otherwise, match the correct number of\\n')", "('', '// bytes\\n')", "('', '// match each byte in the integer using a regex hex sequence\\n')", "('', '// null longs can be excluded entirely if there are just nulls at\\n')", "('', '// the end of the EntityId, otherwise, match the correct number of\\n')", "('', '// bytes\\n')", "('', '// match each byte in the long using a regex hex sequence\\n')", "('', '// match any non-zero character at least once, followed by a zero\\n')", "('', '// delimiter, or match nothing at all in case the component was at\\n')", "('', '// the end of the EntityId and skipped entirely\\n')", "('', '// FormattedEntityId converts a string component to UTF-8 bytes to\\n')", "('', '// create the HBase key. RegexStringComparator will convert the\\n')", "('', '// value it sees (ie, the HBase key) to a string using ISO-8859-1.\\n')", "('', '// Therefore, we need to write ISO-8859-1 characters to our regex so\\n')", "('', '// that the comparison happens correctly.\\n')", "('', '// $ matches the end of the string\\n')"] | b'/** {@inheritDoc} */'@Override
public Filter toHBaseFilter(Context context) throws IOException {
// In the case that we have enough information to generate a prefix, we will
// construct a PrefixFilter that is AND'ed with the RowFilter. This way,
// when the scan passes the end of the prefix, it can end the filtering
// process quickly.
boolean addPrefixFilter = false;
ByteArrayOutputStream prefixBytes = new ByteArrayOutputStream();
// Define a regular expression that effectively creates a mask for the row
// key based on the key format and the components passed in. Prefix hashes
// are skipped over, and null components match any value.
// ISO-8859-1 is used so that numerals map to valid characters
// see http://stackoverflow.com/a/1387184
// Use the embedded flag (?s) to turn on single-line mode; this makes the
// '.' match on line terminators. The RegexStringComparator uses the DOTALL
// flag during construction, but it does not use that flag upon
// deserialization. This bug has been fixed in HBASE-5667, part of the 0.95
// release.
StringBuilder regex = new StringBuilder("(?s)^"); // ^ matches the beginning of the string
if (null != mRowKeyFormat.getSalt()) {
if (mRowKeyFormat.getSalt().getHashSize() > 0) {
// If all of the components included in the hash have been specified,
// then match on the value of the hash
Object[] prefixComponents =
getNonNullPrefixComponents(mComponents, mRowKeyFormat.getRangeScanStartIndex());
if (prefixComponents.length == mRowKeyFormat.getRangeScanStartIndex()) {
ByteArrayOutputStream tohash = new ByteArrayOutputStream();
for (Object component : prefixComponents) {
byte[] componentBytes = toBytes(component);
tohash.write(componentBytes, 0, componentBytes.length);
}
byte[] hashed = Arrays.copyOfRange(Hasher.hash(tohash.toByteArray()), 0,
mRowKeyFormat.getSalt().getHashSize());
for (byte hashedByte : hashed) {
regex.append(String.format("\\x%02x", hashedByte & 0xFF));
}
addPrefixFilter = true;
// Write the hashed bytes to the prefix buffer
prefixBytes.write(hashed, 0, hashed.length);
} else {
// match any character exactly 'hash size' number of times
regex.append(".{").append(mRowKeyFormat.getSalt().getHashSize()).append("}");
}
}
}
// Only add to the prefix buffer until we hit a null component. We do this
// here, because the prefix is going to expect to have 0x00 component
// terminators, which we put in during this loop but not in the loop above.
boolean hitNullComponent = false;
for (int i = 0; i < mComponents.length; i++) {
final Object component = mComponents[i];
switch (mRowKeyFormat.getComponents().get(i).getType()) {
case INTEGER:
if (null == component) {
// null integers can be excluded entirely if there are just nulls at
// the end of the EntityId, otherwise, match the correct number of
// bytes
regex.append("(.{").append(Bytes.SIZEOF_INT).append("})?");
hitNullComponent = true;
} else {
byte[] tempBytes = toBytes((Integer) component);
// match each byte in the integer using a regex hex sequence
for (byte tempByte : tempBytes) {
regex.append(String.format("\\x%02x", tempByte & 0xFF));
}
if (!hitNullComponent) {
prefixBytes.write(tempBytes, 0, tempBytes.length);
}
}
break;
case LONG:
if (null == component) {
// null longs can be excluded entirely if there are just nulls at
// the end of the EntityId, otherwise, match the correct number of
// bytes
regex.append("(.{").append(Bytes.SIZEOF_LONG).append("})?");
hitNullComponent = true;
} else {
byte[] tempBytes = toBytes((Long) component);
// match each byte in the long using a regex hex sequence
for (byte tempByte : tempBytes) {
regex.append(String.format("\\x%02x", tempByte & 0xFF));
}
if (!hitNullComponent) {
prefixBytes.write(tempBytes, 0, tempBytes.length);
}
}
break;
case STRING:
if (null == component) {
// match any non-zero character at least once, followed by a zero
// delimiter, or match nothing at all in case the component was at
// the end of the EntityId and skipped entirely
regex.append("([^\\x00]+\\x00)?");
hitNullComponent = true;
} else {
// FormattedEntityId converts a string component to UTF-8 bytes to
// create the HBase key. RegexStringComparator will convert the
// value it sees (ie, the HBase key) to a string using ISO-8859-1.
// Therefore, we need to write ISO-8859-1 characters to our regex so
// that the comparison happens correctly.
byte[] utfBytes = toBytes((String) component);
String isoString = new String(utfBytes, Charsets.ISO_8859_1);
regex.append(isoString).append("\\x00");
if (!hitNullComponent) {
prefixBytes.write(utfBytes, 0, utfBytes.length);
prefixBytes.write((byte) 0);
}
}
break;
default:
throw new IllegalStateException("Unknown component type: "
+ mRowKeyFormat.getComponents().get(i).getType());
}
}
regex.append("$"); // $ matches the end of the string
final RowFilter regexRowFilter =
SchemaPlatformBridge.get().createRowFilterFromRegex(CompareOp.EQUAL, regex.toString());
if (addPrefixFilter) {
return new FilterList(new PrefixFilter(prefixBytes.toByteArray()), regexRowFilter);
}
return regexRowFilter;
} | @Test
public void testLatinNewlineCharacterInclusion() throws Exception {
RowKeyFormat2 rowKeyFormat = createRowKeyFormat(1, INTEGER, LONG);
EntityIdFactory factory = EntityIdFactory.getFactory(rowKeyFormat);
// Create and serialize a filter.
FormattedEntityIdRowFilter filter = createFilter(rowKeyFormat, 10);
byte[] serializedFilter = filter.toHBaseFilter(null).toByteArray();
// Deserialize the filter.
Filter deserializedFilter = FilterList.parseFrom(serializedFilter);
// Filter an entity with the deserialized filter.
EntityId entityId = factory.getEntityId(10, 10L);
byte[] hbaseKey = entityId.getHBaseRowKey();
boolean filtered = deserializedFilter.filterRowKey(hbaseKey, 0, hbaseKey.length);
assertEquals(INCLUDE, filtered);
} |
['(\'/**\\\\n * Gets a builder configured with default Kiji URI fields.\\\\n *\\\\n * More precisely, the following defaults are initialized:\\\\n * <ul>\\\\n * <li>The Zookeeper quorum and client port is taken from the Hadoop <tt>Configuration</tt></li>\\\\n * <li>The Kiji instance name is set to <tt>KConstants.DEFAULT_INSTANCE_NAME</tt>\\\\n * (<tt>"default"</tt>).</li>\\\\n * <li>The table name and column names are explicitly left unset.</li>\\\\n * </ul>\\\\n *\\\\n * @return A builder configured with this Kiji URI.\\\\n */\', \'\')'] | b'/**\n * Gets a builder configured with default Kiji URI fields.\n *\n * More precisely, the following defaults are initialized:\n * <ul>\n * <li>The Zookeeper quorum and client port is taken from the Hadoop <tt>Configuration</tt></li>\n * <li>The Kiji instance name is set to <tt>KConstants.DEFAULT_INSTANCE_NAME</tt>\n * (<tt>"default"</tt>).</li>\n * <li>The table name and column names are explicitly left unset.</li>\n * </ul>\n *\n * @return A builder configured with this Kiji URI.\n */'public static HBaseKijiURIBuilder newBuilder() {
return new HBaseKijiURIBuilder();
} | @Test
public void testSingleHost() {
final KijiURI uri = KijiURI.newBuilder("kiji-hbase://zkhost:1234/instance/table/col").build();
assertEquals("kiji-hbase", uri.getScheme());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
} |
["('/**\\\\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\\\\n * description record.\\\\n *\\\\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\\\\n * of the table.\\\\n * @return A new table layout.\\\\n * @throws InvalidLayoutException If the descriptor is invalid.\\\\n */', '')"] | b'/**\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\n * description record.\n *\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\n * of the table.\n * @return A new table layout.\n * @throws InvalidLayoutException If the descriptor is invalid.\n */'public static KijiTableLayout newLayout(TableLayoutDesc layout) throws InvalidLayoutException {
return new KijiTableLayout(layout, null);
} | @Test
public void badHashSizeRKF() throws InvalidLayoutException {
final TableLayoutDesc desc = TableLayoutDesc.newBuilder()
.setName("table_name")
.setKeysFormat(badHashSizeRowKeyFormat())
.setVersion(TABLE_LAYOUT_VERSION)
.build();
try {
final KijiTableLayout ktl = KijiTableLayout.newLayout(desc);
fail("An exception should have been thrown.");
} catch (InvalidLayoutException ile) {
assertEquals("Valid hash sizes are between 1 and 16", ile.getMessage());
}
} |
["('/**\\\\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\\\\n * description record.\\\\n *\\\\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\\\\n * of the table.\\\\n * @return A new table layout.\\\\n * @throws InvalidLayoutException If the descriptor is invalid.\\\\n */', '')"] | b'/**\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\n * description record.\n *\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\n * of the table.\n * @return A new table layout.\n * @throws InvalidLayoutException If the descriptor is invalid.\n */'public static KijiTableLayout newLayout(TableLayoutDesc layout) throws InvalidLayoutException {
return new KijiTableLayout(layout, null);
} | @Test
public void repeatedNamesRKF() throws InvalidLayoutException {
final TableLayoutDesc desc = TableLayoutDesc.newBuilder()
.setName("table_name")
.setKeysFormat(repeatedNamesRowKeyFormat())
.setVersion(TABLE_LAYOUT_VERSION)
.build();
try {
final KijiTableLayout ktl = KijiTableLayout.newLayout(desc);
fail("An exception should have been thrown.");
} catch (InvalidLayoutException ile) {
assertEquals("Component name already used.", ile.getMessage());
}
} |
["('/**\\\\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\\\\n * description record.\\\\n *\\\\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\\\\n * of the table.\\\\n * @return A new table layout.\\\\n * @throws InvalidLayoutException If the descriptor is invalid.\\\\n */', '')"] | b'/**\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\n * description record.\n *\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\n * of the table.\n * @return A new table layout.\n * @throws InvalidLayoutException If the descriptor is invalid.\n */'public static KijiTableLayout newLayout(TableLayoutDesc layout) throws InvalidLayoutException {
return new KijiTableLayout(layout, null);
} | @Test
public void tooHighRangeScanIndexRKF() throws InvalidLayoutException {
final TableLayoutDesc desc = TableLayoutDesc.newBuilder()
.setName("table_name")
.setKeysFormat(tooHighRangeScanIndexRowKeyFormat())
.setVersion(TABLE_LAYOUT_VERSION)
.build();
try {
final KijiTableLayout ktl = KijiTableLayout.newLayout(desc);
fail("An exception should have been thrown.");
} catch (InvalidLayoutException ile) {
assertEquals(
"Invalid range scan index. Range scans are supported starting with the second component.",
ile.getMessage());
}
} |
["('/**\\\\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\\\\n * description record.\\\\n *\\\\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\\\\n * of the table.\\\\n * @return A new table layout.\\\\n * @throws InvalidLayoutException If the descriptor is invalid.\\\\n */', '')"] | b'/**\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\n * description record.\n *\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\n * of the table.\n * @return A new table layout.\n * @throws InvalidLayoutException If the descriptor is invalid.\n */'public static KijiTableLayout newLayout(TableLayoutDesc layout) throws InvalidLayoutException {
return new KijiTableLayout(layout, null);
} | @Test
public void zeroNullableIndexRKF() throws InvalidLayoutException {
final TableLayoutDesc desc = TableLayoutDesc.newBuilder()
.setName("table_name")
.setKeysFormat(zeroNullableIndexRowKeyFormat())
.setVersion(TABLE_LAYOUT_VERSION)
.build();
try {
final KijiTableLayout ktl = KijiTableLayout.newLayout(desc);
fail("An exception should have been thrown.");
} catch (InvalidLayoutException ile) {
assertEquals(
"Invalid index for nullable component. The second component onwards can be set to null.",
ile.getMessage());
}
} |
["('/**\\\\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\\\\n * description record.\\\\n *\\\\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\\\\n * of the table.\\\\n * @return A new table layout.\\\\n * @throws InvalidLayoutException If the descriptor is invalid.\\\\n */', '')"] | b'/**\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\n * description record.\n *\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\n * of the table.\n * @return A new table layout.\n * @throws InvalidLayoutException If the descriptor is invalid.\n */'public static KijiTableLayout newLayout(TableLayoutDesc layout) throws InvalidLayoutException {
return new KijiTableLayout(layout, null);
} | @Test
public void tooHighNullableScanIndexRKF() throws InvalidLayoutException {
final TableLayoutDesc desc = TableLayoutDesc.newBuilder()
.setName("table_name")
.setKeysFormat(tooHighNullableIndexRowKeyFormat())
.setVersion(TABLE_LAYOUT_VERSION)
.build();
try {
final KijiTableLayout ktl = KijiTableLayout.newLayout(desc);
fail("An exception should have been thrown.");
} catch (InvalidLayoutException ile) {
assertEquals(
"Invalid index for nullable component. The second component onwards can be set to null.",
ile.getMessage());
}
} |
["('/**\\\\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\\\\n * description record.\\\\n *\\\\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\\\\n * of the table.\\\\n * @return A new table layout.\\\\n * @throws InvalidLayoutException If the descriptor is invalid.\\\\n */', '')"] | b'/**\n * Creates and returns a new KijiTableLayout instance as specified by an Avro TableLayoutDesc\n * description record.\n *\n * @param layout The Avro TableLayoutDesc descriptor record that describes the actual layout.\n * of the table.\n * @return A new table layout.\n * @throws InvalidLayoutException If the descriptor is invalid.\n */'public static KijiTableLayout newLayout(TableLayoutDesc layout) throws InvalidLayoutException {
return new KijiTableLayout(layout, null);
} | @Test
public void emptyCompNameRKF() throws InvalidLayoutException {
final TableLayoutDesc desc = TableLayoutDesc.newBuilder()
.setName("table_name")
.setKeysFormat(emptyCompNameRowKeyFormat())
.setVersion(TABLE_LAYOUT_VERSION)
.build();
try {
final KijiTableLayout ktl = KijiTableLayout.newLayout(desc);
fail("An exception should have been thrown.");
} catch (InvalidLayoutException ile) {
assertEquals("Names should begin with a letter followed by a combination of letters, numbers "
+ "and underscores.", ile.getMessage());
}
} |
["('/**\\\\n * Build a new table layout descriptor.\\\\n *\\\\n * @return a built table layout descriptor.\\\\n */', '')"] | b'/**\n * Build a new table layout descriptor.\n *\n * @return a built table layout descriptor.\n */'public TableLayoutDesc build() {
return mDescBuilder.build();
} | @Test
public void testTableLayoutSafeMutation() throws IOException {
final KijiTableLayout layout = KijiTableLayouts.getTableLayout(TEST_LAYOUT);
final TableLayoutDesc tld = layout.getDesc();
final TableLayoutBuilder tlb = new TableLayoutBuilder(tld, getKiji());
tld.setName("blastoise");
final TableLayoutDesc tldBuilt = tlb.build();
assertFalse(tld.getName().equals(tldBuilt.getName()));
} |
["('/**\\\\n * Register a reader schema to a column.\\\\n *\\\\n * @param columnName at which to register the schema.\\\\n * @param schema to register.\\\\n * @throws IOException If the parameters are invalid.\\\\n * @return this.\\\\n */', '')"] | b'/**\n * Register a reader schema to a column.\n *\n * @param columnName at which to register the schema.\n * @param schema to register.\n * @throws IOException If the parameters are invalid.\n * @return this.\n */'public TableLayoutBuilder withReader(
final KijiColumnName columnName,
final Schema schema)
throws IOException {
return withSchema(columnName, schema, SchemaRegistrationType.READER);
} | @Test
public void testSchemaRegistrationAtBadColumns() throws IOException {
final KijiTableLayout layout = KijiTableLayouts.getTableLayout(TEST_LAYOUT);
final TableLayoutBuilder tlb = new TableLayoutBuilder(layout.getDesc(), getKiji());
final Schema.Parser p = new Schema.Parser();
Schema stringSchema = p.parse("\"string\"");
// Unqualified group family
try {
tlb.withReader(KijiColumnName.create("profile"), stringSchema);
fail("An exception should have been thrown.");
} catch (NoSuchColumnException nsce) {
assertEquals("Table 'table_name' has no column 'profile'.", nsce.getMessage());
}
// Fully qualified map family
try {
tlb.withReader(KijiColumnName.create("heroism:mordor"), stringSchema);
fail("An exception should have been thrown.");
} catch (InvalidLayoutException ile) {
assertEquals("A fully qualified map-type column name was provided.", ile.getMessage());
}
// Nonexistent column
try {
tlb.withReader(KijiColumnName.create("info:name"), stringSchema);
fail("An exception should have been thrown.");
} catch (NoSuchColumnException nsce) {
assertEquals("Table 'table_name' has no column 'info:name'.", nsce.getMessage());
}
// FINAL column
try {
tlb.withReader(KijiColumnName.create("clans"), stringSchema);
fail("An exception should have been thrown.");
} catch (InvalidLayoutException ile) {
assertEquals("Final or non-AVRO column schema cannot be modified.", ile.getMessage());
}
} |
["('/**\\\\n * Adds the jars from a directory into the distributed cache of a job.\\\\n *\\\\n * @param job The job to configure.\\\\n * @param jarDirectory A path to a directory of jar files.\\\\n * @throws IOException If there is a problem reading from the file system.\\\\n */', '')"] | b'/**\n * Adds the jars from a directory into the distributed cache of a job.\n *\n * @param job The job to configure.\n * @param jarDirectory A path to a directory of jar files.\n * @throws IOException If there is a problem reading from the file system.\n */'public static void addJarsToDistributedCache(Job job, String jarDirectory) throws IOException {
addJarsToDistributedCache(job, new File(jarDirectory));
} | @Test
public void testJarsDeDupe() throws IOException {
// Jar list should de-dupe to {"myjar_a, "myjar_b", "myjar_0", "myjar_1"}
Set<String> dedupedJarNames = new HashSet<String>(4);
dedupedJarNames.add("myjar_a.jar");
dedupedJarNames.add("myjar_b.jar");
dedupedJarNames.add("myjar_0.jar");
dedupedJarNames.add("myjar_1.jar");
Job job = new Job();
List<String> someJars = new ArrayList<String>();
// Some unique jar names.
someJars.add("/somepath/myjar_a.jar");
someJars.add("/another/path/myjar_b.jar");
someJars.add("/myjar_0.jar");
// Duplicate jars.
someJars.add("/another/path/myjar_b.jar");
someJars.add("/yet/another/path/myjar_b.jar");
job.getConfiguration().set(CONF_TMPJARS, StringUtils.join(someJars, ","));
// Now add some duplicate jars from mTempDir.
assertEquals(0, mTempDir.getRoot().list().length);
createTestJars("myjar_0.jar", "myjar_1.jar");
assertEquals(2, mTempDir.getRoot().list().length);
DistributedCacheJars.addJarsToDistributedCache(job, mTempDir.getRoot());
// Confirm each jar appears in de-dupe list exactly once.
String listedJars = job.getConfiguration().get(CONF_TMPJARS);
String[] jars = listedJars.split(",");
for (String jar : jars) {
// Check that path terminates in an expected jar.
Path p = new Path(jar);
assertTrue(dedupedJarNames.contains(p.getName()));
dedupedJarNames.remove(p.getName());
}
assertEquals(0, dedupedJarNames.size());
} |
["('/** {@inheritDoc} */', '')"] | b'/** {@inheritDoc} */'@Override
public void close() throws IOException {
mVersionPager.close();
} | @Test
public void testQualifiersIterator() throws IOException {
final EntityId eid = mTable.getEntityId("me");
final KijiDataRequest dataRequest = KijiDataRequest.builder()
.addColumns(ColumnsDef.create()
.withMaxVersions(HConstants.ALL_VERSIONS).withPageSize(1).addFamily("jobs"))
.build();
final KijiRowData row = mReader.get(eid, dataRequest);
final ColumnVersionIterator<String> it =
new ColumnVersionIterator<String>(row, "jobs", "j2", 3);
try {
long counter = 5;
for (Entry<Long, String> entry : it) {
assertEquals(counter, (long) entry.getKey());
counter -= 1;
}
} finally {
it.close();
}
} |
['(\'/**\\\\n * Gets a builder configured with default Kiji URI fields.\\\\n *\\\\n * More precisely, the following defaults are initialized:\\\\n * <ul>\\\\n * <li>The Zookeeper quorum and client port is taken from the Hadoop <tt>Configuration</tt></li>\\\\n * <li>The Kiji instance name is set to <tt>KConstants.DEFAULT_INSTANCE_NAME</tt>\\\\n * (<tt>"default"</tt>).</li>\\\\n * <li>The table name and column names are explicitly left unset.</li>\\\\n * </ul>\\\\n *\\\\n * @return A builder configured with this Kiji URI.\\\\n */\', \'\')'] | b'/**\n * Gets a builder configured with default Kiji URI fields.\n *\n * More precisely, the following defaults are initialized:\n * <ul>\n * <li>The Zookeeper quorum and client port is taken from the Hadoop <tt>Configuration</tt></li>\n * <li>The Kiji instance name is set to <tt>KConstants.DEFAULT_INSTANCE_NAME</tt>\n * (<tt>"default"</tt>).</li>\n * <li>The table name and column names are explicitly left unset.</li>\n * </ul>\n *\n * @return A builder configured with this Kiji URI.\n */'public static HBaseKijiURIBuilder newBuilder() {
return new HBaseKijiURIBuilder();
} | @Test
public void testSingleHostGroupColumn() {
final KijiURI uri =
KijiURI.newBuilder("kiji-hbase://zkhost:1234/instance/table/family:qualifier").build();
assertEquals("kiji-hbase", uri.getScheme());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("family:qualifier", uri.getColumns().get(0).getName());
} |
@inheritDoc | b'/** {@inheritDoc} */'@Override
public boolean equals(Object object) {
if (object instanceof KijiCell) {
final KijiCell<?> that = (KijiCell<?>) object;
return this.mColumn.equals(that.mColumn)
&& (this.mTimestamp == that.mTimestamp)
&& this.mDecodedCell.equals(that.mDecodedCell);
} else {
return false;
}
} | @Test
public void testEquals() {
final KijiCell<Integer> cell1 =
KijiCell.create(KijiColumnName.create("family", "qualifier"), 1234L,
new DecodedCell<Integer>(Schema.create(Schema.Type.INT), 31415));
final KijiCell<Integer> cell2 =
KijiCell.create(KijiColumnName.create("family", "qualifier"), 1234L,
new DecodedCell<Integer>(Schema.create(Schema.Type.INT), 31415));
Assert.assertTrue(cell1.equals(cell2));
Assert.assertTrue(cell2.equals(cell1));
Assert.assertEquals(cell1.hashCode(), cell2.hashCode());
} |
["('/**\\\\n * Create a new KijiColumnName from a family and qualifier.\\\\n *\\\\n * @param family Family of the Kiji column for which to create a name.\\\\n * @param qualifier Qualifier of the Kiji column for which to create a name.\\\\n * @return a new KijiColumnName from the given family and qualifier.\\\\n */', '')"] | b'/**\n * Create a new KijiColumnName from a family and qualifier.\n *\n * @param family Family of the Kiji column for which to create a name.\n * @param qualifier Qualifier of the Kiji column for which to create a name.\n * @return a new KijiColumnName from the given family and qualifier.\n */'public static KijiColumnName create(
final String family,
final String qualifier
) {
return new KijiColumnName(family, qualifier);
} | @Test
public void testNull() {
try {
KijiColumnName.create(null);
fail("An exception should have been thrown.");
} catch (IllegalArgumentException iae) {
assertEquals("Column name may not be null. At least specify family", iae.getMessage());
}
} |
["('/**\\\\n * Create a new KijiColumnName from a family and qualifier.\\\\n *\\\\n * @param family Family of the Kiji column for which to create a name.\\\\n * @param qualifier Qualifier of the Kiji column for which to create a name.\\\\n * @return a new KijiColumnName from the given family and qualifier.\\\\n */', '')"] | b'/**\n * Create a new KijiColumnName from a family and qualifier.\n *\n * @param family Family of the Kiji column for which to create a name.\n * @param qualifier Qualifier of the Kiji column for which to create a name.\n * @return a new KijiColumnName from the given family and qualifier.\n */'public static KijiColumnName create(
final String family,
final String qualifier
) {
return new KijiColumnName(family, qualifier);
} | @Test
public void testNullFamily() {
try {
KijiColumnName.create(null, "qualifier");
fail("An exception should have been thrown.");
} catch (IllegalArgumentException iae) {
assertEquals("Family name may not be null.", iae.getMessage());
}
} |
["('/**\\\\n * Create a new KijiColumnName from a family and qualifier.\\\\n *\\\\n * @param family Family of the Kiji column for which to create a name.\\\\n * @param qualifier Qualifier of the Kiji column for which to create a name.\\\\n * @return a new KijiColumnName from the given family and qualifier.\\\\n */', '')"] | b'/**\n * Create a new KijiColumnName from a family and qualifier.\n *\n * @param family Family of the Kiji column for which to create a name.\n * @param qualifier Qualifier of the Kiji column for which to create a name.\n * @return a new KijiColumnName from the given family and qualifier.\n */'public static KijiColumnName create(
final String family,
final String qualifier
) {
return new KijiColumnName(family, qualifier);
} | @Test
public void testInvalidFamilyName() {
try {
KijiColumnName.create("1:qualifier");
fail("An exception should have been thrown.");
} catch (KijiInvalidNameException kine) {
assertEquals("Invalid family name: 1 Name must match pattern: [a-zA-Z_][a-zA-Z0-9_]*",
kine.getMessage());
}
} |
@inheritDoc | b'/** {@inheritDoc} */'@Override
public boolean equals(Object otherObj) {
if (otherObj == this) {
return true;
} else if (null == otherObj) {
return false;
} else if (!otherObj.getClass().equals(getClass())) {
return false;
}
final KijiColumnName other = (KijiColumnName) otherObj;
return other.getFamily().equals(mFamily) && Objects.equal(other.getQualifier(), mQualifier);
} | @Test
public void testEquals() {
KijiColumnName columnA = KijiColumnName.create("family", "qualifier1");
KijiColumnName columnC = KijiColumnName.create("family", null);
KijiColumnName columnD = KijiColumnName.create("family", "qualifier2");
assertTrue(columnA.equals(columnA)); // reflexive
assertFalse(columnA.equals(columnC) || columnC.equals(columnA));
assertFalse(columnA.equals(columnD) || columnD.equals(columnA));
} |
@inheritDoc | b'/** {@inheritDoc} */'@Override
public int hashCode() {
return new HashCodeBuilder().append(mFamily).append(mQualifier).toHashCode();
} | @Test
public void testHashCode() {
KijiColumnName columnA = KijiColumnName.create("family", "qualifier");
KijiColumnName columnB = KijiColumnName.create("family:qualifier");
assertEquals(columnA.hashCode(), columnB.hashCode());
} |
@inheritDoc | b'/** {@inheritDoc} */'@Override
public int compareTo(KijiColumnName otherObj) {
final int comparison = this.mFamily.compareTo(otherObj.mFamily);
if (0 == comparison) {
return (this.isFullyQualified() ? mQualifier : "")
.compareTo(otherObj.isFullyQualified() ? otherObj.getQualifier() : "");
} else {
return comparison;
}
} | @Test
public void testCompareTo() {
KijiColumnName columnA = KijiColumnName.create("family");
KijiColumnName columnB = KijiColumnName.create("familyTwo");
KijiColumnName columnC = KijiColumnName.create("family:qualifier");
assertTrue(0 == columnA.compareTo(columnA));
assertTrue(0 > columnA.compareTo(columnB) && 0 < columnB.compareTo(columnA));
assertTrue(0 > columnA.compareTo(columnC) && 0 < columnC.compareTo(columnA));
assertTrue(0 < columnB.compareTo(columnC) && 0 > columnC.compareTo(columnB));
} |
["('/**\\\\n * Creates a new {@link KijiDataRequestBuilder}. Use this to configure a KijiDataRequest,\\\\n * then create one with the {@link KijiDataRequestBuilder#build()} method.\\\\n *\\\\n * @return a new KijiDataRequestBuilder.\\\\n */', '')"] | b'/**\n * Creates a new {@link KijiDataRequestBuilder}. Use this to configure a KijiDataRequest,\n * then create one with the {@link KijiDataRequestBuilder#build()} method.\n *\n * @return a new KijiDataRequestBuilder.\n */'public static KijiDataRequestBuilder builder() {
return new KijiDataRequestBuilder();
} | @Test
public void testDataRequestEquals() {
KijiDataRequestBuilder builder0 = KijiDataRequest.builder()
.withTimeRange(3L, 4L);
builder0.newColumnsDef().withMaxVersions(2).addFamily("foo");
builder0.newColumnsDef().withMaxVersions(5).add("bar", "baz");
KijiDataRequest request0 = builder0.build();
KijiDataRequestBuilder builder1 = KijiDataRequest.builder()
.withTimeRange(3L, 4L);
builder1.newColumnsDef().withMaxVersions(2).addFamily("foo");
builder1.newColumnsDef().withMaxVersions(5).add("bar", "baz");
KijiDataRequest request1 = builder1.build();
KijiDataRequestBuilder builder2 = KijiDataRequest.builder()
.withTimeRange(3L, 4L);
builder2.newColumnsDef().withMaxVersions(2).addFamily("foo");
builder2.newColumnsDef().withMaxVersions(5).add("car", "bot");
KijiDataRequest request2 = builder2.build();
KijiDataRequestBuilder builder3 = KijiDataRequest.builder()
.withTimeRange(3L, 4L);
builder3.newColumnsDef().withMaxVersions(2).addFamily("foo");
builder3.newColumnsDef().withMaxVersions(3).add("car", "bot");
KijiDataRequest request3 = builder3.build();
assertEquals(request0, request1);
assertThat(new Object(), is(not((Object) request0)));
assertThat(request0, is(not(request2)));
assertThat(request2, is(not(request3)));
} |
Creates a new data request representing the union of this data request and the data request specified as an argument pThis method merges data requests using the widestpossible treatment of parameters This may result in cells being included in the result set that were not specified by either data set For example if request A includes ttinfofoott from time range 400 700 and request B includes ttinfobartt from time range 500 900 then AmergeB will yield a data request for both columns with time range 400 900p pMore precisely merges are handled in the following wayp ul liThe output time interval encompasses both data requests time intervalsli liAll columns associated with both data requests will be includedli liWhen maxVersions differs for the same column in both requests the greater value is chosenli liWhen pageSize differs for the same column in both requests the lesser value is chosenli liIf either request contains KijiColumnFilter definitions attached to a column this is considered an error and a RuntimeException is thrown Data requests with filters cannot be mergedli liIf one data request includes an entire column family ttfoott and the other data request includes a column within that family ttfoobartt the entire family will be requested and properties such as max versions etc for the familywide request will be merged with the column to ensure the request is as wide as possibleli ul @param other another data request to include as a part of this one @return A new KijiDataRequest instance including the union of this data request and the argument request maptype families requested First include any requests for column families And while were at it check for filters We dont know how to merge these Loop through any requests on our end that have the same family Include requests for column families on our side that arent present on theirs And while were at it check for filters We dont know how to merge these Loop through requests on their end that have the same family Now include individual columns from their side If we have corresponding definitions for the same columns merge them If the column is already covered by a request for a family ignore the individual column its already been merged We dont have a request for otherColumn so add it Now grab any columns that were present in our data request but missed entirely in the other sides data request Column in our list but not the other sides list | b"/**\n * Creates a new data request representing the union of this data request and the\n * data request specified as an argument.\n *\n * <p>This method merges data requests using the widest-possible treatment of\n * parameters. This may result in cells being included in the result set that\n * were not specified by either data set. For example, if request A includes <tt>info:foo</tt>\n * from time range [400, 700), and request B includes <tt>info:bar</tt> from time range\n * [500, 900), then A.merge(B) will yield a data request for both columns, with time\n * range [400, 900).</p>\n *\n * <p>More precisely, merges are handled in the following way:</p>\n * <ul>\n * <li>The output time interval encompasses both data requests' time intervals.</li>\n * <li>All columns associated with both data requests will be included.</li>\n * <li>When maxVersions differs for the same column in both requests, the greater\n * value is chosen.</li>\n * <li>When pageSize differs for the same column in both requests, the lesser value\n * is chosen.</li>\n * <li>If either request contains KijiColumnFilter definitions attached to a column,\n * this is considered an error, and a RuntimeException is thrown. Data requests with\n * filters cannot be merged.</li>\n * <li>If one data request includes an entire column family (<tt>foo:*</tt>) and\n * the other data request includes a column within that family (<tt>foo:bar</tt>),\n * the entire family will be requested, and properties such as max versions, etc.\n * for the family-wide request will be merged with the column to ensure the request\n * is as wide as possible.</li>\n * </ul>\n *\n * @param other another data request to include as a part of this one.\n * @return A new KijiDataRequest instance, including the union of this data request\n * and the argument request.\n */"public KijiDataRequest merge(KijiDataRequest other) {
if (null == other) {
throw new IllegalArgumentException("Input data request cannot be null.");
}
List<Column> outCols = new ArrayList<Column>();
Set<String> families = new HashSet<String>(); // map-type families requested.
// First, include any requests for column families.
for (Column otherCol : other.getColumns()) {
if (otherCol.getFilter() != null) {
// And while we're at it, check for filters. We don't know how to merge these.
throw new IllegalStateException("Invalid merge request: "
+ otherCol.getName() + " has a filter.");
}
if (otherCol.getQualifier() == null) {
Column outFamily = otherCol;
// Loop through any requests on our end that have the same family.
for (Column myCol : getColumns()) {
if (myCol.getFamily().equals(otherCol.getFamily())) {
outFamily = mergeColumn(myCol.getFamily(), null, myCol, outFamily);
}
}
outCols.add(outFamily);
families.add(outFamily.getFamily());
}
}
// Include requests for column families on our side that aren't present on their's.
for (Column myCol : getColumns()) {
if (myCol.getFilter() != null) {
// And while we're at it, check for filters. We don't know how to merge these.
throw new IllegalStateException("Invalid merge request: "
+ myCol.getName() + " has a filter.");
}
if (myCol.getQualifier() == null && !families.contains(myCol.getFamily())) {
Column outFamily = myCol;
// Loop through requests on their end that have the same family.
for (Column otherCol : other.getColumns()) {
if (otherCol.getFamily().equals(myCol.getFamily())) {
outFamily = mergeColumn(myCol.getFamily(), null, outFamily, otherCol);
}
}
outCols.add(outFamily);
families.add(outFamily.getFamily());
}
}
// Now include individual columns from their side. If we have corresponding definitions
// for the same columns, merge them. If the column is already covered by a request
// for a family, ignore the individual column (it's already been merged).
for (Column otherCol : other.getColumns()) {
if (otherCol.getQualifier() != null && !families.contains(otherCol.getFamily())) {
Column myCol = getColumn(otherCol.getFamily(), otherCol.getQualifier());
if (null == myCol) {
// We don't have a request for otherColumn, so add it.
outCols.add(otherCol);
} else {
outCols.add(mergeColumn(myCol.getFamily(), myCol.getQualifier(), myCol, otherCol));
}
}
}
// Now grab any columns that were present in our data request, but missed entirely
// in the other side's data request.
for (Column myCol : getColumns()) {
if (myCol.getQualifier() != null && !families.contains(myCol.getFamily())) {
Column otherCol = other.getColumn(myCol.getFamily(), myCol.getQualifier());
if (null == otherCol) {
// Column in our list but not the other side's list.
outCols.add(myCol);
}
}
}
long outMinTs = Math.min(getMinTimestamp(), other.getMinTimestamp());
long outMaxTs = Math.max(getMaxTimestamp(), other.getMaxTimestamp());
return new KijiDataRequest(outCols, outMinTs, outMaxTs);
} | @Test
public void testMerge() {
KijiDataRequestBuilder builder1 = KijiDataRequest.builder().withTimeRange(3, 4);
builder1.newColumnsDef().withMaxVersions(2).add("foo", "bar");
KijiDataRequest first = builder1.build();
KijiDataRequestBuilder builder2 = KijiDataRequest.builder().withTimeRange(2, 4);
builder2.newColumnsDef().add("baz", "bot");
builder2.newColumnsDef().withMaxVersions(6).add("foo", "bar");
KijiDataRequest second = builder2.build();
KijiDataRequest merged = first.merge(second);
assertTrue("merge() cannot mutate the object in place", first != merged);
KijiDataRequest.Column fooBarColumnRequest = merged.getColumn("foo", "bar");
assertNotNull("Missing column foo:bar from merged request", fooBarColumnRequest);
assertEquals("Max versions was not increased", 6, fooBarColumnRequest.getMaxVersions());
assertEquals("Time range was not extended", 2L, merged.getMinTimestamp());
assertEquals(4L, merged.getMaxTimestamp());
KijiDataRequest.Column bazBotColumnRequest = merged.getColumn("baz", "bot");
assertNotNull("Missing column from merged-in request", bazBotColumnRequest);
KijiDataRequest symmetricMerged = second.merge(first);
assertEquals("Merge must be symmetric", merged, symmetricMerged);
} |
["('/**\\\\n * Creates a new {@link KijiDataRequestBuilder}. Use this to configure a KijiDataRequest,\\\\n * then create one with the {@link KijiDataRequestBuilder#build()} method.\\\\n *\\\\n * @return a new KijiDataRequestBuilder.\\\\n */', '')"] | b'/**\n * Creates a new {@link KijiDataRequestBuilder}. Use this to configure a KijiDataRequest,\n * then create one with the {@link KijiDataRequestBuilder#build()} method.\n *\n * @return a new KijiDataRequestBuilder.\n */'public static KijiDataRequestBuilder builder() {
return new KijiDataRequestBuilder();
} | @Test
public void testInvalidColumnSpec() {
// The user really wants 'builder.columns().add("family", "qualifier")'.
// This will throw an exception.
try {
KijiDataRequest.builder().newColumnsDef().addFamily("family:qualifier");
fail("An exception should have been thrown.");
} catch (KijiInvalidNameException kine) {
assertEquals(
"Invalid family name: family:qualifier Name must match pattern: [a-zA-Z_][a-zA-Z0-9_]*",
kine.getMessage());
}
} |
['(\'/**\\\\n * Gets a builder configured with default Kiji URI fields.\\\\n *\\\\n * More precisely, the following defaults are initialized:\\\\n * <ul>\\\\n * <li>The Zookeeper quorum and client port is taken from the Hadoop <tt>Configuration</tt></li>\\\\n * <li>The Kiji instance name is set to <tt>KConstants.DEFAULT_INSTANCE_NAME</tt>\\\\n * (<tt>"default"</tt>).</li>\\\\n * <li>The table name and column names are explicitly left unset.</li>\\\\n * </ul>\\\\n *\\\\n * @return A builder configured with this Kiji URI.\\\\n */\', \'\')'] | b'/**\n * Gets a builder configured with default Kiji URI fields.\n *\n * More precisely, the following defaults are initialized:\n * <ul>\n * <li>The Zookeeper quorum and client port is taken from the Hadoop <tt>Configuration</tt></li>\n * <li>The Kiji instance name is set to <tt>KConstants.DEFAULT_INSTANCE_NAME</tt>\n * (<tt>"default"</tt>).</li>\n * <li>The table name and column names are explicitly left unset.</li>\n * </ul>\n *\n * @return A builder configured with this Kiji URI.\n */'public static HBaseKijiURIBuilder newBuilder() {
return new HBaseKijiURIBuilder();
} | @Test
public void testSingleHostDefaultInstance() {
final KijiURI uri = KijiURI.newBuilder("kiji-hbase://zkhost:1234/default/table/col").build();
assertEquals("kiji-hbase", uri.getScheme());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1, uri.getZookeeperQuorum().size());
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("default", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
} |
Construct a new KijiDataRequest based on the configuration specified in this builder and its associated column builders pAfter calling build you may not use the builder anymorep @return a new KijiDataRequest object containing the column requests associated with this KijiDataRequestBuilder Entire families for which a definition has been recorded Fullyqualified columns for which a definition has been recorded Families of fullyqualified columns for which definitions have been recorded Iterate over the ColumnsDefs in the order they were added mColumnsDef is a LinkedHashSet | b'/**\n * Construct a new KijiDataRequest based on the configuration specified in this builder\n * and its associated column builders.\n *\n * <p>After calling build(), you may not use the builder anymore.</p>\n *\n * @return a new KijiDataRequest object containing the column requests associated\n * with this KijiDataRequestBuilder.\n */'public KijiDataRequest build() {
checkNotBuilt();
mIsBuilt = true;
// Entire families for which a definition has been recorded:
final Set<String> families = Sets.newHashSet();
// Fully-qualified columns for which a definition has been recorded:
final Set<KijiColumnName> columns = Sets.newHashSet();
// Families of fully-qualified columns for which definitions have been recorded:
final Set<String> familiesOfColumns = Sets.newHashSet();
final List<KijiDataRequest.Column> requestedColumns = Lists.newArrayList();
// Iterate over the ColumnsDefs in the order they were added (mColumnsDef is a LinkedHashSet).
for (ColumnsDef columnsDef : mColumnsDefs) {
for (KijiDataRequest.Column column : columnsDef.buildColumns()) {
if (column.getQualifier() == null) {
final boolean isNotDuplicate = families.add(column.getFamily());
Preconditions.checkState(isNotDuplicate,
"Duplicate definition for family '%s'.", column.getFamily());
Preconditions.checkState(!familiesOfColumns.contains(column.getFamily()),
"KijiDataRequest may not simultaneously contain definitions for family '%s' "
+ "and definitions for fully qualified columns in family '%s'.",
column.getFamily(), column.getFamily());
} else {
final boolean isNotDuplicate = columns.add(column.getColumnName());
Preconditions.checkState(isNotDuplicate, "Duplicate definition for column '%s'.", column);
Preconditions.checkState(!families.contains(column.getFamily()),
"KijiDataRequest may not simultaneously contain definitions for family '%s' "
+ "and definitions for fully qualified columns '%s'.",
column.getFamily(), column.getColumnName());
familiesOfColumns.add(column.getFamily());
}
requestedColumns.add(column);
}
}
return new KijiDataRequest(requestedColumns, mMinTimestamp, mMaxTimestamp);
} | @Test
public void testBuild() {
KijiDataRequestBuilder builder = KijiDataRequest.builder();
builder.newColumnsDef().add("info", "foo");
KijiDataRequest request = builder.build();
// We should be able to use KijiDataRequest's create() method to similar effect.
KijiDataRequest request2 = KijiDataRequest.create("info", "foo");
assertEquals("Constructions methods make different requests", request, request2);
assertTrue("Builder doesn't build a new object", request != request2);
assertNotNull("Missing info:foo!", request.getColumn("info", "foo"));
assertNull("Got spurious info:missing", request.getColumn("info", "missing"));
assertNull("Got spurious info: family", request.getColumn("info", null));
} |
["('/**\\\\n * Return a builder for columns associated with this KijiDataRequestBuilder.\\\\n *\\\\n * <p>Creates an object that allows you to specify a set of related columns attached\\\\n * to the same KijiDataRequest that all share the same retrieval properties, like\\\\n * the number of max versions.</p>\\\\n *\\\\n * @return a new KijiDataRequestBuilder.ColumnsDef builder object associated with this\\\\n * data request builder.\\\\n */', '')"] | b'/**\n * Return a builder for columns associated with this KijiDataRequestBuilder.\n *\n * <p>Creates an object that allows you to specify a set of related columns attached\n * to the same KijiDataRequest that all share the same retrieval properties, like\n * the number of max versions.</p>\n *\n * @return a new KijiDataRequestBuilder.ColumnsDef builder object associated with this\n * data request builder.\n */'public ColumnsDef newColumnsDef() {
checkNotBuilt();
final ColumnsDef c = new ColumnsDef();
mColumnsDefs.add(c);
return c;
} | @Test
public void testNoRedundantColumn() {
KijiDataRequestBuilder builder = KijiDataRequest.builder();
try {
builder.newColumnsDef().add("info", "foo").add("info", "foo");
fail("Should have thrown exception for redundant add");
} catch (IllegalArgumentException ise) {
assertEquals("Duplicate request for column 'info:foo'.", ise.getMessage());
}
} |
["('/**\\\\n * Return a builder for columns associated with this KijiDataRequestBuilder.\\\\n *\\\\n * <p>Creates an object that allows you to specify a set of related columns attached\\\\n * to the same KijiDataRequest that all share the same retrieval properties, like\\\\n * the number of max versions.</p>\\\\n *\\\\n * @return a new KijiDataRequestBuilder.ColumnsDef builder object associated with this\\\\n * data request builder.\\\\n */', '')"] | b'/**\n * Return a builder for columns associated with this KijiDataRequestBuilder.\n *\n * <p>Creates an object that allows you to specify a set of related columns attached\n * to the same KijiDataRequest that all share the same retrieval properties, like\n * the number of max versions.</p>\n *\n * @return a new KijiDataRequestBuilder.ColumnsDef builder object associated with this\n * data request builder.\n */'public ColumnsDef newColumnsDef() {
checkNotBuilt();
final ColumnsDef c = new ColumnsDef();
mColumnsDefs.add(c);
return c;
} | @Test
public void testNoNegativeMaxVer() {
KijiDataRequestBuilder builder = KijiDataRequest.builder();
try {
builder.newColumnsDef().withMaxVersions(-5).addFamily("info");
fail("An exception should have been thrown.");
} catch (IllegalArgumentException iae) {
assertEquals("Maximum number of versions must be strictly positive, but got: -5",
iae.getMessage());
}
} |