auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean validateUuidPresent(CaseInsensitiveString name, Set<String> uuids) { if (isEmpty(uuids)) { return false; } if (!uuids.contains(uuid)) { this.addError(UUID, format("Environment '%s' has an invalid agent uuid '%s'", name, uuid)); } return errors().isEmpty(); }

Target:
public boolean validateUuidPresent(CaseInsensitiveString name, Set<String> uuids) { if (isEmpty(uuids) || !uuids.contains(uuid)) { this.addError(UUID, format("Environment '%s' has an invalid agent uuid '%s'", name, uuid)); } return errors().isEmpty(); }
Source:
public void testUpsertSelect() throws Exception { String tableName = generateUniqueName(); String idxName = "IDX_" + generateUniqueName(); try (Connection conn = DriverManager.getConnection(getUrl(), testProps)) { conn.setAutoCommit(true); createTableAndIndex(conn, tableName, idxName, null, true, 2); assertMetadata(conn, ONE_CELL_PER_COLUMN, NON_ENCODED_QUALIFIERS, tableName); assertMetadata(conn, SINGLE_CELL_ARRAY_WITH_OFFSETS, TWO_BYTE_QUALIFIERS, idxName); conn.createStatement().execute("delete from " + tableName + " where pk1 = 'PK1'"); conn.commit(); String sql = "UPSERT INTO " + idxName + "(\":PK1\",\":INT_PK\",\"0:V1\",\"0:V2\",\"0:V4\") SELECT PK1,INT_PK, V1, V2,V4 FROM " + tableName; conn.createStatement().executeUpdate(sql); conn.commit(); String query = "SELECT \":PK1\" from " + idxName + " ORDER BY \":PK1\""; ResultSet rs = conn.createStatement().executeQuery(query); assertTrue(rs.next()); assertEquals("PK2", rs.getString(1)); assertFalse(rs.next()); } }

Target:
public void testUpsertSelect() throws Exception { String tableName = generateUniqueName(); String idxName = "IDX_" + generateUniqueName(); try (Connection conn = DriverManager.getConnection(getUrl(), testProps)) { conn.setAutoCommit(true); createTableAndIndex(conn, tableName, idxName, null, true, 2); assertMetadata(conn, ONE_CELL_PER_COLUMN, NON_ENCODED_QUALIFIERS, tableName); assertMetadata(conn, SINGLE_CELL_ARRAY_WITH_OFFSETS, TWO_BYTE_QUALIFIERS, idxName); conn.createStatement().execute("delete from " + tableName + " where pk1 = 'PK1'"); conn.commit(); String sql = "UPSERT INTO " + idxName + "(\":PK1\",\":INT_PK\",\"0:V1\",\"0:V2\",\"0:V4\") " + " SELECT PK1,INT_PK, V1, V2,V4 FROM " + tableName; conn.createStatement().executeUpdate(sql); conn.commit(); String query = "SELECT \":PK1\" from " + idxName + " ORDER BY \":PK1\""; ResultSet rs = conn.createStatement().executeQuery(query); assertTrue(rs.next()); assertEquals("PK2", rs.getString(1)); assertFalse(rs.next()); } }
Source:
private void checkVdsNetworkThreshold(VdsStatistics stat) { Integer maxUsedPercentageThreshold = Config.getValue(ConfigValues.LogMaxNetworkUsedThresholdInPercentage); for (VdsNetworkInterface iface : _vds.getInterfaces()) { Double transmitRate = iface.getStatistics().getTransmitRate(); Double receiveRate = iface.getStatistics().getReceiveRate(); if ((transmitRate != null && iface.getStatistics().getTransmitRate().intValue() > maxUsedPercentageThreshold) || (receiveRate != null && iface.getStatistics().getReceiveRate().intValue() > maxUsedPercentageThreshold)) { AuditLogableBase logable = new AuditLogableBase(_vds.getId()); logable.setCustomId(iface.getName().toString()); logable.addCustomValue("HostName", _vds.getName()); logable.addCustomValue("InterfaceName", iface.getName()); logable.addCustomValue("Threshold", maxUsedPercentageThreshold.toString()); logable.addCustomValue("TransmitRate", String.valueOf(transmitRate.intValue())); logable.addCustomValue("ReceiveRate", String.valueOf(receiveRate.intValue())); auditLog(logable, AuditLogType.HOST_INTERFACE_HIGH_NETWORK_USE); } } }

Target:
private void checkVdsNetworkThreshold(VdsStatistics stat) { Integer maxUsedPercentageThreshold = Config.getValue(ConfigValues.LogMaxNetworkUsedThresholdInPercentage); for (VdsNetworkInterface iface : _vds.getInterfaces()) { Double transmitRate = iface.getStatistics().getTransmitRate(); Double receiveRate = iface.getStatistics().getReceiveRate(); if ((transmitRate != null && iface.getStatistics().getTransmitRate().intValue() > maxUsedPercentageThreshold) || (receiveRate != null && iface.getStatistics().getReceiveRate().intValue() > maxUsedPercentageThreshold)) { AuditLogableBase logable = new AuditLogableBase(_vds.getId()); logable.setCustomId(iface.getName()); logable.addCustomValue("HostName", _vds.getName()); logable.addCustomValue("InterfaceName", iface.getName()); logable.addCustomValue("Threshold", maxUsedPercentageThreshold.toString()); logable.addCustomValue("TransmitRate", String.valueOf(transmitRate.intValue())); logable.addCustomValue("ReceiveRate", String.valueOf(receiveRate.intValue())); auditLog(logable, AuditLogType.HOST_INTERFACE_HIGH_NETWORK_USE); } } }
Source:
public void checkStorageProcessorAndHandlerNfsVersionAttributeVersionNotSet(){ _resource.checkStorageProcessorAndHandlerNfsVersionAttribute(storageCmd); assertEquals(NFS_VERSION, _resource._storageNfsVersion); }

Target:
public void checkStorageProcessorAndHandlerNfsVersionAttributeVersionNotSet(){ _resource.checkStorageProcessorAndHandlerNfsVersionAttribute(storageCmd); verify(_resource).examineStorageSubSystemCommandNfsVersion(storageCmd); assertEquals(NFS_VERSION, _resource.storageNfsVersion); }
Source:
public void test() throws InvalidConfigurationException { try { config = tryConfiguration(SOCKET_LOCATION); log.info("Accessing docker with local Unix socket"); } catch (Exception | UnsatisfiedLinkError e) { throw new InvalidConfigurationException("ping failed", e); } }

Target:
public void test() throws InvalidConfigurationException { try { config = tryConfiguration(); log.info("Accessing docker with {}", getDescription()); } catch (Exception | UnsatisfiedLinkError e) { throw new InvalidConfigurationException("ping failed", e); } }
Source:
public void testCompatWarn() throws Exception { Framework.getProperties().setProperty("nuxeo.test.dummyStringProperty", "anotherDummyValue"); boolean devModeSet = Framework.isDevModeSet(); if (!devModeSet) { Framework.getProperties().setProperty(Framework.NUXEO_DEV_SYSTEM_PROP, "true"); } assertEquals(0, Framework.getRuntime().getMessageHandler().getWarnings().size()); hotDeployer.deploy("org.nuxeo.runtime.test.tests:configuration-test-contrib.xml"); assertEquals(0, Framework.getRuntime().getMessageHandler().getWarnings().size()); List<String> caughtEvents = logCaptureResult.getCaughtEventMessages(); assertEquals(1, caughtEvents.size()); String message = "Since version 7.4: Property 'nuxeo.test.dummyStringProperty' should now be contributed to " + "extension point 'org.nuxeo.runtime.ConfigurationService', using target 'configuration'"; assertEquals(message, caughtEvents.get(0)); Framework.getProperties().remove("nuxeo.test.dummyStringProperty"); Framework.getProperties().setProperty(Framework.NUXEO_DEV_SYSTEM_PROP, devModeSet ? "true" : "false"); }

Target:
public void testCompatWarn() throws Exception { Framework.getProperties().setProperty("nuxeo.test.dummyStringProperty", "anotherDummyValue"); assertEquals(0, Framework.getRuntime().getMessageHandler().getWarnings().size()); hotDeployer.deploy("org.nuxeo.runtime.test.tests:configuration-test-contrib.xml"); assertEquals(0, Framework.getRuntime().getMessageHandler().getWarnings().size()); List<String> caughtEvents = logCaptureResult.getCaughtEventMessages(); assertEquals(1, caughtEvents.size()); String message = "Since version 7.4: Property 'nuxeo.test.dummyStringProperty' should now be contributed to " + "extension point 'org.nuxeo.runtime.ConfigurationService', using target 'configuration'"; assertEquals(message, caughtEvents.get(0)); Framework.getProperties().remove("nuxeo.test.dummyStringProperty"); }
Source:
public Function1D<NormalFunctionData, Double> getPriceFunction(EuropeanVanillaOption option) { ArgChecker.notNull(option, "option"); double strike = option.getStrike(); double t = option.getTimeToExpiry(); return new Function1D<NormalFunctionData, Double>() { @SuppressWarnings("synthetic-access") @Override public Double evaluate(NormalFunctionData data) { ArgChecker.notNull(data, "data"); double forward = data.getForward(); double numeraire = data.getNumeraire(); double sigma = data.getNormalVolatility(); double sigmaRootT = sigma * Math.sqrt(t); int sign = option.isCall() ? 1 : -1; if (sigmaRootT < 1e-16) { double x = sign * (forward - strike); return (x > 0 ? numeraire * x : 0.0); } double arg = sign * (forward - strike) / sigmaRootT; return numeraire * (sign * (forward - strike) * NORMAL.getCDF(arg) + sigmaRootT * NORMAL.getPDF(arg)); } }; }

Target:
public Function1D<NormalFunctionData, Double> getPriceFunction(EuropeanVanillaOption option) { ArgChecker.notNull(option, "option"); double strike = option.getStrike(); double t = option.getTimeToExpiry(); return new Function1D<NormalFunctionData, Double>() { @SuppressWarnings("synthetic-access") @Override public Double evaluate(NormalFunctionData data) { ArgChecker.notNull(data, "data"); double forward = data.getForward(); double numeraire = data.getNumeraire(); double sigma = data.getNormalVolatility(); double sigmaRootT = sigma * Math.sqrt(t); int sign = option.isCall() ? 1 : -1; if (sigmaRootT < NEAR_ZERO) { double x = sign * (forward - strike); return (x > 0 ? numeraire * x : 0.0); } double arg = sign * (forward - strike) / sigmaRootT; return numeraire * (sign * (forward - strike) * NORMAL.getCDF(arg) + sigmaRootT * NORMAL.getPDF(arg)); } }; }
Source:
protected boolean connectLunDisks(Guid hostId) { if (getVm().getDiskMap().isEmpty()) { vmHandler.updateDisksFromDb(getVm()); } List<LunDisk> lunDisks = DisksFilter.filterLunDisks(getVm().getDiskMap().values()); Map<StorageType, List<StorageServerConnections>> connectionsByType = lunDisks.stream() .flatMap(d -> storageServerConnectionDao.getAllForLun(d.getLun().getLUNId()).stream()) .distinct() .collect(groupingBy(StorageServerConnections::getStorageType, toList())); return connectionsByType.entrySet().stream() .map((entry) -> runVdsCommand( VDSCommandType.ConnectStorageServer, new StorageServerConnectionManagementVDSParameters( hostId, getStoragePoolId(), entry.getKey(), entry.getValue()))) .noneMatch(vdsReturnValue -> !vdsReturnValue.getSucceeded()); }

Target:
protected boolean connectLunDisks(Guid hostId) { if (getVm().getDiskMap().isEmpty()) { vmHandler.updateDisksFromDb(getVm()); } List<LunDisk> lunDisks = DisksFilter.filterLunDisks(getVm().getDiskMap().values()); Map<StorageType, List<StorageServerConnections>> connectionsByType = lunDisks.stream() .flatMap(d -> storageServerConnectionDao.getAllForLun(d.getLun().getLUNId()).stream()) .distinct() .collect(groupingBy(StorageServerConnections::getStorageType, toList())); return connectionsByType.entrySet().stream() .map(entry -> runVdsCommand( VDSCommandType.ConnectStorageServer, new StorageServerConnectionManagementVDSParameters( hostId, getStoragePoolId(), entry.getKey(), entry.getValue()))) .noneMatch(vdsReturnValue -> !vdsReturnValue.getSucceeded()); }
Source:
public void iNavigateTo(String nameToken) { if (nameToken.equals(NameTokens.LOGIN)) { applicationPage.navigateToNotLoggedIn(nameToken); } else { applicationPage.navigateToWithMenu(nameToken); } }

Target:
public void iNavigateTo(String nameToken) { if (NameTokens.LOGIN.equals(nameToken)) { applicationPage.navigateToNotLoggedIn(nameToken); } else { applicationPage.navigateToWithMenu(nameToken); } }
Source:
public boolean test(final String rawConfig) { try { Map<String, Object> parsedConfig = MAPPER.readValue(rawConfig, new TypeReference<Map<String, Object>>() {}); for (Map<String, Object> node : (List<Map<String, Object>>) parsedConfig.get("nodesExt")) { final Map<String, Integer> nodeServices = (Map<String, Integer>) node.get("services"); for (CouchbaseService enabledService : enabledServices) { boolean found = false; for (String nodeService : nodeServices.keySet()) { if (nodeService.startsWith(enabledService.getIdentifier())) { found = true; } } if (!found) { logger().trace("Service not yet part of config, retrying.", enabledService); return false; } } } return true; } catch (IOException ex) { logger().error("Unable to parse response {}", rawConfig); return false; } }

Target:
public boolean test(final String rawConfig) { try { for (JsonNode node : MAPPER.readTree(rawConfig).at("/nodesExt")) { for (CouchbaseService enabledService : enabledServices) { boolean found = false; Iterator<String> fieldNames = node.get("services").fieldNames(); while (fieldNames.hasNext()) { if (fieldNames.next().startsWith(enabledService.getIdentifier())) { found = true; } } if (!found) { logger().trace("Service not yet part of config, retrying.", enabledService); return false; } } } return true; } catch (IOException ex) { logger().error("Unable to parse response: {}", rawConfig, ex); return false; } }
Source:
private void pulseSingleTickMap() { ItemTable itemTable = ItemTable.instance(); HashMap<Location, Long> pulsesToRemove = new HashMap<Location, Long>(); getSingleTickMap().entrySet().stream().filter(entry -> entry.getValue() - worldAge <= 0).forEach(entry -> { GlowBlock block = getBlockAt(entry.getKey()); BlockType notifyType = itemTable.getBlock(block.getTypeId()); if (notifyType != null) notifyType.receivePulse(block); pulsesToRemove.put(entry.getKey(), entry.getValue()); }); for (Map.Entry<Location, Long> entry : pulsesToRemove.entrySet()) { getSingleTickMap().remove(entry.getKey(), entry.getValue()); } }

Target:
private void pulseSingleTickMap() { ItemTable itemTable = ItemTable.instance(); getSingleTickMap().entrySet().stream().filter(entry -> entry.getValue() - worldAge <= 0).forEach(entry -> { GlowBlock block = getBlockAt(entry.getKey()); BlockType notifyType = itemTable.getBlock(block.getTypeId()); if (notifyType != null) notifyType.receivePulse(block); getSingleTickMap().remove(entry.getKey(), entry.getValue()); }); }
Source:
public void test1_check_login_saml() throws InterruptedException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Log_OC.i(LOG_TAG, "Test Check Login SAML Start"); SystemClock.sleep(WAIT_INITIAL); onView(withId(R.id.buttonOK)).check(matches(not(isEnabled()))); onView(withId(R.id.hostUrlInput)).perform(replaceText(testServerURL)); onView(withId(R.id.thumbnail)).perform(click()); if (servertype == ServerType.NON_TRUSTED) { SystemClock.sleep(WAIT_CONNECTION); onView(withId(R.id.ok)).perform(click()); } SystemClock.sleep(WAIT_CONNECTION); onView(withId(R.id.server_status_text)).check(matches(withText(R.string.auth_secure_connection))); onView(withId(R.id.buttonOK)).perform(click()); SystemClock.sleep(WAIT_CONNECTION); onWebView().withElement(findElement(Locator.NAME, webViewUsernameId)).perform(webKeys(testUser)); onWebView().withElement(findElement(Locator.NAME, webViewPasswordId)).perform(webKeys(testPassword)); onWebView().withElement(findElement(Locator.XPATH, webViewSubmitXPath)).perform(webClick()); SystemClock.sleep(WAIT_LOGIN); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) assertTrue(ERROR_MESSAGE, mActivityRule.getActivity().isDestroyed()); else { Field f = Activity.class.getDeclaredField(RESULT_CODE); f.setAccessible(true); int mResultCode = f.getInt(mActivityRule.getActivity()); assertTrue(ERROR_MESSAGE, mResultCode == Activity.RESULT_OK); } Log_OC.i(LOG_TAG, "Test Check Login SAML Passed"); }

Target:
public void test1_check_login_saml() throws InterruptedException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Log_OC.i(LOG_TAG, "Test Check Login SAML Start"); SystemClock.sleep(WAIT_INITIAL_MS); onView(withId(R.id.buttonOK)).check(matches(not(isEnabled()))); onView(withId(R.id.hostUrlInput)).perform(replaceText(testServerURL)); onView(withId(R.id.thumbnail)).perform(click()); if (servertype == ServerType.NON_TRUSTED) { SystemClock.sleep(WAIT_CONNECTION_MS); onView(withId(R.id.ok)).perform(click()); } SystemClock.sleep(WAIT_CONNECTION_MS); onView(withId(R.id.server_status_text)).check(matches(withText(R.string.auth_secure_connection))); onView(withId(R.id.buttonOK)).perform(click()); SystemClock.sleep(WAIT_CONNECTION_MS); onWebView().withElement(findElement(Locator.NAME, webViewUsernameId)).perform(webKeys(testUser)); onWebView().withElement(findElement(Locator.NAME, webViewPasswordId)).perform(webKeys(testPassword)); onWebView().withElement(findElement(Locator.XPATH, webViewSubmitXPath)).perform(webClick()); SystemClock.sleep(WAIT_LOGIN_MS); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) assertTrue(ERROR_MESSAGE, mActivityRule.getActivity().isDestroyed()); else { Field f = Activity.class.getDeclaredField(RESULT_CODE); f.setAccessible(true); int mResultCode = f.getInt(mActivityRule.getActivity()); assertTrue(ERROR_MESSAGE, mResultCode == Activity.RESULT_OK); } Log_OC.i(LOG_TAG, "Test Check Login SAML Passed"); }
Source:
public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) { XmlStringBuilder xml = new XmlStringBuilder(this).rightAngleBracket(); for (ExtensionElement element : payloadElements) { xml.append(element); } return xml.closeElement(this); }

Target:
public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) { XmlStringBuilder xml = new XmlStringBuilder(this).rightAngleBracket(); xml.append(payloadElements); return xml.closeElement(this); }
Source:
public static String createAbsolute(String path){ File curFile = new File(path); if(!curFile.isAbsolute()){ path = currPath + '/' + path; } return path; }

Target:
public static String createAbsolute(String path) { File curFile = new File(path); if (!curFile.isAbsolute()) { path = currPath + File.separator + path; } return path; }
Source:
private DeleteRequest(LwM2mPath target) { super(target); if (!target.isObjectInstance()) throw new InvalidRequestException("Invalid path %s : Only object instance can be delete.", target); }

Target:
private DeleteRequest(LwM2mPath target) { super(target); if (!target.isObjectInstance()) throw new InvalidRequestException("Invalid path %s : Only object instances can be delete", target); }
Source:
public void testMenuStyles() { Assert.assertEquals("Root Menu Style", "grid", mApp.getSession().getPlatform().getMenuDisplayStyle("root")); Assert.assertEquals("Common Menu Style", "list", mApp.getSession().getPlatform().getMenuDisplayStyle("m1")); Assert.assertEquals("Disperate Menu Style", null, mApp.getSession().getPlatform().getMenuDisplayStyle("m2")); }

Target:
public void testMenuStyles() { Assert.assertEquals("Root Menu Style", "grid", mApp.getSession().getPlatform().getMenuDisplayStyle("root")); Assert.assertEquals("Common Menu Style", "list", mApp.getSession().getPlatform().getMenuDisplayStyle("m1")); Assert.assertEquals("Disperate Menu Style", null, mApp.getSession().getPlatform().getMenuDisplayStyle("m2")); Assert.assertEquals("Empty Menu", null, mApp.getSession().getPlatform().getMenuDisplayStyle("m0")); Assert.assertEquals("Specific override", "grid", mApp.getSession().getPlatform().getMenuDisplayStyle("m3")); }
Source:
public void onReport() { platformService.showDocument(clientProperties.getLinks().get("linksModerationReport")); }

Target:
public void onReport() { platformService.showDocument(clientProperties.getWebsite().getReportUrl()); }
Source:
synchronized void subscribe(final String topic) throws MqttException { synchronized (subscribeLock) { if (!started) { client = new MqttClient(brokerURI, clientId); client.connect(); client.setCallback(this); started = true; } client.subscribe(topic); } }

Target:
void subscribe(final String topic) throws MqttException { synchronized (subscribeLock) { if (!started) { client = new MqttClient(brokerURI, clientId); client.connect(); client.setCallback(this); started = true; } client.subscribe(topic); } }
Source:
public synchronized void commit() { try { switch (state) { case EMPTY: break; case SHARED_OPERATION_BUFFERED: Optional<String> doAsUser = getImpersonationUser(); if (doAsUser.isPresent()) { hdfsEnvironment.doAs(doAsUser.get(), () -> commitShared()); } else { commitShared(); } break; case EXCLUSIVE_OPERATION_BUFFERED: requireNonNull(bufferedExclusiveOperation, "bufferedExclusiveOperation is null"); bufferedExclusiveOperation.execute(delegate, hdfsEnvironment); break; case FINISHED: throw new IllegalStateException("Tried to commit buffered metastore operations after transaction has been committed/aborted"); default: throw new IllegalStateException("Unknown state"); } } finally { state = State.FINISHED; } }

Target:
public synchronized void commit() { try { switch (state) { case EMPTY: break; case SHARED_OPERATION_BUFFERED: commitShared(); break; case EXCLUSIVE_OPERATION_BUFFERED: requireNonNull(bufferedExclusiveOperation, "bufferedExclusiveOperation is null"); bufferedExclusiveOperation.execute(delegate, hdfsEnvironment, metastoreAuthentication); break; case FINISHED: throw new IllegalStateException("Tried to commit buffered metastore operations after transaction has been committed/aborted"); default: throw new IllegalStateException("Unknown state"); } } finally { state = State.FINISHED; } }
Source:
protected boolean isHandledByDirectEditor(final EObject element) { return DirectEditorEditingSupport.getConfiguration(element) != null; }

Target:
protected boolean isHandledByDirectEditor(final EObject element) { return null != DirectEditorEditingSupport.getConfiguration(element); }
Source:
public void removeLun(LUNs lun) { if (lun.getvolume_group_id().isEmpty()) { DbFacade.getInstance().getLunDao().remove(lun.getLUN_id()); } for (storage_server_connections connection : filterConnectionsUsedByOthers(lun.getLunConnections(), "", lun.getLUN_id())) { DbFacade.getInstance().getStorageServerConnectionDao().remove(connection.getid()); } }

Target:
public void removeLun(LUNs lun) { if (lun.getvolume_group_id().isEmpty()) { DbFacade.getInstance().getLunDao().remove(lun.getLUN_id()); for (storage_server_connections connection : filterConnectionsUsedByOthers(lun.getLunConnections(), "", lun.getLUN_id())) { DbFacade.getInstance().getStorageServerConnectionDao().remove(connection.getid()); } } }
Source:
static String createSerialized(boolean isFooterKey, String kmsInstanceID, String kmsInstanceURL, String masterKeyID, boolean isDoubleWrapped, String kekID, String encodedWrappedKEK, String encodedWrappedDEK, boolean isInternalStorage) { Map<String, String> keyMaterialMap = new HashMap<String, String>(10); keyMaterialMap.put(KEY_MATERIAL_TYPE_FIELD, KEY_MATERIAL_TYPE); if (isInternalStorage) { keyMaterialMap.put(KEY_MATERIAL_INTERNAL_STORAGE_FIELD, "true"); } keyMaterialMap.put(IS_FOOTER_KEY_FIELD, Boolean.toString(isFooterKey)); if (isFooterKey) { keyMaterialMap.put(KMS_INSTANCE_ID_FIELD, kmsInstanceID); keyMaterialMap.put(KMS_INSTANCE_URL_FIELD, kmsInstanceURL); } keyMaterialMap.put(MASTER_KEY_ID_FIELD, masterKeyID); keyMaterialMap.put(WRAPPED_DEK_FIELD, encodedWrappedDEK); keyMaterialMap.put(DOUBLE_WRAPPING_FIELD, Boolean.toString(isDoubleWrapped)); if (isDoubleWrapped) { keyMaterialMap.put(KEK_ID_FIELD, kekID); keyMaterialMap.put(WRAPPED_KEK_FIELD, encodedWrappedKEK); } try { return OBJECT_MAPPER.writeValueAsString(keyMaterialMap); } catch (IOException e) { throw new ParquetCryptoRuntimeException("Failed to serialize key material", e); } }

Target:
static String createSerialized(boolean isFooterKey, String kmsInstanceID, String kmsInstanceURL, String masterKeyID, boolean isDoubleWrapped, String kekID, String encodedWrappedKEK, String encodedWrappedDEK, boolean isInternalStorage) { Map<String, Object> keyMaterialMap = new HashMap<String, Object>(10); keyMaterialMap.put(KEY_MATERIAL_TYPE_FIELD, KEY_MATERIAL_TYPE1); if (isInternalStorage) { keyMaterialMap.put(KeyMetadata.KEY_MATERIAL_INTERNAL_STORAGE_FIELD, Boolean.TRUE); } keyMaterialMap.put(IS_FOOTER_KEY_FIELD, Boolean.valueOf(isFooterKey)); if (isFooterKey) { keyMaterialMap.put(KMS_INSTANCE_ID_FIELD, kmsInstanceID); keyMaterialMap.put(KMS_INSTANCE_URL_FIELD, kmsInstanceURL); } keyMaterialMap.put(MASTER_KEY_ID_FIELD, masterKeyID); keyMaterialMap.put(WRAPPED_DEK_FIELD, encodedWrappedDEK); keyMaterialMap.put(DOUBLE_WRAPPING_FIELD, Boolean.valueOf(isDoubleWrapped)); if (isDoubleWrapped) { keyMaterialMap.put(KEK_ID_FIELD, kekID); keyMaterialMap.put(WRAPPED_KEK_FIELD, encodedWrappedKEK); } try { return OBJECT_MAPPER.writeValueAsString(keyMaterialMap); } catch (IOException e) { throw new ParquetCryptoRuntimeException("Failed to serialize key material", e); } }
Source:
public void visitNode(Tree tree) { if (check.isOneSpaceBetweenKeywordAndNextToken && tree.is(CONTROL_STRUCTURES)) { checkSpaceBetweenKeywordAndNextNode(new TokenVisitor(tree), tree); } if (check.isOneSpaceAfterForLoopSemicolon && tree.is(Kind.FOR_STATEMENT)) { checkSpaceForStatement(tree); } if (check.isSpaceForeachStatement && tree.is(Kind.FOREACH_STATEMENT)) { ForEachStatementTree forloop = (ForEachStatementTree) tree; checkForeachStatement(new TokenVisitor(tree), forloop, forloop.asToken(), forloop.doubleArrowToken()); } }

Target:
public void visitNode(Tree tree) { if (check.isOneSpaceBetweenKeywordAndNextToken) { checkSpaceBetweenKeywordAndNextNode(new TokenVisitor(tree), tree); } if (check.isOneSpaceAfterForLoopSemicolon && tree.is(Kind.FOR_STATEMENT)) { checkSpaceForStatement(tree); } if (check.isSpaceForeachStatement && tree.is(Kind.FOREACH_STATEMENT)) { ForEachStatementTree foreachLoop = (ForEachStatementTree) tree; checkForeachStatement(new TokenVisitor(tree), foreachLoop, foreachLoop.asToken(), foreachLoop.doubleArrowToken()); } }
Source:
private static void scanFile(JavaIssueFilter filter) { List<JavaCheck> visitors = Lists.<JavaCheck>newArrayList(filter); VisitorsBridgeForTests visitorsBridge = new VisitorsBridgeForTests(visitors, Lists.<File>newLinkedList(), null); JavaAstScanner.scanSingleFileForTests(new File("src/test/files/filters/AnyRuleIssueFilter.java"), visitorsBridge); }

Target:
private static void scanFile(JavaIssueFilter filter) { VisitorsBridgeForTests visitorsBridge = new VisitorsBridgeForTests(Collections.singletonList(filter), Collections.emptyList(), null); JavaAstScanner.scanSingleFileForTests(new File("src/test/files/filters/AnyRuleIssueFilter.java"), visitorsBridge); }
Source:
public void checkConfigFile(File configFile, File serverDir) { try { ServerFeature servUtil = getServerFeatureUtil(); Set<String> features = servUtil.getServerFeatures(serverDir); if (features != null) { features.removeAll(existingFeatures); if (!features.isEmpty()) { log.info("Configuration features have been added"); Element[] featureElems = new Element[features.size() + 1]; int i = 0; for (String f : features) { featureElems[i] = element(name("feature"), f); i++; } featureElems[i] = element(name("acceptLicense"), "true"); runLibertyMojoInstallFeature(element(name("features"), featureElems)); this.existingFeatures.addAll(features); } } } catch (MojoExecutionException e) { log.error("Failed to install features from configuration file", e); } }

Target:
public void checkConfigFile(File configFile, File serverDir) { try { ServerFeature servUtil = getServerFeatureUtil(); Set<String> features = servUtil.getServerFeatures(serverDir); if (features != null) { features.removeAll(existingFeatures); if (!features.isEmpty()) { log.info("Configuration features have been added"); Element[] featureElems = new Element[features.size() + 1]; featureElems[0] = element(name("acceptLicense"), "true"); String[] values = features.toArray(new String[features.size()]); for (int i = 0; i < features.size(); i++) { featureElems[i+1] = element(name("feature"), values[i]); } runLibertyMojoInstallFeature(element(name("features"), featureElems)); this.existingFeatures.addAll(features); } } } catch (MojoExecutionException e) { log.error("Failed to install features from configuration file", e); } }
Source:
public void getNearestRail() { minX = NukkitMath.floorFloat(this.boundingBox.minX); minY = NukkitMath.floorFloat(this.boundingBox.minY); minZ = NukkitMath.floorFloat(this.boundingBox.minZ); maxX = NukkitMath.ceilFloat(this.boundingBox.maxX); maxY = NukkitMath.ceilFloat(this.boundingBox.maxY); maxZ = NukkitMath.ceilFloat(this.boundingBox.maxZ); rails = []; for (z = minZ; z <= maxZ; ++z) { for (x = minX; x <= maxX; ++x) { for (y = minY; y <= maxY; ++y) { Block block = this.level.getBlock(this.temporalVector.setComponents(x, y, z)); if (block.getId(), {Block::RAIL, Block::ACTIVATOR_RAIL, Block::DETECTOR_RAIL, Block::POWERED_RAIL}) rails[] = block; } } } minDistance = PHP_INT_MAX; nearestRail = null; foreach (rails as rail) { dis = this.distance(rail); if (dis < minDistance) { nearestRail = rail; minDistance = dis; } } return nearestRail; }

Target:
public void getNearestRail() { minX = NukkitMath.floorFloat(this.boundingBox.minX); minY = NukkitMath.floorFloat(this.boundingBox.minY); minZ = NukkitMath.floorFloat(this.boundingBox.minZ); maxX = NukkitMath.ceilFloat(this.boundingBox.maxX); maxY = NukkitMath.ceilFloat(this.boundingBox.maxY); maxZ = NukkitMath.ceilFloat(this.boundingBox.maxZ); rails = []; for (z = minZ; z <= maxZ; ++z) { for (x = minX; x <= maxX; ++x) { for (y = minY; y <= maxY; ++y) { Block block = this.level.getBlock(this.temporalVector.setComponents(x, y, z)); if (block.getId(), {Block.RAIL, Block.ACTIVATOR_RAIL, Block.DETECTOR_RAIL, Block.POWERED_RAIL}) rails[] = block; } } } minDistance = Integer.MAX_VALUE; nearestRail = null; foreach (rails as rail) { dis = this.distance(rail); if (dis < minDistance) { nearestRail = rail; minDistance = dis; } } return nearestRail; }
Source:
private void initializePattern(final String pattern) { final String[] split = pattern.split(Pattern.quote("*"), -1); final StringBuilder escapedPattern = new StringBuilder(Pattern.quote(split[0])); for (int i = 1; i < split.length; i++) { String quoted = Pattern.quote(split[i]); escapedPattern.append("(.+)").append(quoted); } final String regex = "^" + escapedPattern.toString() + "$"; this.patternStr = regex; this.pattern = Pattern.compile(regex); }

Target:
private void initializePattern(final String pattern) { final String[] split = pattern.split(Pattern.quote("*"), -1); final StringBuilder escapedPattern = new StringBuilder(Pattern.quote(split[0])); for (int i = 1; i < split.length; i++) { String quoted = Pattern.quote(split[i]); escapedPattern.append("([^.]*)").append(quoted); } final String regex = "^" + escapedPattern.toString() + "$"; this.patternStr = regex; this.pattern = Pattern.compile(regex); }
Source:
public boolean acquireReadLock(String ownerId) { try (Handle handle = rdbi.open()) { final MultiReadSingleWriteLockDAO dao = handle.attach(MultiReadSingleWriteLockDAO.class); while (true) { final int acquiredLock = dao.acquireReadLock(writeLockKey, readLockKey, ownerId, Instant.now().plus(Duration.millis(readTimeoutMillis)).getMillis()); if (acquiredLock > 0) { return true; } Thread.sleep(250); } } catch (InterruptedException e) { throw new RuntimeException(e); } }

Target:
public boolean acquireReadLock(String ownerId) { try (Handle handle = rdbi.open()) { final MultiReadSingleWriteLockDAO dao = handle.attach(MultiReadSingleWriteLockDAO.class); while (true) { final int acquiredLock = dao.acquireReadLock(writeLockKey, readLockKey, ownerId, Instant.now().plus(readTimeoutMillis, ChronoUnit.MILLIS).toEpochMilli()); if (acquiredLock > 0) { return true; } Thread.sleep(250); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return false; }
Source:
public void testHigherPriorityRequestPreemptedByAnother() throws Exception { ZKDistributedNonblockingLock lock = new ZKDistributedNonblockingLock(_participantScope, ZK_ADDR, 3600000L, "original " + "lock", "original_lock", 1, 1000, 25000, false, _lockListener); ZKDistributedNonblockingLock higherLock = new ZKDistributedNonblockingLock(_participantScope, ZK_ADDR, 3600000L, "higher priority lock", "high_lock", 2, 30000, 10000, false, createLockListener()); ZKDistributedNonblockingLock highestLock = new ZKDistributedNonblockingLock(_participantScope , ZK_ADDR, 3600000L, "highest priority lock", "highest_lock", 3, 30000, 20000, false, createLockListener()); Thread t = new Thread() { @Override public void run() { lock.tryLock(); } }; Thread t_highest = new Thread() { @Override public void run() { highestLock.tryLock(); } }; t.start(); t.join(); Assert.assertTrue(lock.isCurrentOwner()); LockHelper lockHelper = new LockHelper(higherLock); Thread t_higher = new Thread(lockHelper); t_higher.start(); Thread.sleep(1000); boolean higherResult = lockHelper.getResult(); Assert.assertFalse(higherLock.isCurrentOwner()); Assert.assertFalse(higherResult); t_highest.start(); t_highest.join(); Assert.assertTrue(highestLock.isCurrentOwner()); _isCleanupNotified.set(false); highestLock.unlock(); highestLock.close(); higherLock.close(); lock.close(); }

Target:
public void testHigherPriorityRequestPreemptedByAnother() throws Exception { ZKDistributedNonblockingLock lock = createLockWithConfig(); ZKDistributedNonblockingLock.Builder lockBuilder = new ZKDistributedNonblockingLock.Builder(); lockBuilder.setLockScope(_participantScope).setZkAddress(ZK_ADDR).setTimeout(3600000L) .setLockMsg("higher priority lock").setUserId("high_lock").setPriority(2) .setWaitingTimeout(30000).setCleanupTimeout(10000).setIsForceful(false) .setLockListener(createLockListener()); ZKDistributedNonblockingLock higherLock = lockBuilder.build(); ZKDistributedNonblockingLock.Builder highestLockBuilder = new ZKDistributedNonblockingLock.Builder(); highestLockBuilder.setLockScope(_participantScope).setZkAddress(ZK_ADDR).setTimeout(3600000L) .setLockMsg("highest priority lock").setUserId("highest_lock").setPriority(3) .setWaitingTimeout(30000).setCleanupTimeout(10000).setIsForceful(false) .setLockListener(createLockListener()); ZKDistributedNonblockingLock highestLock = highestLockBuilder.build(); Thread t = new Thread() { @Override public void run() { lock.tryLock(); } }; Thread t_highest = new Thread() { @Override public void run() { highestLock.tryLock(); } }; t.start(); t.join(); Assert.assertTrue(lock.isCurrentOwner()); LockHelper lockHelper = new LockHelper(higherLock); Thread t_higher = new Thread(lockHelper); t_higher.start(); boolean higherResult = TestHelper.verify(() -> { return lockHelper.getResult(); }, 1000); Assert.assertFalse(higherResult); Assert.assertFalse(higherLock.isCurrentOwner()); t_highest.start(); t_highest.join(); Assert.assertTrue(highestLock.isCurrentOwner()); _isCleanupNotified.set(false); highestLock.unlock(); highestLock.close(); higherLock.close(); lock.close(); }
Source:
private void checkHandlerAnnotation(String name, List<String> foundClasses) throws IOException { if (name.endsWith(CLASS_SUFFIX)) { int end = name.lastIndexOf(CLASS_SUFFIX); String clazzPath = name.substring(0, end); String clazzName = pathToName(clazzPath); try { Class<?> clazz = classForName(clazzName); for (Annotation a : clazz.getAnnotations()) { if (a.annotationType().getName().contains(SCHEMA_HANDLER_JAVA_ANNOTATION)) { foundClasses.add(clazzName); return; } } } catch (ClassNotFoundException e) { throw new IOException("Failed to load class while scanning classes", e); } catch (Exception | Error e) { getProject().getLogger() .info("Unexpected exceptions or errors found during scanning class, ok to skip", e); } } }

Target:
private void checkHandlerAnnotation(String name, List<String> foundClasses) throws IOException { if (name.endsWith(CLASS_SUFFIX)) { int end = name.lastIndexOf(CLASS_SUFFIX); String clazzPath = name.substring(0, end); String clazzName = pathToName(clazzPath); try { Class<?> clazz = classForName(clazzName); for (Annotation a : clazz.getAnnotations()) { if (a.annotationType().getName().contains(SCHEMA_HANDLER_JAVA_ANNOTATION)) { foundClasses.add(clazzName); return; } } } catch (ClassNotFoundException e) { throw new IOException("Failed to load class while scanning classes", e); } } }
Source:
protected List<TaskData> doProcess(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, BugzillaRestException { BufferedInputStream is = new BufferedInputStream(response.getResponseEntityAsStream()); InputStreamReader in = new InputStreamReader(is); throwExeptionIfRestError(is, in); return parseFromJson(in); }

Target:
protected List<TaskData> doProcess(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, BugzillaRestException { InputStream is = response.getResponseEntityAsStream(); InputStreamReader in = new InputStreamReader(is); return parseFromJson(in); }
Source:
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation, Supplier<Mono<T>> activationOperation, Consumer<Poller<T>> cancelOperation) { if (pollInterval == null || pollInterval.compareTo(Duration.ZERO) <= 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Null, negative or zero value for poll interval is not allowed.")); } if (pollOperation == null) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Null value for poll operation is not allowed.")); } this.pollInterval = pollInterval; this.pollOperation = pollOperation; final Mono<T> onActivation = activationOperation == null ? Mono.empty() : activationOperation.get().map(response -> { pollResponse.set(new PollResponse<>(OperationStatus.NOT_STARTED, response)); return response; }); this.fluxHandle = asyncPollRequestWithDelay() .flux() .repeat() .takeUntil(pollResponse -> hasCompleted()) .share() .delaySubscription(onActivation); this.fluxDisposable = fluxHandle.subscribe(); this.autoPollingEnabled = true; this.cancelOperation = cancelOperation; }

Target:
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation, Supplier<Mono<T>> activationOperation, Consumer<Poller<T>> cancelOperation) { Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); if (pollInterval.compareTo(Duration.ZERO) <= 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'pollInterval' is not allowed.")); } this.pollInterval = pollInterval; this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null."); final Mono<T> onActivation = activationOperation == null ? Mono.empty() : activationOperation.get().map(response -> { this.pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, response); return response; }); this.fluxHandle = asyncPollRequestWithDelay() .flux() .repeat() .takeUntil(pollResponse -> hasCompleted()) .share() .delaySubscription(onActivation); this.fluxDisposable = fluxHandle.subscribe(); this.autoPollingEnabled = true; this.cancelOperation = cancelOperation; }
Source:
private boolean canPerform(ApprovalCategory.Id actionId, short level) { final Set<AccountGroup.Id> groups = getCurrentUser().getEffectiveGroups(); int val = Integer.MIN_VALUE; List<RefRight> allRights = new ArrayList<RefRight>(); allRights.addAll(getLocalRights()); if (actionId.canInheritFromWildProject()) { allRights.addAll(getInheritedRights()); } List<RefRight> actionRights = new ArrayList<RefRight>(); for (final RefRight right : allRights) { if (right.getApprovalCategoryId().equals(actionId)) { actionRights.add(right); } } Collections.sort(actionRights, new RefRight.RefPatternOrder()); List<RefRight> mostSpecific = filterMostSpecific(actionRights); for (RefRight right : mostSpecific) { if (groups.contains(right.getAccountGroupId())) { if (val < 0 && right.getMaxValue() > 0) { val = right.getMaxValue(); } else { val = Math.max(right.getMaxValue(), val); } } } return val >= level; }

Target:
private boolean canPerform(ApprovalCategory.Id actionId, short level) { final Set<AccountGroup.Id> groups = getCurrentUser().getEffectiveGroups(); int val = Integer.MIN_VALUE; List<RefRight> allRights = new ArrayList<RefRight>(); allRights.addAll(getLocalRights(actionId)); if (actionId.canInheritFromWildProject()) { allRights.addAll(getInheritedRights(actionId)); } Collections.sort(allRights, RefRight.REF_PATTERN_ORDER); for (RefRight right : filterMostSpecific(allRights)) { if (groups.contains(right.getAccountGroupId())) { if (val < 0 && right.getMaxValue() > 0) { val = right.getMaxValue(); } else { val = Math.max(right.getMaxValue(), val); } } } return val >= level; }
Source:
@Test public void testInvalidParse() { final String urn = "urn:ogcx:def:CRS:EPSG:6.8:4326"; try { URN_Parser.buildParser(urn); fail(); } catch (NoSuchAuthorityCodeException e) { assertEquals(urn, e.getAuthorityCode()); } }

Target:
public void testInvalidParse() { final String urn = "urn:ogcx:def:CRS:EPSG:6.8:4326"; try { URN_Parser.buildParser(urn); fail(); } catch (NoSuchAuthorityCodeException e) { assertEquals(urn, e.getAuthorityCode()); } }
Source:
public Config<T> withProjectionString(String p) { return new Config<T>(this.klass, this.filterPredicate, Objects.requireNonNull(p, "projectionString"), this.strictProjectionString); }

Target:
public Config<T> withProjectionString(String p) { return new Config<T>(this.klass, this.filterPredicate, Objects.requireNonNull(p, "projectionString cannot be null"), this.strictProjectionString); }
Source:
public <T> QueryRunner<T> getQueryRunnerForIntervals(final Query<T> query, final Iterable<Interval> intervals) { if (conglomerate == null) { throw new IllegalStateException("Don't query me, bro."); } final Iterable<SegmentDescriptor> specs = FunctionalIterable .create(intervals) .transformCat( new Function<Interval, Iterable<TimelineObjectHolder<String, Sink>>>() { @Override public Iterable<TimelineObjectHolder<String, Sink>> apply(final Interval interval) { return sinkTimeline.lookup(interval); } } ) .transformCat( new Function<TimelineObjectHolder<String, Sink>, Iterable<SegmentDescriptor>>() { @Override public Iterable<SegmentDescriptor> apply(final TimelineObjectHolder<String, Sink> holder) { return FunctionalIterable .create(holder.getObject()) .transform( new Function<PartitionChunk<Sink>, SegmentDescriptor>() { @Override public SegmentDescriptor apply(final PartitionChunk<Sink> chunk) { return new SegmentDescriptor( holder.getInterval(), holder.getVersion(), chunk.getChunkNumber() ); } } ); } } ); return getQueryRunnerForSegments(query, specs); }

Target:
public <T> QueryRunner<T> getQueryRunnerForIntervals(final Query<T> query, final Iterable<Interval> intervals) { final Iterable<SegmentDescriptor> specs = FunctionalIterable .create(intervals) .transformCat( new Function<Interval, Iterable<TimelineObjectHolder<String, Sink>>>() { @Override public Iterable<TimelineObjectHolder<String, Sink>> apply(final Interval interval) { return sinkTimeline.lookup(interval); } } ) .transformCat( new Function<TimelineObjectHolder<String, Sink>, Iterable<SegmentDescriptor>>() { @Override public Iterable<SegmentDescriptor> apply(final TimelineObjectHolder<String, Sink> holder) { return FunctionalIterable .create(holder.getObject()) .transform( new Function<PartitionChunk<Sink>, SegmentDescriptor>() { @Override public SegmentDescriptor apply(final PartitionChunk<Sink> chunk) { return new SegmentDescriptor( holder.getInterval(), holder.getVersion(), chunk.getChunkNumber() ); } } ); } } ); return getQueryRunnerForSegments(query, specs); }
Source:
public void testCompletingCheckoutWithEmptyCheckoutToken() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); try { buyClient.completeCheckout(paymentToken, ""); } catch (IllegalArgumentException e) { latch.countDown(); return; } latch.await(); fail("Expected an IllegalArgumentException"); }

Target:
public void testCompletingCheckoutWithEmptyCheckoutToken() throws InterruptedException { try { buyClient.completeCheckout(paymentToken, ""); } catch (IllegalArgumentException e) { return; } fail("Expected an IllegalArgumentException"); }
Source:
public static List<Person> peopleListFromJSON(JSONArray jsonArray, int localTableBlogId) { if (jsonArray == null) { return null; } ArrayList<Person> peopleList = new ArrayList<>(jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { Person person = Person.fromJSON(jsonArray.optJSONObject(i), localTableBlogId); if (person != null) { peopleList.add(person); } } return peopleList; }

Target:
private static List<Person> peopleListFromJSON(JSONArray jsonArray, int localTableBlogId) { if (jsonArray == null) { return null; } ArrayList<Person> peopleList = new ArrayList<>(jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { Person person = Person.fromJSON(jsonArray.optJSONObject(i), localTableBlogId); if (person != null) { peopleList.add(person); } } return peopleList; }
Source:
protected GitCompareInput getCompareInput(ComparisonDataSource baseData, ComparisonDataSource remoteData, ComparisonDataSource ancestorData) { return null; }

Target:
protected GitCompareInput getCompareInput(ComparisonDataSource baseData, ComparisonDataSource remoteData, ComparisonDataSource ancestorData) { throw new UnsupportedOperationException( "Compare editor for working tree files is should be opened directly from GitOpenInCompareAction"); }
Source:
public Block[] getSequenceBlocks(int start, int length) { int sequenceLength = 2 * length; BlockBuilder bucketCountsBuilder = BIGINT.createBlockBuilder(null, sequenceLength); BlockBuilder samplesBuilder = DOUBLE.createBlockBuilder(null, sequenceLength); for (int weight = 1; weight < 3; ++weight) { for (int i = start; i < start + length; i++) { BIGINT.writeLong(bucketCountsBuilder, TestReservoirAggregation.SIZE); DOUBLE.writeDouble(samplesBuilder, Double.valueOf(i)); } } return new Block[] { bucketCountsBuilder.build(), samplesBuilder.build() }; }

Target:
public Block[] getSequenceBlocks(int start, int length) { int positionCount = 2 * length; BlockBuilder samples = DOUBLE.createBlockBuilder(null, positionCount); for (int weight = 1; weight < 3; weight++) { for (int i = start; i < start + length; i++) { DOUBLE.writeDouble(samples, i); } } return new Block[] { createRLEBlock(AbstractTestReservoirAggregation.MAX_SAMPLES, positionCount), samples.build() }; }
Source:
public void verifyRecordingSingletonLatencyIsCheapWhenDisabled() throws Exception { final double maxLatencyWhenDisabledMs = 1; final double minLatencyWhenDisabledMs = 0; final long numTasks = 1000; long aggregateLatency = 0; AbfsPerfTracker abfsPerfTracker = new AbfsPerfTracker(accountName, filesystemName, false); List<Callable<Long>> tasks = new ArrayList<>(); final AbfsHttpOperation httpOperation = new AbfsHttpOperation(url, "GET", new ArrayList<>()); for (int i = 0; i < numTasks; i++) { tasks.add(() -> { Instant startRecord = Instant.now(); try (AbfsPerfInfo tracker = new AbfsPerfInfo(abfsPerfTracker, "oneOperationCaller", "oneOperationCallee")) { tracker.registerResult(httpOperation).registerSuccess(true); } long latencyRecord = Duration.between(startRecord, Instant.now()).toMillis(); LOG.debug("Spent ms in recording latency.", latencyRecord); return latencyRecord; }); } for (Future<Long> fr: executorService.invokeAll(tasks)) { aggregateLatency += fr.get(); } double averageRecordLatency = aggregateLatency/numTasks; assertThat(averageRecordLatency).describedAs("Average time for recording singleton latencies should be bounded") .isBetween(minLatencyWhenDisabledMs, maxLatencyWhenDisabledMs); }

Target:
public void verifyRecordingSingletonLatencyIsCheapWhenDisabled() throws Exception { final double maxLatencyWhenDisabledMs = 1000; final double minLatencyWhenDisabledMs = 0; final long numTasks = 1000; long aggregateLatency = 0; AbfsPerfTracker abfsPerfTracker = new AbfsPerfTracker(accountName, filesystemName, false); List<Callable<Long>> tasks = new ArrayList<>(); final AbfsHttpOperation httpOperation = new AbfsHttpOperation(url, "GET", new ArrayList<>()); for (int i = 0; i < numTasks; i++) { tasks.add(() -> { Instant startRecord = Instant.now(); try (AbfsPerfInfo tracker = new AbfsPerfInfo(abfsPerfTracker, "oneOperationCaller", "oneOperationCallee")) { tracker.registerResult(httpOperation).registerSuccess(true); } long latencyRecord = Duration.between(startRecord, Instant.now()).toMillis(); LOG.debug("Spent ms in recording latency.", latencyRecord); return latencyRecord; }); } for (Future<Long> fr: executorService.invokeAll(tasks)) { aggregateLatency += fr.get(); } double averageRecordLatency = aggregateLatency / numTasks; assertThat(averageRecordLatency).describedAs("Average time for recording singleton latencies should be bounded") .isBetween(minLatencyWhenDisabledMs, maxLatencyWhenDisabledMs); }